Ejemplo n.º 1
0
        public void Configuration_CanAdd_Editable_ToDefinition()
        {
            DefinitionElement definitionElement = new DefinitionElement {
                Name = "DefinitionTextPage"
            };

            definitionElement.Containers.Add(new ContainableElement {
                Name = "X", Type = typeof(EditableCheckBoxAttribute).AssemblyQualifiedName
            });
            var definitionCollection = new DefinitionCollection();

            definitionCollection.Add(definitionElement);

            DefinitionBuilder builder = new DefinitionBuilder(new DefinitionMap(), typeFinder, new EngineSection {
                Definitions = definitionCollection
            });

            var definitions        = builder.GetDefinitions();
            var textPageDefinition = definitions
                                     .Single(d => d.ItemType == typeof(DefinitionTextPage));

            var textEditors = textPageDefinition.Editables
                              .Where(e => e.GetType() == typeof(EditableCheckBoxAttribute));

            Assert.That(textEditors.Count(), Is.EqualTo(1));
        }
Ejemplo n.º 2
0
        public void Configuration_CanChange_Editable_OnExistingDefinition()
        {
            var definitionCollection = new DefinitionCollection();

            definitionCollection.Add(new DefinitionElement
            {
                Name      = "DefinitionTextPage",
                Editables = new ContainableCollection {
                    new ContainableElement {
                        Name  = "Title",
                        Title = "Page title in navigation",
                        Type  = typeof(EditableTextAttribute).AssemblyQualifiedName
                    }
                }
            });
            DefinitionBuilder builder = new DefinitionBuilder(new DefinitionMap(), typeFinder, new EngineSection {
                Definitions = definitionCollection
            });

            var definitions    = builder.GetDefinitions();
            var textDefinition = definitions.Single(d => d.ItemType == typeof(DefinitionTextPage));

            Assert.That(textDefinition.Editables.Any(e => e.Title == "Page title in navigation" && e.GetType() == typeof(EditableTextAttribute)));
            Assert.That(textDefinition.Editables.Any(e => e.Title == "Title" || e.GetType() == typeof(WithEditableTitleAttribute)), Is.False);
        }
Ejemplo n.º 3
0
        static GrammarCompiler()
        {
            documentParser = new Parser();

            documentParser.Lexer = new Lexer();
            documentParser.Lexer.RegexOptions           = RegexOptions.IgnoreCase | RegexOptions.Multiline;
            documentParser.Settings.RootProductionNames = new List <string>(new string[1] {
                "section"
            });
            documentParser.Lexer.Substitutions = DefinitionCollection.Parse(@"
noteol: [^\r\n];
eol: \r\n|\n\r|\r|\n|$;
");
            documentParser.Lexer.Modes.Add("default", DefinitionCollection.Parse(@"
-COMMENT: /\*[^*]*\*+(?:[^/][^*]*\*+)*/ ;
NAME : ^#[a-zA-Z]\w* ;
LONGVAL : (?:^[^#]{noteol}*{eol})+ ;
S: [ \t]+;
SPECIALCHAR: [.=] ;
SHORTVAL: {noteol}+{eol} ;
"));
            documentParser.Productions = Productions.Parse(@"
section      : name ( value | S* '=' S* value ) ;
name         : NAME;
value        : LONGVAL | SHORTVAL;
");
        }
Ejemplo n.º 4
0
        public void Configuration_CanAdd_Editable_ToExistingDefinition()
        {
            var definitionCollection = new DefinitionCollection {
                DefineUnattributedTypes = true
            };

            definitionCollection.Add(new DefinitionElement
            {
                Name      = "DefinitionTextPage",
                Editables = new ContainableCollection {
                    new ContainableElement {
                        Name  = "MetaTitle",
                        Title = "Page title",
                        Type  = typeof(N2.Details.EditableTextAttribute).AssemblyQualifiedName
                    }
                }
            });
            DefinitionBuilder builder = new DefinitionBuilder(new DefinitionMap(), typeFinder, new TransformerBase <IUniquelyNamed> [0], new EngineSection {
                Definitions = definitionCollection
            });

            var definitions    = builder.GetDefinitions();
            var textDefinition = definitions.Single(d => d.ItemType == typeof(DefinitionTextPage));

            Assert.That(textDefinition.Editables.Any(e => e.Name == "MetaTitle"));
        }
Ejemplo n.º 5
0
        public Resolver(DefinitionCollection store, IEnumerable <string> paths, bool ignoreFileCase)
        {
            if (store == null)
            {
                throw new ArgumentNullException("store");
            }
            if (paths == null)
            {
                throw new ArgumentNullException("paths");
            }
            this.store = store;

            Set <string> dp = new Set <string>();

            foreach (string p in paths)
            {
                dp.Put(Path.GetFullPath(p + Path.DirectorySeparatorChar));
            }

            this.paths = new List <string>(dp);

            if (Program.CaseSensitiveFileSystem)
            {
                parsedFiles = new Set <string>(StringComparer.Ordinal);
            }
            else
            {
                parsedFiles = new Set <string>(StringComparer.InvariantCultureIgnoreCase);
            }

            SetupVoid();

            prefetcher = new Prefetcher(ignoreFileCase);
        }
Ejemplo n.º 6
0
        public void ConfigureServices(IServiceCollection services)
        {
            services
            .AddRazorPages()
            .AddApplicationPart(Assembly.GetEntryAssembly())
            .AddApplicationPart(Assembly.GetExecutingAssembly());
            services
            .AddSignalR()
            .AddNewtonsoftJsonProtocol();

            services.AddSingleton(
                provider => new Processor.x86.CSharpExecutor.Cpu(
                    ConfigurationDto.Processor,
                    provider.GetRequiredService <IHostApplicationLifetime>().ApplicationStopping));
            services.AddSingleton(p => MethodInfoCollection.Load(ConfigurationDto.BinToCSharp));
            services.AddSingleton(
                p =>
            {
                var definitionCollection = new DefinitionCollection();
                definitionCollection.AddDefinitionsFromAssembly(typeof(Definitions).Assembly);
                return(definitionCollection);
            });
            services.AddSingleton(
                p => new RawProgramMain(
                    p.GetRequiredService <Processor.x86.CSharpExecutor.Cpu>(),
                    ConfigurationDto,
                    p.GetRequiredService <MethodInfoCollection>(),
                    p.GetRequiredService <DefinitionCollection>(),
                    p));
        }
Ejemplo n.º 7
0
        public const ushort PspSeg       = ImageLoadSeg - 16; // 0x192

        public RawProgramMain(
            Processor.x86.CSharpExecutor.Cpu implementation,
            ConfigurationDto configuration,
            MethodInfoCollection methodInfoCollection,
            DefinitionCollection definitionCollection,
            IServiceProvider serviceProvider)
            : base(implementation)
        {
            MethodInfoCollection = methodInfoCollection;
            Configuration        = configuration;
            Implementation       = implementation;
            DefinitionCollection = definitionCollection;
            ServiceProvider      = serviceProvider;

            DosMemory    = new DosMemory(implementation, this);
            DosInterrupt = new DosInterrupt(implementation, this);
            DosTimer     = new DosTimer(implementation, this);
            DosPort      = new DosPort(implementation, this);
            DosDma       = new DosDma(implementation, this);
            DosPic       = new DosPic(implementation, this);

            Implementation.MethodInfoCollection     = MethodInfoCollection;
            implementation.CompiledMethodCollection = this;
            implementation.runIrqs += (sender, args) => DosPic.RunIrqs();
            DosPort.SubscribeToCpuPortEvents();
        }
Ejemplo n.º 8
0
        private static void LoadDff()
        {
            using (new Timing("Loading DFFs into scene"))
                using (new MemoryCounter()) {
                    var itemDefinitions   = new DefinitionCollection();
                    var modelCollection   = new ModelCollection();
                    var textureCollection = new TextureCollection(true);

                    foreach (var obj in Selection.objects)
                    {
                        var objPath = AssetDatabase.GetAssetPath(obj);

                        if (objPath.EndsWith(".dff", StringComparison.OrdinalIgnoreCase))
                        {
                            var dff = new DffFile(objPath);

                            modelCollection.Add(dff);
                            itemDefinitions.Add(new ItemDefinition(dff.FileNameWithoutExtension));
                        }
                        else if (objPath.EndsWith(".txd", StringComparison.OrdinalIgnoreCase))
                        {
                            textureCollection.Add(new TxdFile(objPath));
                        }
                    }

                    using (new Loader(itemDefinitions, modelCollection, textureCollection))
                        foreach (var definition in itemDefinitions)
                        {
                            definition.GetObject(true);
                        }
                }
        }
        public void InheritanceMissing()
        {
            var cityDef = new SiteDefinition()
            {
                Name         = "City",
                Description  = "A moderate sized settlement",
                InheritsFrom = "Population Center",
            };

            cityDef.Attributes["Population"] = new AttributeDefinition()
            {
                BaseValue = "rand.Next(20000, 100000)"
            };

            IList <SiteDefinition> sites = new List <SiteDefinition>
            {
                cityDef,
            };

            var definitions = new DefinitionCollection(sites);

            int worldSeed = 915434125;

            ThingFactory factory = new ThingFactory(definitions);

            //factory.CreateSite(new Random(worldSeed), 0, 0, "City");
        }
Ejemplo n.º 10
0
        public void Configuration_CanRemove_Editable_FromDefinition()
        {
            DefinitionElement definitionElement = new DefinitionElement {
                Name = "DefinitionTextPage"
            };

            definitionElement.Containers.Remove(new ContainableElement {
                Name = "Text"
            });
            var definitionCollection = new DefinitionCollection();

            definitionCollection.Add(definitionElement);

            DefinitionBuilder builder = new DefinitionBuilder(new DefinitionMap(), typeFinder, new EngineSection {
                Definitions = definitionCollection
            });

            var definitions        = builder.GetDefinitions();
            var textPageDefinition = definitions
                                     .Single(d => d.ItemType == typeof(DefinitionTextPage));

            var textEditors = textPageDefinition.Editables
                              .Where(e => e.GetType() == typeof(EditableFreeTextAreaAttribute));

            Assert.That(textEditors.Count(), Is.EqualTo(0));
        }
Ejemplo n.º 11
0
 public FrameConstructor()
 {
     InitializeComponent();
     //
     _definitions    = new DefinitionCollection();
     _frameStructure = new Frame();
     //
     ConstructeZDataGridViewFrame(eZDataGridViewFrame);
 }
Ejemplo n.º 12
0
 public TunnelConstructor()
 {
     InitializeComponent();
     //
     _definitions     = new DefinitionCollection();
     _tunnelStructure = new Tunnel();
     //
     ConstructeZDataGridViewTunnel(eZDataGridViewTunnel);
 }
Ejemplo n.º 13
0
        public Loader(DefinitionCollection itemDefinitions, ModelCollection modelCollection, TextureCollection textureCollection)
        {
            if (Current != null)
            {
                throw new Exception("Another loader already in progress, make sure only one loader run at a time");
            }

            Current         = this;
            IdeCollection   = itemDefinitions;
            ModelCollection = modelCollection;
            TxdCollection   = textureCollection;
        }
        public void Configuration_CanAdd_Definition()
        {
            var definitionCollection = new DefinitionCollection();
            definitionCollection.Add(new DefinitionElement { Name = "DefinitionUndefined", Type = typeof(DefinitionUndefined).AssemblyQualifiedName });
            DefinitionBuilder builder = new DefinitionBuilder(new DefinitionMap(), typeFinder, new EngineSection { Definitions = definitionCollection });

            var definitions = builder.GetDefinitions();
            var undefinedDefinition = definitions
                .Single(d => d.ItemType == typeof(DefinitionUndefined));

            Assert.That(undefinedDefinition.IsDefined, Is.True);
        }
Ejemplo n.º 15
0
        public void AddLocal(Span span, IEnumerable <Definition> defs)
        {
            DefinitionCollection list;

            if (!_localDefs.TryGetValue(span, out list))
            {
                list             = new DefinitionCollection();
                _localDefs[span] = list;
            }

            list.Add(defs);
        }
Ejemplo n.º 16
0
        public void Configuration_CanRemove_Definition()
        {
            var definitionCollection = new DefinitionCollection { DefineUnattributedTypes = true };
            definitionCollection.Remove(new DefinitionElement { Name = "DefinitionTextPage" });
            DefinitionBuilder builder = new DefinitionBuilder(new DefinitionMap(), typeFinder, new TransformerBase<IUniquelyNamed>[0], new EngineSection { Definitions = definitionCollection });

            var definitions = builder.GetDefinitions();
            var textPageDefinitions = definitions
                .Where(d => d.ItemType == typeof(DefinitionTextPage));

            Assert.That(textPageDefinitions.Count(), Is.EqualTo(0));
        }
        public void Configuration_CanRemove_Definition()
        {
            var definitionCollection = new DefinitionCollection();
            definitionCollection.Remove(new DefinitionElement { Name = "DefinitionTextPage" });
            DefinitionBuilder builder = new DefinitionBuilder(typeFinder, new EngineSection { Definitions = definitionCollection });

            var definitions = builder.GetDefinitions();
            var textPageDefinitions = definitions
                .Where(d => d.ItemType == typeof(DefinitionTextPage));

            Assert.That(textPageDefinitions.Count(), Is.EqualTo(0));
        }
Ejemplo n.º 18
0
 private void ApplyFilter()
 {
     if (SourceCollection == null)
         return;
     if (currentSearch == string.Empty)
         SourceCollection = new DefinitionCollection<EntityDefinition>(SourceCollection.Definitions.ToList());
     else
     {
         var sourceCollectionFiltered = SourceCollection.Definitions.ToList().FindAll(e => e.Match(currentSearch));
         SourceCollection.ObservableDefinitions = new ObservableCollection<EntityDefinition>(sourceCollectionFiltered);
     }
     SendMessage(new Message<DefinitionCollection<EntityDefinition>> { CallbackCaller = OriginalSender, DataType = SourceCollection }, MessageToken.Search);
 }
Ejemplo n.º 19
0
        /// <summary>
        /// This is an internal helper which looks up a term/expression, parses it and
        /// returns as a list for convenience.
        /// </summary>
        private DefinitionCollection InternalGetDefinitions(string text, string database)
        {
            if (database == null || database.Length == 0)
            {
                database = "*";
            }

            string command = string.Concat("DEFINE ", database, " \"", text, "\"");

            string[]             responses      = reDefinitions.Split(ExecuteCommand(command));
            DefinitionCollection definitionList = new DefinitionCollection();


            for (int i = 0; i < responses.Length; i++)
            {
                // Split occasionally produces empty strings
                if (responses[i].Trim().Length == 0)
                {
                    continue;
                }

                StringReader rdr = new StringReader(responses[i]);

                try
                {
                    string statusLine = rdr.ReadLine();

                    // --------------------------------------------------------------------------
                    // The status line would look similar to this:
                    // "Shortcake" web1913 "Webster's Revised Unabridged Dictionary (1913)"
                    //
                    // We need to pull out the dictionary name where it was found.
                    // --------------------------------------------------------------------------
                    Match  m = reDatabase.Match(statusLine);
                    string dbName = null, dbDescription = null;
                    string termDescription = null;

                    dbName          = m.Groups[1].Value;
                    dbDescription   = m.Groups[2].Value;
                    termDescription = rdr.ReadToEnd().ToString();

                    definitionList.Add(new Definition(termDescription, new Database(dbName, dbDescription)));
                }
                finally
                {
                    rdr.Close();
                }
            }

            return(definitionList);
        }
Ejemplo n.º 20
0
 public ActionResult Save(Bam.Net.Analytics.EnglishDictionary.Definition[] values)
 {
     try
     {
         DefinitionCollection saver = new DefinitionCollection();
         saver.AddRange(values);
         saver.Save();
         return(Json(new { Success = true, Message = "", Dao = "" }));
     }
     catch (Exception ex)
     {
         return(GetErrorResult(ex));
     }
 }
Ejemplo n.º 21
0
 static EntityFactory()
 {
     definitions = new DefinitionCollection();
     constructors = new Dictionary<string, ComponentActivator>();
     foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
     {
         foreach (var type in assembly.GetTypes())
         {
             if (!type.GetInterfaces().Contains(typeof (IComponent))) continue;
             if (type.GetConstructor(Type.EmptyTypes) == null) continue;
             var ctr = Expression.New(type);
             var lambda = Expression.Lambda<ComponentActivator>(ctr).Compile();
             constructors.Add(type.Name, lambda);
         }
     }
 }
Ejemplo n.º 22
0
        public void Configuration_CanRemove_Definition()
        {
            var definitionCollection = new DefinitionCollection();

            definitionCollection.Remove(new DefinitionElement {
                Name = "DefinitionTextPage"
            });
            DefinitionBuilder builder = new DefinitionBuilder(new DefinitionMap(), typeFinder, new EngineSection {
                Definitions = definitionCollection
            });

            var definitions         = builder.GetDefinitions();
            var textPageDefinitions = definitions
                                      .Where(d => d.ItemType == typeof(DefinitionTextPage));

            Assert.That(textPageDefinitions.Count(), Is.EqualTo(0));
        }
Ejemplo n.º 23
0
        public void Configuration_CanAdd_Definition()
        {
            var definitionCollection = new DefinitionCollection();

            definitionCollection.Add(new DefinitionElement {
                Name = "DefinitionUndefined", Type = typeof(DefinitionUndefined).AssemblyQualifiedName
            });
            DefinitionBuilder builder = new DefinitionBuilder(new DefinitionMap(), typeFinder, new EngineSection {
                Definitions = definitionCollection
            });

            var definitions         = builder.GetDefinitions();
            var undefinedDefinition = definitions
                                      .Single(d => d.ItemType == typeof(DefinitionUndefined));

            Assert.That(undefinedDefinition.IsDefined, Is.True);
        }
        public void Configuration_CanAdd_Editable_ToDefinition()
        {
            DefinitionElement definitionElement = new DefinitionElement { Name = "DefinitionTextPage" };
            definitionElement.Containers.Add(new ContainableElement { Name = "X", Type = typeof(EditableCheckBoxAttribute).AssemblyQualifiedName });
            var definitionCollection = new DefinitionCollection();
            definitionCollection.Add(definitionElement);

            DefinitionBuilder builder = new DefinitionBuilder(new DefinitionMap(), typeFinder, new EngineSection { Definitions = definitionCollection });

            var definitions = builder.GetDefinitions();
            var textPageDefinition = definitions
                .Single(d => d.ItemType == typeof(DefinitionTextPage));

            var textEditors = textPageDefinition.Editables
                .Where(e => e.GetType() == typeof(EditableCheckBoxAttribute));

            Assert.That(textEditors.Count(), Is.EqualTo(1));
        }
Ejemplo n.º 25
0
        /// <summary>
        /// 将模型中的圆形隧道或者材料、截面定义信息刷新到控件中
        /// </summary>
        /// <param name="tunnel"></param>
        public void ImportTunnelOrDefinitions(Tunnel tunnel, DefinitionCollection definitions)
        {
            if (definitions != null)
            {
                _definitions = definitions;
            }
            if (tunnel != null)
            {
                _tunnelStructure = tunnel;
                TunnelPointorChanged?.Invoke(_tunnelStructure);

                // 半径与管片块数
                textBoxNum_Radius.Text   = tunnel.Radius.ToString();
                textBoxNum_Segments.Text = tunnel.SegmentNum.ToString();
                //
                RefreshUI_TunnelTable(tunnel);
            }
        }
        public void Configuration_CanAdd_Editable_ToExistingDefinition()
        {
            var definitionCollection = new DefinitionCollection();
            definitionCollection.Add(new DefinitionElement
            {
                Name = "DefinitionTextPage",
                Editables = new ContainableCollection { new ContainableElement {
                    Name = "MetaTitle",
                    Title = "Page title",
                    Type = typeof(N2.Details.EditableTextAttribute).AssemblyQualifiedName } }
            });
            DefinitionBuilder builder = new DefinitionBuilder(new DefinitionMap(), typeFinder, new EngineSection { Definitions = definitionCollection });

            var definitions = builder.GetDefinitions();
            var textDefinition = definitions.Single(d => d.ItemType == typeof(DefinitionTextPage));

            Assert.That(textDefinition.Editables.Any(e => e.Name == "MetaTitle"));
        }
        public void Configuration_CanRemove_Editable_FromDefinition()
        {
            DefinitionElement definitionElement = new DefinitionElement { Name = "DefinitionTextPage" };
            definitionElement.Containers.Remove(new ContainableElement { Name = "Text" });
            var definitionCollection = new DefinitionCollection();
            definitionCollection.Add(definitionElement);

            DefinitionBuilder builder = new DefinitionBuilder(typeFinder, new EngineSection { Definitions = definitionCollection });

            var definitions = builder.GetDefinitions();
            var textPageDefinition = definitions
                .Single(d => d.ItemType == typeof(DefinitionTextPage));

            var textEditors = textPageDefinition.Editables
                .Where(e => e.GetType() == typeof(EditableFreeTextAreaAttribute));

            Assert.That(textEditors.Count(), Is.EqualTo(0));
        }
Ejemplo n.º 28
0
        /// <summary>
        /// 将模型中的框架结构或者材料、截面定义信息刷新到控件中
        /// </summary>
        /// <param name="frame"></param>
        public void ImportFrameOrDefinitions(Frame frame, DefinitionCollection definitions)
        {
            if (definitions != null)
            {
                _definitions = definitions;
            }
            if (frame != null)
            {
                _frameStructure = frame;
                FramePointorChanged?.Invoke(_frameStructure);

                // 层高与跨度
                textBoxNum_layers.Text = frame.LayerHeights.Length.ToString();
                textBoxNum_spans.Text  = frame.SpanWidths.Length.ToString();
                //
                RefreshUI_FrameTable(frame);
            }
        }
Ejemplo n.º 29
0
        internal static void DoTranslate(IDictDServiceItem dictServiceItem, string phrase, LanguagePair languagesPair, string subject, Result result, NetworkSetting networkSetting)
        {
            ServiceItem      si = dictServiceItem as ServiceItem;
            DictionaryClient dc = null;

            try
            {
                dc = DictDClientsPool.GetPooledClient(dictServiceItem.Urls);
                DefinitionCollection definitions = dc.GetDefinitions(phrase, si.Name);
                string translation;
                if (definitions != null && definitions.Count > 0)
                {
                    foreach (Definition df in definitions)
                    {
                        translation = "html!<div style='width:{allowed_width}px;overflow:scroll;overflow-y:hidden;overflow-x:auto;'><pre>" + df.Description.Replace("\r\n", "<br />") + "&nbsp</pre></div>";
                        result.Translations.Add(translation);
                    }
                }
                else
                {
                    result.ResultNotFound = true;
                    throw new TranslationException("Nothing found");
                }
            }
            catch (DictionaryServerException e)
            {
                if (e.ErrorCode == 552)                //No definitions found
                {
                    result.ResultNotFound = true;
                    throw new TranslationException("Nothing found");
                }
                else
                {
                    throw;
                }
            }
            finally
            {
                if (dc != null)
                {
                    DictDClientsPool.PushPooledClient(dc);
                }
            }
        }
        public void Configuration_CanChange_Editable_OnExistingDefinition()
        {
            var definitionCollection = new DefinitionCollection();
            definitionCollection.Add(new DefinitionElement
            {
                Name = "DefinitionTextPage",
                Editables = new ContainableCollection { new ContainableElement {
                    Name = "Title",
                    Title = "Page title in navigation",
                    Type = typeof(EditableTextAttribute).AssemblyQualifiedName } }
            });
            DefinitionBuilder builder = new DefinitionBuilder(new DefinitionMap(), typeFinder, new EngineSection { Definitions = definitionCollection });

            var definitions = builder.GetDefinitions();
            var textDefinition = definitions.Single(d => d.ItemType == typeof(DefinitionTextPage));

            Assert.That(textDefinition.Editables.Any(e => e.Title == "Page title in navigation" && e.GetType() == typeof(EditableTextAttribute)));
            Assert.That(textDefinition.Editables.Any(e => e.Title == "Title" || e.GetType() == typeof(WithEditableTitleAttribute)), Is.False);
        }
Ejemplo n.º 31
0
        /// <inheritdoc />
        public void GetMethod(out MethodInfoDto methodInfo, out Action method)
        {
            while (true)
            {
                var fullAddress = cs[eip];
                if (fullAddress == 0)
                {
                    throw new InvalidOperationException("Запрос метода по нулевому указателю.");
                }

                var info = FindExactMethod(fullAddress);
                if (info != null)
                {
                    methodInfo = info.MethodInfo;
                    method     = info.Action;
                    return;
                }

                // Всё-таки декодируем.
                var files = DecodeCurrentMethod();

                // Compile and load.
                try
                {
                    NonBlockingConsole.WriteLine($"Компилирование новых методов.");
                    var dllPath = Compile(files);

                    NonBlockingConsole.WriteLine($"Загрузка '{dllPath}'.");
                    var assembly = Assembly.LoadFile(dllPath);

                    DefinitionCollection.AddDefinitionsFromAssembly(assembly);
                    ConnectDecodedMethods(assembly);
                }
                catch (Exception ex)
                {
                    NonBlockingConsole.WriteLine(ex);
                    throw;
                }
            }

            //throw new InvalidOperationException("Метод не найдена.");
        }
        /// <summary>
        /// Initializes the context object.
        /// </summary>
        /// <returns>THe context object.</returns>
        public static Context InitContext()
        {
            int worldSeed = 915434125;

            ConditionCompiler <BaseGlobalVariables> processor =
                new ConditionCompiler <BaseGlobalVariables>(new BaseGlobalVariables()
            {
                World = new World(),
            });
            DefinitionCollection definitions = DefinitionSerializer.DeserializeFromDirectory(processor, "Definitions");
            ThingFactory         factory     = new ThingFactory(definitions);

            HistoryGenerator history = new HistoryGenerator(factory, definitions);

            WorldGen.WorldGenerator worldGen = new WorldGen.WorldGenerator(worldSeed, factory);
            int   width  = 200;
            int   height = 200;
            World world  = worldGen.GenerateWorld(width, height);

            processor.UpdateGlobalVariables(g => g.World = world);

            Random rdm = new Random(worldSeed);

            for (int i = 0; i < 100; i++)
            {
                int  x        = rdm.Next(0, width - 1);
                int  y        = rdm.Next(0, height - 1);
                Site cityInst = factory.CreateSite(rdm, x, y, "City");
                world.Grid.AddThing(cityInst);
            }

            foreach (var thing in world.Grid.GetAllGridEntries().SelectMany(x => x.Square.GetThings()))
            {
                thing.FinalizeConstruction(new Random());
            }

            Context.Instance.Attach(history, world, processor);

            return(Context.Instance);
        }
Ejemplo n.º 33
0
        public List <Token> Tokenize(string str)
        {
            DefinitionCollection compiledSubs = Substitutions.Compile(RegexOptions);

            Dictionary <string, DefinitionCollection> compiledModes = new Dictionary <string, DefinitionCollection>();

            foreach (var mode in Modes)
            {
                compiledModes.Add(mode.Key, mode.Value.Compile(RegexOptions, compiledSubs));
            }

            List <Token>         tokens = new List <Token>();
            Token                currentToken;
            Token                lastToken = new Token(null, null, -1);
            Match                match;
            int                  strLength    = str.Length;
            int                  currentIndex = 0;
            string               defaultMode  = DefaultMode ?? compiledModes.First().Key;
            DefinitionCollection currentMode  = compiledModes[defaultMode];

            while (strLength >= currentIndex && (match = currentMode.RegexInfo.Tokenizer.Match(str, currentIndex)).Success)
            {
                currentToken = match.Groups.Cast <Group>()
                               .Select((g, i) => new { Group = g, Index = i })
                               .Where((g => g.Group.Success && currentMode.RegexInfo.GroupNames.ContainsKey(g.Index)))
                               .Select(g => new Token(currentMode[currentMode.RegexInfo.GroupNames[g.Index]], g.Group.Value, match.Index))
                               .FirstOrDefault();

                if (!currentToken.TokenType.IsIgnored)
                {
                    lastToken.Next = currentToken;
                    tokens.Add(currentToken);
                    lastToken = currentToken;
                }

                currentIndex = match.Index + match.Length;
            }

            return(tokens);
        }
Ejemplo n.º 34
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ThingFactory"/> class.
 /// </summary>
 /// <param name="definitions">The definitions.</param>
 public ThingFactory(
     DefinitionCollection definitions)
 {
     this.Definitions = definitions;
     this.Definitions.CompileInheritance();
 }
Ejemplo n.º 35
0
        static private void ProcessSection(SyntaxNode section, Parser parser)
        {
            if (section.Rule.ProductionName != "section")
            {
                throw Exceptions.InvalidSyntaxException(section, "section");
            }

            string name  = null;
            string value = null;

            foreach (SyntaxNode node in section)
            {
                switch (node.Rule.ProductionName)
                {
                case "name":
                    name = node.StartToken.Text.Trim();
                    break;

                case "value":
                    value = node.StartToken.Text.Trim();
                    break;
                }
            }

            switch (name)
            {
            case "#AlternateCritera":
                parser.Settings.AlternateCritera = (ParserSettings.SelectionCriteria)
                                                   Enum.Parse(typeof(ParserSettings.SelectionCriteria), value);
                break;

            case "#RootProductionNames":
                parser.Settings.RootProductionNames = new List <string>(
                    Regex.Split(value, @"\s*,\s*"));
                break;

            case "#ZeroLengthRulesOK":
                // boolean.parse wasn't working.
                parser.Settings.ZeroLengthRulesOK =
                    Regex.Match(value, @"\btrue\b", RegexOptions.IgnoreCase).Success;
                break;

            case "#RegexOptions":
                parser.Lexer.RegexOptions = RegexOptions.None;
                if (value.Contains("x"))
                {
                    parser.Lexer.RegexOptions |= RegexOptions.IgnorePatternWhitespace;
                }
                if (value.Contains("i"))
                {
                    parser.Lexer.RegexOptions |= RegexOptions.IgnoreCase;
                }
                if (value.Contains("m"))
                {
                    parser.Lexer.RegexOptions |= RegexOptions.Multiline;
                }
                if (value.Contains("s"))
                {
                    parser.Lexer.RegexOptions |= RegexOptions.Singleline;
                }
                if (value.Contains("n"))
                {
                    parser.Lexer.RegexOptions |= RegexOptions.ExplicitCapture;
                }
                if (value.Contains("r"))
                {
                    parser.Lexer.RegexOptions |= RegexOptions.RightToLeft;
                }
                if (value.Contains("none"))
                {
                    parser.Lexer.RegexOptions = RegexOptions.None;
                }
                break;

            case "#TokenSubs":
                parser.Lexer.Substitutions = DefinitionCollection.Parse(value);
                break;

            case "#Tokens":
                parser.Lexer.Modes.Clear();
                parser.Lexer.Modes.Add("default", DefinitionCollection.Parse(value));
                break;

            case "#Productions":
                parser.Productions = Productions.Parse(value);
                break;
            }
        }
Ejemplo n.º 36
0
        /// <summary>
        /// This is an internal helper which looks up a term/expression, parses it and 
        /// returns as a list for convenience.
        /// </summary>
        private DefinitionCollection InternalGetDefinitions(string text, string database)
        {
            if (database == null || database.Length == 0)
                database = "*";

            string                  command = string.Concat ("DEFINE ", database, " \"", text, "\"");
            string[]                responses = reDefinitions.Split(ExecuteCommand (command));
            DefinitionCollection    definitionList = new DefinitionCollection ();

            for (int i=0; i<responses.Length; i++)
            {
                // Split occasionally produces empty strings
                if (responses[i].Trim().Length == 0)
                    continue;

                StringReader rdr = new StringReader (responses[i]);

                try
                {
                    string statusLine = rdr.ReadLine ();

                    // --------------------------------------------------------------------------
                    // The status line would look similar to this:
                    // "Shortcake" web1913 "Webster's Revised Unabridged Dictionary (1913)"
                    //
                    // We need to pull out the dictionary name where it was found.
                    // --------------------------------------------------------------------------
                    Match       m = reDatabase.Match (statusLine);
                    string      dbName = null, dbDescription = null;
                    string      termDescription = null;

                    dbName              = m.Groups[1].Value;
                    dbDescription       = m.Groups[2].Value;
                    termDescription     = rdr.ReadToEnd ().ToString ();

                    definitionList.Add (new Definition (termDescription, new Database (dbName, dbDescription)));
                }
                finally
                {
                    rdr.Close ();
                }
            }

            return definitionList;
        }
Ejemplo n.º 37
0
 protected Generator(IEnumerable <string> paths, bool ignoreFileCase)
 {
     store    = new DefinitionCollection();
     resolver = new Resolver(store, paths, ignoreFileCase);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="HistoryGenerator"/> class.
 /// </summary>
 /// <param name="definitions">The definitions collection to use.</param>
 public HistoryGenerator(DefinitionCollection definitions)
 {
     this.definitions  = definitions;
     this.thingFactory = new ThingFactory(definitions);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="HistoryGenerator"/> class.
 /// </summary>
 /// <param name="thingFactory">The thing factory to use.</param>
 /// <param name="definitions">The definitions collection to use.</param>
 public HistoryGenerator(ThingFactory thingFactory, DefinitionCollection definitions)
 {
     this.definitions  = definitions;
     this.thingFactory = thingFactory;
 }
        public void Happypath()
        {
            var popCenter = new SiteDefinition()
            {
                Name        = "Population Center",
                Description = "A center of population.",
            };

            popCenter.Attributes["Evil"] = new AttributeDefinition()
            {
                BaseValue = "Rand.Next(-5, 5)"
            };
            popCenter.Attributes["Population"] = new AttributeDefinition()
            {
                BaseValue = "Rand.Next(0, 1000000)"
            };

            var cityDef = new SiteDefinition()
            {
                Name         = "City",
                Description  = "A moderate sized settlement",
                InheritsFrom = "Population Center",
            };

            cityDef.Attributes["Population"] = new AttributeDefinition()
            {
                BaseValue = "Rand.Next(20000, 100000)"
            };

            IList <SiteDefinition> sites = new List <SiteDefinition>
            {
                popCenter,
                cityDef,
            };

            var definitions = new DefinitionCollection(sites);

            int    worldSeed = 915434125;
            Random rdm       = new Random(worldSeed);

            ConditionCompiler <BaseGlobalVariables> processor = new ConditionCompiler <BaseGlobalVariables>(new BaseGlobalVariables()
            {
                World = new Contracts.World(),
            });

            definitions.Attach(processor);
            ThingFactory factory = new ThingFactory(definitions);

            for (int i = 0; i < 100; i++)
            {
                Site city = factory.CreateSite(rdm, 0, 0, "City");
                city.FinalizeConstruction(rdm);
                Console.WriteLine($"City created: {city.EffectiveAttribute("Population")} {city.EffectiveAttribute("Evil")}");

                Assert.AreEqual(ThingType.Site, city.ThingType);
                Assert.AreEqual(cityDef, city.Definition);
                int population = city.EffectiveAttribute("Population");
                Assert.IsTrue(population <= 100000);
                Assert.IsTrue(population >= 20000);
                int evil = city.EffectiveAttribute("Evil");
                Assert.IsTrue(evil <= 5);
                Assert.IsTrue(evil >= -5);
            }
        }
Ejemplo n.º 41
0
 private void ManageDataResult(object data)
 {
     var entities = (List<EntityDefinition>)data;
     EntityCollection = new DefinitionCollection<EntityDefinition>(entities);
     SendMessage(new Message<DefinitionCollection<EntityDefinition>> { DataType = EntityCollection }, MessageToken.Main);
 }