public void ParseTest()
 {
     {
         var math = new TreeParser("0-5*2/2*8");
         math.Parse();
         var result = math.JoinTreeAsString();
         Assert.AreEqual("END-*8/2*250", result);
     }
     {
         var math = new TreeParser("0-5*2/2*12");
         math.Parse();
         var result = math.JoinTreeAsString();
         Assert.AreEqual("END-*12/2*250", result);
     }
     {
         var math = new TreeParser("0-Cos(2.43-18.3+8*2/3-24.1)-Cos(12*3)");
         math.Parse();
         var result = math.JoinTreeAsString();
         Assert.AreEqual("END-Cos*312-Cos-24.1+/3*28-18.32.430", result);
     }
     {
         var math = new TreeParser("0-Pow(12*3,1+1)");
         math.Parse();
         var result = math.JoinTreeAsString();
         Assert.AreEqual("END-Pow,+11*3120", result);
     }
 }
        public void Simplification_WithCos_Test()
        {
            {
                var math = new TreeParser("0-8/Cos(1)/4");
                math.Parse();
                math.Simplification();
                var res = math.ReparseTree();
                Assert.AreEqual("0-3.70163143536185", res);
            }

            {
                var math = new TreeParser("0-8/Cos(1)*4");
                math.Parse();
                math.Simplification();
                var res = math.ReparseTree();
                Assert.AreEqual("0-59.2261029657896", res);
            }

            {
                var math = new TreeParser("0-8*Cos(1)/4");
                math.Parse();
                math.Simplification();
                var res = math.ReparseTree();
                Assert.AreEqual("0-1.08060461173628", res);
            }

            {
                var math = new TreeParser("0-8*Cos(1)*4");
                math.Parse();
                math.Simplification();
                var res = math.ReparseTree();
                Assert.AreEqual("0-17.2896737877805", res);
            }
        }
        public void Simplification_LowPriorityOperations_Test()
        {
            {
                var math = new TreeParser("0-8-2-4");
                math.Parse();
                math.Simplification();
                var res = math.ReparseTree();
                Assert.AreEqual("0-14", res);
            }

            {
                var math = new TreeParser("0-8-2+4");
                math.Parse();
                math.Simplification();
                var res = math.ReparseTree();
                Assert.AreEqual("0-6", res);
            }

            {
                var math = new TreeParser("0+8+2+4");
                math.Parse();
                math.Simplification();
                var res = math.ReparseTree();
                Assert.AreEqual("0+14", res);
            }

            {
                var math = new TreeParser("0+8+2-4");
                math.Parse();
                math.Simplification();
                var res = math.ReparseTree();
                Assert.AreEqual("0+6", res);
            }
        }
        public void NormalUseCases(string input, string output)
        {
            var parser = new TreeParser();
            var tree   = parser.Parse(input);

            Assert.Equal(output, tree.ToString());
        }
        public void Simplification_HighPriopityOperations_Test()
        {
            {
                var math = new TreeParser("0-8/2/4");
                math.Parse();
                math.Simplification();
                var res = math.ReparseTree();
                Assert.AreEqual("0-1", res);
            }

            {
                var math = new TreeParser("0-8/2*4");
                math.Parse();
                math.Simplification();
                var res = math.ReparseTree();
                Assert.AreEqual("0-16", res);
            }

            {
                var math = new TreeParser("0-8*2*4");
                math.Parse();
                math.Simplification();
                var res = math.ReparseTree();
                Assert.AreEqual("0-64", res);
            }

            {
                var math = new TreeParser("0-8*2/4");
                math.Parse();
                math.Simplification();
                var res = math.ReparseTree();
                Assert.AreEqual("0-4", res);
            }
        }
Exemple #6
0
        public void Simplification(Log?log = null, bool swapConstantsToLeaf = true)
        {
            if (LeafsCount > 0)
            {
                for (var i = 0; i < LeafsCount; i++)
                {
                    Genotype = Genotype.Replace("Leaf[" + i + "]", SurvivalRate.Constants[i].ToString(CultureInfo.InvariantCulture));
                }

                Genotype = Genotype.Replace("+-", "-").Replace("--", "+");
            }
            var synanthicTree = new TreeParser(Genotype);

            synanthicTree.Parse();
            synanthicTree.Simplification();
            if (swapConstantsToLeaf)
            {
                SurvivalRate.Constants = synanthicTree.ChangeConstantsToLeaf();
            }
            LeafsCount = SurvivalRate.Constants.Length;
            string simlificated = synanthicTree.ReparseTree();

            Genotype = simlificated;

            if (log == null)
            {
                return;
            }
            ((Log)log).Simplification.Add(":Gen: " + Genotype);
            ((Log)log).Simplification.Add(":End: " + Genotype);
        }
        public void Simplification_WithArg_Test()
        {
            {
                var math = new TreeParser("0-8/Arg[0,n]/4");
                math.Parse();
                math.Simplification();
                var res = math.ReparseTree();
                Assert.AreEqual("0-2/Arg[0,n]", res);
            }

            {
                var math = new TreeParser("0-8*Arg[0,n]/4");
                math.Parse();
                math.Simplification();
                var res = math.ReparseTree();
                Assert.AreEqual("0-2*Arg[0,n]", res);
            }

            {
                var math = new TreeParser("0-8*Arg[0,n]*4");
                math.Parse();
                math.Simplification();
                var res = math.ReparseTree();
                Assert.AreEqual("0-32*Arg[0,n]", res);
            }

            {
                var math = new TreeParser("0-8/Arg[0,n]*4");
                math.Parse();
                math.Simplification();
                var res = math.ReparseTree();
                Assert.AreEqual("0-32/Arg[0,n]", res);
            }
        }
Exemple #8
0
        public static TreeNode GetTreeFromString(string treeStr)
        {
            StreamReader stream = Utils.GenerateStreamFromString(treeStr);
            TreeParser   parser = new TreeParser(stream);
            TreeNode     tree   = parser.ParseTree();

            return(tree);
        }
Exemple #9
0
        public void TestValid4()
        {
            StreamReader stream = Utils.GenerateStreamFromString(exampleTreeWithWhitespace);
            TreeParser   parser = new TreeParser(stream);
            TreeNode     tree   = parser.ParseTree();

            Assert.IsTrue(parser.IsParsedTreeValid());
        }
Exemple #10
0
        public void TestValid5()
        {
            StreamReader stream = Utils.GenerateStreamFromString(exampleTree + " ( ) ");
            TreeParser   parser = new TreeParser(stream);
            TreeNode     tree   = parser.ParseTree();

            Assert.IsFalse(parser.IsParsedTreeValid());
        }
Exemple #11
0
        public void TestValid2()
        {
            string       treeStr = "  sf as ";
            StreamReader stream  = Utils.GenerateStreamFromString(treeStr);
            TreeParser   parser  = new TreeParser(stream);
            TreeNode     tree    = parser.ParseTree();

            Assert.IsTrue(parser.IsParsedTreeValid());
        }
        /// <summary>
        /// Convert the parsed tree into the specified type.
        /// </summary>
        /// <typeparam name="T">The type to convert to.</typeparam>
        /// <param name="treeConnectors">Custom connectors to use for attaching edges and vertices.</param>
        /// <returns></returns>
        public T[] ToObject <T>(IEnumerable <ITreeConnector> treeConnectors = null)
            where T : IVertex
        {
            var parser = new TreeParser(treeConnectors ?? Enumerable.Empty <ITreeConnector>());

            var vertices = RootVertexNodes.Select(n => parser.GetVertex(n, typeof(T))).Cast <T>();

            return(vertices.ToArray());
        }
Exemple #13
0
        public void ParserBaseTest()
        {
            string source = "A((B(,),C(,)";
            CompilationErrorManager em = new CompilationErrorManager();

            var parser = new TreeParser(em);

            var result = parser.Parse(source);

            ;
        }
Exemple #14
0
        public void ParserBaseTest()
        {
            string source              = "A((B(,),C(,)";
            string correct             = "A(B(,),C(,))";
            CompilationErrorManager em = new CompilationErrorManager();

            var parser = new TreeParser(em);

            var result = parser.Parse(source, em.CreateErrorList());

            Assert.AreEqual(correct, result.ToString());
        }
Exemple #15
0
        public void Test3()
        {
            var          str            = string.Format("{0}", 23.0);
            string       file           = resourcesFilePath + "TemplateTest3.test";
            CodeTemplate template       = (new CodeTemplate(file)).ReadTemplate();
            TreeParser   parser         = new TreeParser();
            var          res            = parser.PraseTemplate(template);
            string       outputFilePath = @"C:/Users/ITQ2CS/rtc_sandbox/rbd_briBk10_gly_sw_Development_RWS_Hansong_Dev/rbd/briBk10/gly/sw/01_ApplLyr/SysCtrl/ComWrp/src/ComWrp_ComWrapper_cc.c";

            File.WriteAllText(outputFilePath, res.ToString());
            Assert.Equal(1, template.Root.ChildNodeList.Count);
            Assert.Equal(3, template.Root.ChildNodeList[0].ChildNodeList.Count);
        }
Exemple #16
0
        public void Should_Return_Simple_Tree()
        {
            var tokens = new List <IToken>()
            {
                new NumberToken("1"),
                new NumberToken("2"),
                new OperatorToken("+", 10)
            };

            var treeBuilder = new TreeParser();
            var root        = treeBuilder.Build(tokens);

            Assert.Equal(tokens[2], root.Value);
            Assert.Equal(tokens[0], root.Children.First.Value.Value);
            Assert.Equal(tokens[1], root.Children.Last.Value.Value);
        }
Exemple #17
0
        public void Test4()
        {
            string file = resourcesFilePath + "TemplateTest4.test";

            try
            {
                CodeTemplate template       = (new CodeTemplate(file)).ReadTemplate();
                TreeParser   parser         = new TreeParser();
                var          res            = parser.PraseTemplate(template);
                string       outputFilePath = @"C:/Users/ITQ2CS/rtc_sandbox/rbd_briBk10_gly_sw_Development_RWS_Hansong_Dev/rbd/briBk10/gly/sw/01_ApplLyr/SysCtrl/ADtRp/src/ADtRp_Report_cc.c";
                File.WriteAllText(outputFilePath, res.ToString());
                Assert.Equal(1, template.Root.ChildNodeList.Count);
                Assert.Equal(3, template.Root.ChildNodeList[0].ChildNodeList.Count);
            }
            catch (Exception e)
            {
            }
        }
Exemple #18
0
        public void Tree()
        {
            var parser = new TreeParser <Node, int>();
            var path   = Path.Combine(TestContext.CurrentContext.TestDirectory, "input.txt");
            var tree   = parser.Parse(path, canHaveMultipleParents: true);

            bool isOptimalPath(List <INode <int> > l1, List <INode <int> > l2) => l1.Sum(w => w.Value) > l2.Sum(w => w.Value);

            bool canTraverse(INode <int> n1, INode <int> n2)
            {
                var n1IsEven = n1.Value % 2 == 0;
                var n2IsEven = n2.Value % 2 == 0;

                return(n1IsEven && !n2IsEven || !n1IsEven && n2IsEven);
            }

            tree.Traverse(isOptimalPath, canTraverse);
            Console.WriteLine($"(Sum: {tree.CurrentOptimalPath.Sum(s => s.Value)}) { string.Join(" ", tree.CurrentOptimalPath.Select(s => s.Value.ToString()))}");
        }
Exemple #19
0
        static void Main(string[] args)
        {
            //string l_str = Console.ReadLine();
            //Console.WriteLine(l_str);
            string     l_str    = "E:\\Work\\LuaUnity\\Assets\\Lua\\View\\Intents\\AdventureIntent.lua";
            TreeParser l_parser = new TreeParser();

            l_parser.ParseFile(l_str);

            for (int i = 0; i < l_parser.File.Tokens.Count; i++)
            {
                var l_token = l_parser.File.Tokens[i];
                Console.WriteLine(l_token.ToString());
            }

            Console.WriteLine("Press enter to exit.");
            Console.ReadLine();
            return;
        }
Exemple #20
0
        public async ValueTask <IQsiAnalysisResult> Execute(QsiScript script, CancellationToken cancellationToken = default)
        {
            var tree = TreeParser.Parse(script, cancellationToken);

            var options  = LanguageService.CreateAnalyzerOptions();
            var analyzer = _analyzers.Value.FirstOrDefault(a => a.CanExecute(script, tree));

            if (analyzer == null)
            {
                if (script.ScriptType == QsiScriptType.Comment || script.ScriptType == QsiScriptType.Delimiter)
                {
                    return(new EmptyAnalysisResult());
                }

                throw new QsiException(QsiError.NotSupportedScript, script.ScriptType);
            }

            return(await analyzer.Execute(script, tree, options, cancellationToken));
        }
Exemple #21
0
        public void Should_Return_Advanced_Tree()
        {
            var tokens = new List <IToken>()
            {
                new NumberToken("1"),
                new NumberToken("1"),
                new OperatorToken("=", 10),
                new NumberToken("2"),
                new NumberToken("2"),
                new OperatorToken("=", 10),
                new OperatorToken("and", 5)
            };

            var treeBuilder = new TreeParser();
            var root        = treeBuilder.Build(tokens);

            Assert.Equal(tokens[6], root.Value);
            Assert.Equal(tokens[2], root.Children.ElementAt(0).Value);
            Assert.Equal(tokens[5], root.Children.ElementAt(1).Value);
        }
Exemple #22
0
        private TTree ParseTree <TTree>(TTree result, Type classType, string input)
            where TTree : ExpressionTree
        {
            var tree = new TreeParser().Parse(input);

            foreach (var subTree in tree.Children)
            {
                //skip node
                if (subTree.Node == "collection" && classType.GetProperty(subTree.Node) == null)
                {
                    var selectionType = typeof(ISelection <>).MakeGenericType(new[] { classType });
                    result.Children.AddRange(subTree.Children.Select(c => Parse(selectionType, c)));
                }
                else
                {
                    result.Children.Add(Parse(classType, subTree));
                }
            }

            return(result);
        }
Exemple #23
0
    /// <summary>
    /// Default constructor, creates an ExpressionParser object
    /// </summary>
    public ExpressionParser()
    {
        // Cache for values and expressions
        Values      = new ValuesDictionary();
        Expressions = new ExpressionDictionary();

        // Add all valid operators.
        DefaultOperators operators = new();

        ops = new Dictionary <string, Operator>();

        foreach (Operator op in operators.Operators)
        {
            string symbol = op.Symbol;
            if (symbol.Length > maxoplength)
            {
                maxoplength = symbol.Length;
            }

            ops.Add(symbol, op);
        }

        // Constants
        spconst = new Dictionary <string, double>();
        spconst.Add("euler", Math.E);
        spconst.Add("pi", Math.PI);
        spconst.Add("nan", double.NaN);
        spconst.Add("infinity", double.PositiveInfinity);
        spconst.Add("true", 1D);
        spconst.Add("false", 0D);

        treeParser = new TreeParser(ops, spconst)
        {
            ImplicitMultiplication = true,
            RequireParentheses     = true
        };

        Culture = CultureInfo.InvariantCulture;
    }
        public void Simplification_Common_Test()
        {
            {
                var math = new TreeParser("0-5*2");
                math.Parse();
                math.Simplification();
                var res2 = math.ReparseTree();
                Assert.AreEqual("0-10", res2);
            }
            {
                var math = new TreeParser("0-Cos(0)");
                math.Parse();
                math.Simplification();
                var res = math.ReparseTree();
                Assert.AreEqual("0-1", res);
            }
            {
                var math = new TreeParser("0-Pow(2,2)");
                math.Parse();
                math.Simplification();
                var res = math.ReparseTree();
                Assert.AreEqual("0-4", res);
            }
            {
                var math = new TreeParser("0-Pow(2,2)+12-10");
                math.Parse();
                math.Simplification();
                var res = math.ReparseTree();
                Assert.AreEqual("0-2", res);
            }

            {
                var math = new TreeParser("0-Pow(Arg[0,n],2)+12-10");
                math.Parse();
                math.Simplification();
                var res = math.ReparseTree();
                Assert.AreEqual("0-Pow(Arg[0,n],2)+2", res);
            }
        }
 public TreeParserContentTests()
 {
     treeParser = ConfigureDi.Services.GetRequiredService <TreeParser>();
 }
        public void FailedCases(string input)
        {
            var parser = new TreeParser();

            Assert.Throws <FormatException>(() => parser.Parse(input));
        }
Exemple #27
0
        public List <TreeNode> GetContentAsTree(string csprojPath)
        {
            var includes = GetContentIncludes(csprojPath);

            return(TreeParser.GetContentAsTree(includes));
        }
Exemple #28
0
 /** Check if current node in input has a context.  Context means sequence
  *  of nodes towards root of tree.  For example, you might say context
  *  is "MULT" which means my parent must be MULT.  "CLASS VARDEF" says
  *  current node must be child of a VARDEF and whose parent is a CLASS node.
  *  You can use "..." to mean zero-or-more nodes.  "METHOD ... VARDEF"
  *  means my parent is VARDEF and somewhere above that is a METHOD node.
  *  The first node in the context is not necessarily the root.  The context
  *  matcher stops matching and returns true when it runs out of context.
  *  There is no way to force the first node to be the root.
  */
 public static bool InContext(this TreeParser parser, string context)
 {
     return(InContext(parser.GetTreeNodeStream().TreeAdaptor, parser.TokenNames, parser.GetTreeNodeStream().LT(1), context));
 }
Exemple #29
0
        /// <summary>
        ///     Compares the created entities to the entities in the given Table.
        /// </summary>
        /// <param name="table">
        ///     The table.
        /// </param>
        /// <returns>
        ///     The <see cref="System.Collections.Generic.List{T}" />.
        /// </returns>
        /// <exception cref="Exception">
        ///     The exception.
        /// </exception>
        public List <T> Execute(Table table)
        {
            if ((this.lookupProperties == null) || !this.lookupProperties.Any())
            {
                throw new Exception("No lookup properties provided for Then clause.");
            }

            var parsedTree        = new TreeParser(table, this.collectionIncludes.GetHierarchyPropertyNames()).Parse();
            var propertiesToCheck = this.GeneratePropertiesToCheck(table.Header);
            var foundEntities     = new List <T>();
            var entityDictionary  = new Dictionary <int, object>();

            for (var i = 0; i < table.RowCount; i++)
            {
                if (parsedTree[i].HierarchyLevel != 0)
                {
                    continue;
                }

                var entity = (T)Helpers.CreateInstance(table, table.Rows[i], typeof(T));

                // Set Default values
                foreach (var lookupProperty in this.lookupProperties)
                {
                    if (lookupProperty.DefaultValue != null)
                    {
                        ClausesHelper.SetPropertiesValues(
                            entity,
                            new Tuple <object, object>(lookupProperty.LookupExpression, lookupProperty.DefaultValue),
                            false);
                    }
                }

                var            lookupExpression = this.BuildLookupExpression(entity);
                IQueryable <T> query            = this.dbContext.Set <T>();
                query = this.AddIncludes(query);
                var foundEntity = query.FirstOrDefault(lookupExpression);

                if (foundEntity == null)
                {
                    throw new Exception("Entity not found at row :" + i);
                }

                this.CheckEntity(entity, foundEntity, propertiesToCheck);

                foundEntities.Add(foundEntity);
                entityDictionary.Add(i, foundEntity);

                this.CheckIncludedCollections1(foundEntity, table, table.Rows[i]);
            }

            // Resto de la jerarquia + collectionincludes
            var maxHierarchyLevel = parsedTree.Max(x => x.Value.HierarchyLevel);

            for (var hierarchyLevel = 1; hierarchyLevel <= maxHierarchyLevel; hierarchyLevel++)
            {
                var indexes =
                    parsedTree.Where(x => x.Value.HierarchyLevel == hierarchyLevel).Select(x => x.Key).ToList();

                for (var i = 0; i < table.RowCount; i++)
                {
                    if (!indexes.Contains(i))
                    {
                        continue;
                    }

                    var rowInfo = parsedTree[i];

                    // Look for the parent entity
                    var parentRowInfo = rowInfo.Parent;
                    var parentIndex   = parsedTree.Single(x => x.Value == parentRowInfo).Key;
                    var parentEntity  = entityDictionary[parentIndex];

                    this.CheckIncludedCollections2((T)parentEntity, table.Rows[i], table.Header, rowInfo.RowKey);
                }
            }

            return(foundEntities);
        }