Exemplo n.º 1
0
        public static List <CFG> Analyze(Node n)
        {
            var symbols = new SymbolTable();
            var scope   = new Scope
            {
                ScopeType   = ScopeType.Program,
                SymbolTable = symbols
            };

            symbols.AddSymbol(new BuiltinFunctionVariable
            {
                Name  = "$main$",
                Scope = scope
            });
            symbols.AddSymbol(new BuiltinFunctionVariable
            {
                Name  = "writeln",
                Scope = scope
            });
            symbols.AddSymbol(new BuiltinFunctionVariable
            {
                Name  = "read",
                Scope = scope
            });
            symbols.AddSymbol(new BuiltinVariable
            {
                Name          = "true",
                PrimitiveType = PrimitiveType.Boolean,
                SubType       = PrimitiveType.Void,
                Scope         = scope
            });
            symbols.AddSymbol(new BuiltinVariable
            {
                Name          = "false",
                PrimitiveType = PrimitiveType.Boolean,
                SubType       = PrimitiveType.Void,
                Scope         = scope
            });


            var visitors = new Visitor[]
            {
                new ScopeVisitor(scope),
                new BuiltinVisitor(scope),
                new TypeVisitor(scope),
                new ExpressionVisitor(scope),
            };

            foreach (var v in visitors)
            {
                n.Accept(v);
            }

            var cfgVisitor = new CfgVisitor(scope, new List <CFG>());
            var cfg        = n.Accept(cfgVisitor);

            Console.WriteLine(string.Join("\n", cfg));
            return(cfg);
        }
Exemplo n.º 2
0
        public override string GenerateCode(AbstractNode node, string indentation)
        {
            StringBuilder     errorBuilder = new StringBuilder();
            ConverterSettings settings     = new ConverterSettings("codegeneration.cs");
            string            output       = null;

            Node booNode = (Node)node.AcceptVisitor(new ConvertVisitor(settings), null);

            if (settings.Errors.Count > 0)
            {
                foreach (CompilerError error in settings.Errors)
                {
                    errorBuilder.AppendLine(error.ToString());
                }
            }
            else
            {
                if (settings.Warnings.Count > 0)
                {
                    foreach (CompilerWarning warning in settings.Warnings)
                    {
                        errorBuilder.AppendLine(warning.ToString());
                    }
                }
                booNode.Accept(new RemoveRedundantTypeReferencesVisitor());
                using (StringWriter w = new StringWriter()) {
                    BooPrinterVisitor printer = new BooPrinterVisitor(w);
                    int indentCount           = 0;
                    foreach (char c in indentation)
                    {
                        if (c == '\t')
                        {
                            indentCount += 4;
                        }
                        else
                        {
                            indentCount += 1;
                        }
                    }
                    indentCount /= 4;
                    while (indentCount-- > 0)
                    {
                        printer.Indent();
                    }
                    booNode.Accept(printer);
                    output = w.ToString();
                }
            }
            if (errorBuilder.Length > 0)
            {
                MessageService.ShowMessage(errorBuilder.ToString());
            }
            return(output);
        }
Exemplo n.º 3
0
            public Node Visit(Node node)
            {
                TextNode tn = node as TextNode;

                if (tn != null)
                {
                    _textContent.Append(tn.Value);
                    _nodeContent.Add(tn);
                    return(node);
                }

                Number number = node as Number;

                if (number != null)
                {
                    _nodeContent.Add(number);
                    return(node);
                }

                Keyword keyword = node as Keyword;

                if (keyword != null)
                {
                    _nodeContent.Add(keyword);
                    _textContent.Append(keyword.Value);
                    return(node);
                }

                node.Accept(this);

                return(node);
            }
Exemplo n.º 4
0
        public void ParseSimpleStylesheetWithTwoPagesAndSections_WillSucceed()
        {
            var  stylesheetTask = new StylesheetTask(TestDataResolver.LoadTestFile("emptyStylesheetWithTwoPagesAndSections.qls"), new SymbolTable());
            Node ast            = _parsingService.Process(stylesheetTask).Ast;

            _assertVisitor.EnqueueStylesheetNodeCallback(st =>
            {
                Assert.AreEqual("test", st.Label);
            });
            _assertVisitor.EnqueuePageNodeCallback(p =>
            {
                Assert.AreEqual("testPage", p.Label);
            });
            _assertVisitor.EnqueuePageNodeCallback(p =>
            {
                Assert.AreEqual("nextPage", p.Label);
            });
            _assertVisitor.EnqueueSectionNodeCallback(s =>
            {
                Assert.AreEqual("testSection", s.Label);
            });
            _assertVisitor.EnqueueSectionNodeCallback(s =>
            {
                Assert.AreEqual("nextSection", s.Label);
            });
            ast.Accept(_assertVisitor);
            _assertVisitor.VerifyAll();
        }
Exemplo n.º 5
0
        public static void Run()
        {
            var tree = new Node <int>(new Node <int>(new Leaf <int>(1), 2, new Leaf <int>(3)),
                                      4, new Node <int>(new Leaf <int>(5), 6, new Leaf <int>(7)));

            var sum = tree.Accept(new AlgebraSumVisitor());
        }
    public static System.Object GetValue(Node n)
    {
        NodeVisitor visitor = new NodeVisitor();

        n.Accept(visitor);
        return(visitor.value);
    }
        public static string SuffixValue(this Node suffix, Interpreter interpreter)
        {
            var prop = suffix as PropertyReferenceSuffix;

            return(prop != null
                ? prop.Identifier.Value
                : CheckIndex(suffix.Accept(interpreter), interpreter));
        }
Exemplo n.º 8
0
 public override T traverse(Node n)
 {
     if (n == null)
     {
         return(default(T));
     }
     return
         (n.Accept <T>(Processor));
 }
Exemplo n.º 9
0
        public Node Visit(Node node)
        {
            bool visitDeeper;
            node = Execute(node, out visitDeeper);
            if (visitDeeper && node != null)
                node.Accept(this);

            return node;
        }
Exemplo n.º 10
0
        public virtual TResult VisitNode(Node node)
        {
            if (node != null)
            {
                return(node.Accept(this));
            }

            return(default(TResult));
        }
Exemplo n.º 11
0
        public static void AssertCSharpCode(string expected, Node node)
        {
            var output = new StringWriter();
            node.Accept(new CSharpPrinter(output));

            StringsModule.AssertAreEqualIgnoringNewLineDifferences(
                StringsModule.NormalizeIndentation(expected),
                output.ToString().TrimEnd());
        }
        public static void Run(Node node, Visitor visitor)
        {
            node.Accept(visitor);

            foreach (Node child in node.Children)
            {
                Run(child, visitor);
            }
        }
Exemplo n.º 13
0
        public static void AssertCSharpCode(string expected, Node node)
        {
            var output = new StringWriter();

            node.Accept(new CSharpPrinter(output));

            StringsModule.AssertAreEqualIgnoringNewLineDifferences(
                StringsModule.NormalizeIndentation(expected),
                output.ToString().TrimEnd());
        }
Exemplo n.º 14
0
 public Response <T> Request <T>(T command) where T : ICommand
 {
     try
     {
         return(_node.Accept(command));
     }
     catch (Exception e)
     {
         return(new ErrorResponse <T>("Unable to send command to node.", command));
     }
 }
Exemplo n.º 15
0
        public void ParseSimpleStylesheetWithOnePageOneSectionOneQuestionAndWidget_WillSucceed()
        {
            var  stylesheetTask = new StylesheetTask(TestDataResolver.LoadTestFile("onePageStylesheetWithQuestionAndWidget.qls"), new SymbolTable());
            Node ast            = _parsingService.Process(stylesheetTask).Ast;

            _assertVisitor.EnqueueWidgetNodeCallback(w =>
            {
                Assert.AreEqual("Radio", w.Widget.ToString());
            });
            ast.Accept(_assertVisitor);
            _assertVisitor.VerifyAll();
        }
Exemplo n.º 16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Query"/> class.
        /// </summary>
        /// <param name="log">The log to query</param>
        /// <param name="settings">The application settings</param>
        /// <param name="query">The query string to execute</param>
        internal Query(Log log, Node tree)
        {
            _log  = log;
            _tree = tree;

            // define result columns for the query
            var visitor = new FieldsVisitor();

            _tree.Accept(visitor);
            _columns = visitor.Fields;
            if (visitor.GeneratesDynamicFields)
            {
                _dynamicColumns = new Dictionary <string, Type>();
            }

            // print the query tree for debugging
            var format = new FormatVisitor();

            _tree.Accept(format);
            _logger.Info($"Created query tree\r\n" + format.ToString().TrimEnd());
        }
Exemplo n.º 17
0
        public Node Visit(Node node)
        {
            bool visitDeeper;

            node = Execute(node, out visitDeeper);
            if (visitDeeper && node != null)
            {
                node.Accept(this);
            }

            return(node);
        }
Exemplo n.º 18
0
        public void BuilderVisitorCantVisitNonRoot()
        {
            #region Arrange Bad Root Node Input and Builder Visitor

            var root = new Node(NodeType.Service, "service");
            var sut = new BuilderVisitor();

            #endregion Arrange Bad Root Node Input and Builder Visitor

            var expected = Assert.Throws<InvalidOperationException>(() => root.Accept(sut));
            expected.Message.Should().Be("Cannot use BuilderVisitor on non-root Node");
        }
 protected override void VisitRecursive(Node node)
 {
     if (node == null)
     {
         Return("");
         return;
     }
     _childStrings.Push(new List <string>());
     foreach (Node child in node)
     {
         VisitRecursive(child);
     }
     node.Accept(this);
 }
Exemplo n.º 20
0
        private static int replyExecutionTree(Node module,
                                              string modname,
                                              WSOutputSink sink)
        {
            Action <XmlDocument, XmlElement> handler = (doc, parent) =>
            {
                var mod = doc.CreateElement("module");
                var vis = new ExecutionTreeJSONVisitor(doc, mod);
                parent.AppendChild(module.Accept(vis));
            };

            sink.SendData("execution-tree", modname, handler);
            return(0);
        }
Exemplo n.º 21
0
        public override void Postprocess(Node root, List <Message> log)
        {
            if (root != null)
            {
                var visitor = new RoutineAggregationVisitor();
                root.Accept(visitor);
                Log.AddRange(visitor.Log);
            }

            foreach (var rec in Log)
            {
                rec.Source = this.GetType().FullName;
            }
        }
Exemplo n.º 22
0
        public void ParseSimpleStylesheetWithOnePage_WillSucceed()
        {
            Node ast = _parsingService.ParseQLSSheet(TestDataResolver.LoadTestFile("emptyStylesheetWithOnePage.qls"));

            _assertVisitor.EnqueueStylesheetNodeCallback(st =>
            {
                Assert.AreEqual("test", st.Label);
            });
            _assertVisitor.EnqueuePageNodeCallback(p =>
            {
                Assert.AreEqual("testPage", p.Label);
            });
            ast.Accept(_assertVisitor);
            _assertVisitor.VerifyAll();
        }
Exemplo n.º 23
0
        private void addProperty(XmlElement parent,
                                 string name, Node value)
        {
            var n = document.CreateElement(name);

            if (value == null)
            {
                n.SetAttribute("type", "null");
                parent.AppendChild(n);
                return;
            }
            n.SetAttribute("type", "object");
            existingNode = n;
            parent.AppendChild(value.Accept(this));
        }
Exemplo n.º 24
0
        protected void TreePostProcessing(Node root)
        {
            root.Accept(new RemoveAutoVisitor(GrammarObject));
            root.Accept(new GhostListOptionProcessingVisitor(GrammarObject));
            root.Accept(new LeafOptionProcessingVisitor(GrammarObject));
            root.Accept(new MergeAnyVisitor(GrammarObject));
            root.Accept(new MappingOptionsProcessingVisitor(GrammarObject));

            NodeRetypingVisitor.Root = root;
            root.Accept(NodeRetypingVisitor);
            root = NodeRetypingVisitor.Root;

            root.Accept(new UserifyVisitor(GrammarObject));
        }
Exemplo n.º 25
0
        public override void Postprocess(Node root, List <Message> log)
        {
            if (Excluded.Count > 0)
            {
                var locations = log.Where(l => l.Location != null).Select(l => l.Location);

                if (root != null)
                {
                    var getLocationsVisitor = new GatherLocationsVisitor();
                    root.Accept(getLocationsVisitor);
                    locations = locations.Concat(getLocationsVisitor.Locations);
                }

                locations = locations.Distinct().OrderBy(l => l.Offset);

                /// Сколько исключенных из компиляции символов было учтено на данный момент
                var includedCharsCount = 0;
                /// Сколько исключенных из компиляции строк было учтено на данный момент
                var includedLinesCount = 0;
                /// Сколько исключенных из компиляции участков было учтено на данный момент
                var includedSegmentsCount = 0;

                foreach (var loc in locations)
                {
                    var start = loc.Offset + includedCharsCount;

                    /// Пока начало содержимого узла в текущих координатах лежит правее
                    /// начала первого не возвращённого в рассмотрение сегмента в координатах исходного файла,
                    /// поправляем текущие координаты с учётом добавления этого сегмента
                    while (includedSegmentsCount < Excluded.Count &&
                           Excluded[includedSegmentsCount].Start.Offset <= start)
                    {
                        includedCharsCount += Excluded[includedSegmentsCount].Length.Value;
                        includedLinesCount += Excluded[includedSegmentsCount].End.Line - Excluded[includedSegmentsCount].Start.Line + 1;
                        start += Excluded[includedSegmentsCount].Length.Value;
                        includedSegmentsCount += 1;
                    }

                    loc.Shift(includedLinesCount, 0, includedCharsCount);
                }
            }
        }
Exemplo n.º 26
0
 public virtual bool LinkNodes(Dictionary <string, Node> nodeMap, Dictionary <string, string[]> linkMap)
 {
     foreach (string link in linkMap.Keys)
     {
         if (nodeMap.ContainsKey(link))
         {
             Node node = nodeMap[link];
             foreach (string linkedlink in linkMap[link])
             {
                 if (nodeMap.ContainsKey(linkedlink))
                 {
                     Node linkNode = nodeMap[linkedlink];
                     node.Accept(Visitor);
                     bool canNext = Visitor.CanAddNext(linkNode);
                     if (canNext)
                     {
                         node.AddNext(linkNode);
                     }
                     linkNode.Accept(Visitor);
                     bool canPrev = Visitor.CanAddPrevious(node);
                     if (canPrev)
                     {
                         linkNode.AddPrevious(node);
                     }
                     if (!canNext || !canPrev)
                     {
                         return(false);
                     }
                 }
                 else
                 {
                     return(false);
                 }
             }
         }
         else
         {
             return(false);
         }
     }
     return(true);
 }
Exemplo n.º 27
0
        public void ParseSimpleStylesheetWithOnePageOneSectionOneQuestion_WillSucceed()
        {
            var  stylesheetTask = new StylesheetTask(TestDataResolver.LoadTestFile("onePageStylesheetWithQuestion.qls"), new SymbolTable());
            Node ast            = _parsingService.Process(stylesheetTask).Ast;

            _assertVisitor.EnqueueStylesheetNodeCallback(st =>
            {
                Assert.AreEqual("test", st.Label);
            });
            _assertVisitor.EnqueuePageNodeCallback(p =>
            {
                Assert.AreEqual("testPage", p.Label);
            });
            _assertVisitor.EnqueueQuestionNodeCallback(q =>
            {
                Assert.AreEqual("questionOne", q.Label);
            });
            ast.Accept(_assertVisitor);
            _assertVisitor.VerifyAll();
        }
Exemplo n.º 28
0
        public void ParseOptionWidgetWithCustomText_WillSucceed()
        {
            var  stylesheetTask = new StylesheetTask(TestDataResolver.LoadTestFile("optionWidgetTest.qls"), new SymbolTable());
            Node ast            = _parsingService.Process(stylesheetTask).Ast;

            _assertVisitor.EnqueueWidgetNodeCallback(w =>
            {
                Assert.AreEqual("Radio", w.Widget.ToString());
            });
            _assertVisitor.EnqueueWidgetOptionNodeCallback(o =>
            {
                Assert.AreEqual("Good", o.Label);
            });
            _assertVisitor.EnqueueWidgetOptionNodeCallback(o =>
            {
                Assert.AreEqual("Evil", o.Label);
            });
            ast.Accept(_assertVisitor);
            _assertVisitor.VerifyAll();
        }
Exemplo n.º 29
0
        public void Select <TNode>(Node <TNode> node) where TNode : class
        {
            _node = null;
            node.Accept(this);

            if (_node == null)
            {
                PropertyNode <T, TProperty> propertyNode = _configurator.Property <T, TProperty>(Property);

                var parentNode = node as Node <T>;
                if (parentNode == null)
                {
                    throw new ArgumentException("Expected propertyNode, but was " + node.GetType().Name);
                }

                parentNode.AddActivation(propertyNode);

                _node = propertyNode;
            }

            _next.Select(_node);
        }
Exemplo n.º 30
0
        public void Select <TNode>(Node <TNode> node) where TNode : class
        {
            _node = null;
            node.Accept(this);

            if (_node == null)
            {
                AlphaNode <T> alphaNode = _configurator.Alpha <T>();

                var parentNode = node as Node <T>;
                if (parentNode == null)
                {
                    throw new ArgumentException("Expected " + typeof(T).Tokens() + ", but was "
                                                + typeof(TNode).Tokens());
                }

                parentNode.AddActivation(alphaNode);

                _node = alphaNode;
            }

            _next.Select(_node);
        }
Exemplo n.º 31
0
        public void Select <TNode>(Node <TNode> node)
            where TNode : class
        {
            _node = null;
            node.Accept(this);

            if (_node == null)
            {
                EachNode <T, TProperty, TElement> eachNode = CreateNode();

                var parentNode = node as Node <Token <T, TProperty> >;
                if (parentNode == null)
                {
                    throw new ArgumentException("Expected " + typeof(T).Tokens() + ", but was "
                                                + typeof(TNode).Tokens());
                }

                parentNode.AddActivation(eachNode);

                _node = eachNode;
            }

            _next.Select(_node);
        }
Exemplo n.º 32
0
        public void Select <TNode>(Node <TNode> node)
            where TNode : class
        {
            _node = null;
            node.Accept(this);

            if (_node == null)
            {
                EqualNode <T, TProperty> equalNode = _configurator.Equal <T, TProperty>();

                var parentNode = node as Node <Token <T, TProperty> >;
                if (parentNode == null)
                {
                    throw new ArgumentException("Expected " + typeof(T).Tokens() + ", but was "
                                                + typeof(TNode).Tokens());
                }

                parentNode.AddActivation(equalNode);

                _node = equalNode;
            }

            _next.Select(_node[_value]);
        }
Exemplo n.º 33
0
        public void ParseStylesheetWithALocalStyleAndAllProperties_WillSucceed()
        {
            var  stylesheetTask = new StylesheetTask(TestDataResolver.LoadTestFile("stylesheetWithOneQuestionAndLocalStyle.qls"), new SymbolTable());
            Node ast            = _parsingService.Process(stylesheetTask).Ast;

            _assertVisitor.EnqueueQuestionNodeCallback(q =>
            {
                Assert.AreEqual("questionOne", q.Label);
            });
            _assertVisitor.EnqueuePropertyNodeCallback(p =>
            {
                Assert.AreEqual("width", p.Name);
                Assert.AreEqual("400", p.Value);
            });
            _assertVisitor.EnqueuePropertyNodeCallback(p =>
            {
                Assert.AreEqual("font", p.Name);
                Assert.AreEqual("Arial", p.Value);
            });
            _assertVisitor.EnqueuePropertyNodeCallback(p =>
            {
                Assert.AreEqual("fontsize", p.Name);
                Assert.AreEqual("14", p.Value);
            });
            _assertVisitor.EnqueuePropertyNodeCallback(p =>
            {
                Assert.AreEqual("color", p.Name);
                Assert.AreEqual("#999999", p.Value);
            });
            _assertVisitor.EnqueueWidgetNodeCallback(p =>
            {
                Assert.AreEqual("Spinbox", p.Widget.ToString());
            });
            ast.Accept(_assertVisitor);
            _assertVisitor.VerifyAll();
        }
 protected override void VisitRecursive(Node node)
 {
     if (node == null) {
         Return("");
         return;
     }
     _childStrings.Push(new List<string>());
     foreach (Node child in node) {
         VisitRecursive(child);
     }
     node.Accept(this);
 }
Exemplo n.º 35
0
        public void DebugVisitorShouldTrackDepth()
        {
            var root = new Node(NodeType.Root, "root");
            var one = new Node(NodeType.Field, "one");
            var two = new Node(NodeType.Type, "two");
            var three = new Node(NodeType.Field, "three");
            root.AddChild(one);
            one.AddChild(two);
            two.AddChild(three);

            var debugVisitor = new DebugVisitor();
            root.Accept(debugVisitor);

            var depth = debugVisitor.GetDepth(three.Guid);

            depth.Should().Be(3, "because root starts at 0 and we have a 3 deep tree");
        }
Exemplo n.º 36
0
		public void Print(Node ast)
		{
			ast.Accept(this);
		}
Exemplo n.º 37
0
        void StoreEntity(OpCode opcode, int index, Node value, IType elementType)
        {
            _il.Emit(OpCodes.Dup);	// array reference
            EmitLoadLiteral(index); // element index

            bool stobj = IsStobj(opcode); // value type sequence?
            if (stobj)
            {
                Type systemType = GetSystemType(elementType);
                _il.Emit(OpCodes.Ldelema, systemType);
                value.Accept(this);
                EmitCastIfNeeded(elementType, PopType());	// might need to cast to decimal
                _il.Emit(opcode, systemType);
            }
            else
            {
                value.Accept(this);
                EmitCastIfNeeded(elementType, PopType());
                _il.Emit(opcode);
            }
        }
Exemplo n.º 38
0
		public void Print(Node node)
		{
			node.Accept(this);
		}
Exemplo n.º 39
0
        public void DebugVisitorShouldPrettyPrint()
        {
            var root = new Node(NodeType.Root, "root");
            var one = new Node(NodeType.Field, "one");
            var two = new Node(NodeType.Type, "two");
            var three = new Node(NodeType.Field, "three");
            root.AddChild(one);
            one.AddChild(two);
            two.AddChild(three);

            var expected = "*Root : root" + Environment.NewLine +
                           "-Field : one" + Environment.NewLine +
                           "--Type : two" + Environment.NewLine +
                           "---Field : three" + Environment.NewLine;

            var debugVisitor = new DebugVisitor();
            root.Accept(debugVisitor);
            var result = debugVisitor.ToString();

            result.Should().Be(expected, "because pretty printing should be successful.");
        }
        protected virtual void VisitRecursive(Node node)
        {
            if (node == null) {
                return;
            }
            if (VisitParentBeforeChildren) {
                node.Accept(this);
            }
            for (int i = 0; i < node.ChildNodes.Count; i++) {

                VisitRecursive(node.ChildNodes[i]);
            }
            if (!VisitParentBeforeChildren) {
                node.Accept(this);
            }
        }