Пример #1
0
        private static void GrammarParsingTest()
        {
            var grammar = Grammar.Create();
            var test    = @"
INT    := ""\b\d+\b"";
OP     := ""[+\-*/]"";
OPAREN := ""\("";
CPAREN := ""\)"";

---

EXPR := OPAREN EXPR CPAREN OP EXPR;
EXPR := INT OP EXPR;
EXPR := OPAREN EXPR CPAREN;
EXPR := INT;

> EXPR;
";
            var tokens  = grammar.Tokenize(test);

            Console.WriteLine(string.Join("\n", tokens));

            var result = grammar.Parse(tokens);

            if (result != null)
            {
                var printer = new PrintVisitor <GrammarToken, GrammarSymbol>();
                printer.Visit(result);
            }

            Console.WriteLine("Now running the resultin grammar:");

            var reader        = new Reader();
            var resultGrammar = reader.Read(result);

            var test2 = "(4 + (2 * 8)) / (6 - 1)";

            Console.WriteLine("Input: " + test2);

            var tokens2 = resultGrammar.Tokenize(test2);

            Console.WriteLine(string.Join("\n", tokens2));

            var result2 = resultGrammar.Parse(tokens2);

            if (result2 != null)
            {
                var printer = new PrintVisitor <string, string>();
                printer.Visit(result2);
            }
        }
Пример #2
0
            public void VisitConditionalExpr(bool condition, int thenValue, int elseValue, string expected)
            {
                var target = new PrintVisitor();

                var conditionExpression = new ConstantExpr(condition);
                var thenExpression      = new ConstantExpr(thenValue);
                var elseExpression      = new ConstantExpr(elseValue);

                var expr = new ConditionalExpr(conditionExpression, thenExpression, elseExpression);

                var actual = target.Visit(expr, scope);

                Assert.AreEqual(expected, actual);
            }
Пример #3
0
        public void Test()
        {
            var visitor = new PrintVisitor();

            var e1 = new E1();
            var r1 = e1.Accept(visitor);

            Assert.Equal("e1", r1);

            var e2 = new E2();
            var r2 = e2.Accept(visitor);

            Assert.Equal("e1", r1);
        }
Пример #4
0
            public void VisitMassEnergyEquavalenceExpressionTree()
            {
                var target = new PrintVisitor();

                var e   = new IdentifierExpr("e");
                var m   = new IdentifierExpr("m");
                var c   = new IdentifierExpr("C");
                var two = new ConstantExpr(2);

                var expression = new AssignmentExpr(e, new MultExpr(m, new PowExpr(c, two)));

                var actual = target.Visit(expression, scope);

                Assert.AreEqual("e=m*C^2", actual);
            }
Пример #5
0
            public void VisitMathExpressionTree()
            {
                var target = new PrintVisitor();

                var one   = new ConstantExpr(1);
                var two   = new ConstantExpr(2);
                var three = new ConstantExpr(3);
                var four  = new ConstantExpr(4);
                var five  = new ConstantExpr(5);
                var six   = new ConstantExpr(6);

                var expression = new DivExpr(new MultExpr(three, six), new MultExpr(new MinusExpr(five, one), new PlusExpr(four, two)));

                var actual = target.Visit(expression, scope);

                Assert.AreEqual("3*6/5-1*4+2", actual);
            }
Пример #6
0
        static void Main(string[] args)
        {
            Directory root                = new Directory("ROOT");
            Directory leftDirectory       = new Directory("LEFT_DIR");
            Directory leftleftDirectory   = new Directory("LEFT_LEFT_DIR");
            Directory rightDirectory      = new Directory("RIGHT_DIR");
            Directory rightleftDirectory  = new Directory("RIGHT_LEFT_DIR");
            Directory rightrightDirectory = new Directory("RIGHT_RIGHT_DIR");

            rightrightDirectory.Add(GenerateRave(3));
            rightleftDirectory.Add(GenerateRave(4));
            rightDirectory.Add(GenerateRave(2));
            leftleftDirectory.Add(GenerateRave(5));
            leftDirectory.Add(GenerateRave(1));

            #region Connections

            leftleftDirectory.Add(leftDirectory);

            rightDirectory.Add(rightrightDirectory);
            rightDirectory.Add(rightleftDirectory);

            root.Add(leftDirectory);
            root.Add(rightDirectory);

            #endregion


            PrintVisitor print = new PrintVisitor();
            //print.visit(root);

            //Serialize(root, "dir");

            var t = Deserialize <Directory>("dir");
            print.visit(t);
            //Console.WriteLine("{0,10}", "ttt");
            //using (var stream = System.IO.File.Open($"../../dirxml", FileMode.OpenOrCreate))
            //{
            //    XmlSerializer xml = new XmlSerializer(typeof());
            //    xml.Serialize(stream, xml);
            //}

            Console.ReadKey();
        }
Пример #7
0
        static void Main()
        {
            string  rules = "COS333 L2 L2 L2 L2 L2 M25 (L40 T60 ) L10 E55 (L28 T73 ) ";
            Context context;

            Console.WriteLine(rules + "\n");
            context = new Context(rules);
            Element course = new Course(context);

            course.Parse(context);
            PrintVisitor visitor = new PrintVisitor();

            Console.WriteLine("Visitor 1 - Course structure");
            visitor.Print(course);
            StructureVisitor visitor2 = new StructureVisitor();

            visitor2.Summarize(course);
            Console.WriteLine("\n\nVisitor 2 - Summing the weights\nLabs " + visitor2.Lab + "% and Tests " + visitor2.Test + "%");
        }
Пример #8
0
            public void NoneShouldThrowNotImplementedException()
            {
                var visitMethods = from method in typeof(PrintVisitor).GetMethods()
                                   where method.Name == "Visit"
                                   select method;

                var target = new PrintVisitor();

                var errors = new List <string>();

                foreach (var method in visitMethods)
                {
                    var parameter = (from param in method.GetParameters()
                                     where typeof(Expression).IsAssignableFrom(param.ParameterType)
                                     select param).First();

                    try
                    {
                        method.Invoke(target, new object[] { null, null });
                    }
                    catch (TargetParameterCountException)
                    {
                        Assert.Fail("Parameter Count Error in Reflection Call.");
                    }
                    catch (Exception e)
                    {
                        if (e is NotImplementedException || e.InnerException is NotImplementedException)
                        {
                            // Not implemented! This is unacceptable!
                            errors.Add(string.Format("Unimplemented Visit method for type {0} found.",
                                                     parameter.ParameterType.FullName));
                        }

                        // all other exception types are fine as we are passing null to the methods. We would expect them to throw.
                    }
                }

                if (errors.Any())
                {
                    string message = string.Join("\r\n", errors.ToArray());
                    Assert.Fail(message);
                }
            }
Пример #9
0
            public void NoneShouldThrowNotImplementedException()
            {
                var visitMethods = from method in typeof(PrintVisitor).GetMethods()
                                   where method.Name == "Visit"
                                   select method;

                var target = new PrintVisitor();

                var errors = new List<string>();
                foreach (var method in visitMethods)
                {
                    var parameter = (from param in method.GetParameters()
                        where typeof (Expression).IsAssignableFrom(param.ParameterType)
                        select param).First();

                    try
                    {
                        method.Invoke(target, new object[] {null, null});
                    }
                    catch (TargetParameterCountException)
                    {
                        Assert.Fail("Parameter Count Error in Reflection Call.");
                    }
                    catch (Exception e)
                    {
                        if (e is NotImplementedException || e.InnerException is NotImplementedException)
                        {
                            // Not implemented! This is unacceptable!
                            errors.Add(string.Format("Unimplemented Visit method for type {0} found.",
                                parameter.ParameterType.FullName));
                        }

                        // all other exception types are fine as we are passing null to the methods. We would expect them to throw.
                    }
                }

                if (errors.Any())
                {
                    string message = string.Join("\r\n", errors.ToArray());
                    Assert.Fail(message);
                }
            }
Пример #10
0
            public void VisitAlgebraicExpressionTree()
            {
                var target = new PrintVisitor();

                var a     = new IdentifierExpr("a");
                var b     = new IdentifierExpr("b");
                var c     = new IdentifierExpr("c");
                var one   = new ConstantExpr(1);
                var two   = new ConstantExpr(2);
                var three = new ConstantExpr(3);
                var four  = new ConstantExpr(4);
                var five  = new ConstantExpr(5);
                var six   = new ConstantExpr(6);

                var expression = new DivExpr(new MultExpr(three, new MultExpr(a, two)), new MultExpr(new MinusExpr(new PowExpr(five, b), one), new PlusExpr(new MinusExpr(six, four), c)));

                var actual = target.Visit(expression, scope);

                Assert.AreEqual("3*a*2/5^b-1*6-4+c", actual);
            }
Пример #11
0
        static void Main(string[] args)
        {
            //Nos visiteurs
            PrintVisitor printVisitor = new PrintVisitor();

            //Nos jeux
            OutdoorGame chatPerche = new OutdoorGame("Récré");
            VideoGame   marioKart  = new VideoGame("Nitendo", 3);
            BoardGame   chess      = new BoardGame("chest board", 32);

            //Notre liste d'objet visitable
            List <IVisitable> visitableClasses = new List <IVisitable> {
                chatPerche, marioKart, chess
            };

            //On visite chacun des objets
            visitableClasses.ForEach(visitableClass => {
                visitableClass.accept(printVisitor);
            });
        }
Пример #12
0
    public static void main(string[] args)
    {
        List <Veiculo> list = new List <Veiculo>();

        list.Add(new Carro("C1"));
        list.Add(new Onibus("O1"));
        list.Add(new Carro("C2"));
        list.Add(new Onibus("O2"));

        // Vamos "visitar", com um PrintVisitor, cada Veiculo da lista
        PrintVisitor visitor = new PrintVisitor();

        foreach (Veiculo veiculo in list)
        {
            veiculo.accept(visitor);
        }

        // Benefício do padrão Visitor:
        // Podemos implementar uma outra classe Visitor sem ter que mexer na implementação
        // da classe Veiculo e de suas subclasses. Em seguinda, podemos usar esse Visitor
        // para visitar todos os veículos da nossa lista.
    }
Пример #13
0
            public void VisitIntegerConstantExpr()
            {
                var target = new PrintVisitor();

                var expression = new ConstantExpr(1234);

                var actual = target.Visit(expression, scope);

                Assert.AreEqual("1234", actual);
            }
Пример #14
0
            public void VisitConditionalExpr(bool condition, int thenValue, int elseValue, string expected)
            {
                var target = new PrintVisitor();

                var conditionExpression = new ConstantExpr(condition);
                var thenExpression = new ConstantExpr(thenValue);
                var elseExpression = new ConstantExpr(elseValue);

                var expr = new ConditionalExpr(conditionExpression, thenExpression, elseExpression);

                var actual = target.Visit(expr, scope);

                Assert.AreEqual(expected, actual);
            }
Пример #15
0
            public void VisitBooleanNotExpr(bool a, string expected)
            {
                var target = new PrintVisitor();

                var aExpression = new ConstantExpr(a);
                var expr = new NotExpr(aExpression);

                var actual = target.Visit(expr, scope);

                Assert.AreEqual(expected, actual);
            }
Пример #16
0
            public void VisitBooleanOrExpr(object a, object b, string expected)
            {
                var target = new PrintVisitor();

                var aExpression = new ConstantExpr(a);
                var bExpression = new ConstantExpr(b);
                var expr = new OrExpr(aExpression, bExpression);

                var actual = target.Visit(expr, scope);

                Assert.AreEqual(expected, actual);
            }
Пример #17
0
            public void VisitMassEnergyEquavalenceExpressionTree()
            {
                var target = new PrintVisitor();

                var e = new IdentifierExpr("e");
                var m = new IdentifierExpr("m");
                var c = new IdentifierExpr("C");
                var two = new ConstantExpr(2);

                var expression = new AssignmentExpr(e, new MultExpr(m, new PowExpr(c, two)));

                var actual = target.Visit(expression, scope);

                Assert.AreEqual("e=m*C^2", actual);
            }
Пример #18
0
            public void VisitAlgebraicExpressionTree()
            {
                var target = new PrintVisitor();

                var a = new IdentifierExpr("a");
                var b = new IdentifierExpr("b");
                var c = new IdentifierExpr("c");
                var one = new ConstantExpr(1);
                var two = new ConstantExpr(2);
                var three = new ConstantExpr(3);
                var four = new ConstantExpr(4);
                var five = new ConstantExpr(5);
                var six = new ConstantExpr(6);

                var expression = new DivExpr(new MultExpr(three,new MultExpr(a, two)), new MultExpr(new MinusExpr(new PowExpr(five,b), one), new PlusExpr(new MinusExpr(six, four), c)));

                var actual = target.Visit(expression, scope);

                Assert.AreEqual("3*a*2/5^b-1*6-4+c", actual);
            }
Пример #19
0
            public void VisitMathExpressionTree()
            {
                var target = new PrintVisitor();

                var one = new ConstantExpr(1);
                var two = new ConstantExpr(2);
                var three = new ConstantExpr(3);
                var four = new ConstantExpr(4);
                var five = new ConstantExpr(5);
                var six = new ConstantExpr(6);

                var expression = new DivExpr(new MultExpr(three, six), new MultExpr(new MinusExpr(five, one), new PlusExpr(four, two)));

                var actual = target.Visit(expression, scope);

                Assert.AreEqual("3*6/5-1*4+2", actual);
            }
Пример #20
0
            public void VisitIdentifierExpr()
            {
                var target = new PrintVisitor();

                var expression = new IdentifierExpr("test");

                var actual = target.Visit(expression, scope);

                Assert.AreEqual("test", actual);
            }
Пример #21
0
            public void VisitDivExpr()
            {
                var target = new PrintVisitor();

                var lhs = new ConstantExpr(1);
                var rhs = new ConstantExpr(2);
                var expression = new DivExpr(lhs, rhs);

                var actual = target.Visit(expression, scope);

                Assert.AreEqual("1/2", actual);
            }
Пример #22
0
 /// <summary>Extension method for minification print of an AST node</summary>
 /// <param name="node">The ast node</param>
 /// <returns>The minified string representation</returns>
 public static string MinifyPrint(this AstNode node)
 {
     return(node == null ? string.Empty : PrintVisitor.Print(node, false));
 }
Пример #23
0
 public DecrementVisitor(PrintVisitor visitor)
 {
     this.visitor = visitor;
 }
Пример #24
0
        static void Main(string[] args)
        {
            /*
             * var acu = new CUser[100];
             * var asu = new SUser[100];
             *
             * var cu = new CUser( "Spi" );
             * var cu2 = cu;
             * cu.Power = 42;
             * Debug.Assert( cu2.Power == 42 );
             *
             * var su = new SUser( "Spi" );
             * var su2 = su;
             * su.Power = 42;
             * Debug.Assert( su2.Power == 0 );
             *
             * // With array:
             * asu[0].Power = 42;
             * Debug.Assert( asu[0].Power == 42 );
             *
             * var lsu = new List<SUser>();
             * lsu.Add( new SUser( "In a list." ) );
             *
             * // This NOW (newer C# version) is forbidden.
             * // But before...
             * // lsu[0].Power = 42;
             * // We'd have had 0 here instead of the expercted 42...
             * // Debug.Assert( lsu[0].Power == 0 );
             */

            string sfString = "(( 3 + x ) + ( y - 2 )) + ( x * y * 3 ) / 2";
            var    sf       = new SimpleAnalyzer().Parse(sfString);

            var boundary = new ComputingBoundary(-1.0d, 1.0d, 20);
            var computer = new InBoundaryCompute(boundary, boundary, sf);
            var heap     = new Heap <ComputeNodeResult>();

            var randomGenerator = new RandomASTGenerator();

            for (int i = 0; i < 100; i++)
            {
                var candidate  = randomGenerator.Generate();
                var nodeResult = computer.ComputeInRange(candidate);
                heap.Add(nodeResult);
            }

            var bestCandidate = new ComputeNodeResult[10];

            while (heap.Peek().Gap > 10.0d)
            {
                for (int i = 0; i < bestCandidate.Length; i++)
                {
                    bestCandidate[i] = heap.RemoveMax();
                }

                heap.Clear();

                for (int i = 0; i < bestCandidate.Length; i++)
                {
                    heap.Add(bestCandidate[i]);
                }

                var genMutator = new GeneticMutator();

                for (int i = 0; i < bestCandidate.Length - 1; i += 2)
                {
                    for (int j = 0; j < 10; j++)
                    {
                        var children = genMutator.Birth(bestCandidate[i].Node, bestCandidate[i + 1].Node);

                        heap.Add(computer.ComputeInRange(children));
                    }
                }
                Console.WriteLine(heap.Peek().Gap);
            }

            var printVisitor = new PrintVisitor();

            printVisitor.VisitNode(heap.Peek().Node);
            Console.WriteLine(printVisitor.Result);
            Console.ReadLine();
        }
Пример #25
0
        public static string Print(this SqlNode sqlNode)
        {
            PrintVisitor printVisitor = new PrintVisitor();

            return(printVisitor.Print(sqlNode));
        }
Пример #26
0
 /// <summary>Extension method for pretty print of an AST node</summary>
 /// <param name="node">The ast node</param>
 /// <returns>The pretty string representation</returns>
 public static string PrettyPrint(this AstNode node)
 {
     return(node == null ? string.Empty : PrintVisitor.Print(node, true));
 }