예제 #1
0
 public override bool Visit(IParseTree tree)
 {
     if (tree as TerminalNodeImpl != null)
     {
         Results[tree] = true;
         tree.Accept(this);
         return(true);
     }
     return(tree.Accept(this));
 }
예제 #2
0
        public void CollectionTest1()
        {
            var stream = CharStreams.fromstring(@"package RobotsTestModel
            context aMotorsForward
            inv@0:
            Bag{ ""a"", ""bb"", ""ccc""}->select(self->size() = 2)->size() = 1
            inv@0:
            Bag{1,2,3}->forAll(x, y | x <> y implies x*y > 1)
            inv@0:
            Bag{1,2,3}->iterate(x; y : T = 0 | y + x) = 6
            inv@0:
            Set{""1"",""2"",""3""}->collect(self = ""0"")->size() = 3
            inv@0:
            Bag{""1"",""2"",""3""}->any(self.toInteger() > 2).toInteger() = 3
            inv@0:
            aMotorsForward->allInstances()->size() > -1
            endpackage");

            ITokenSource lexer  = new OclLexer(stream);
            ITokenStream tokens = new CommonTokenStream(lexer);
            var          parser = new OclParser(tokens)
            {
                BuildParseTree = true
            };
            IParseTree tree = parser.oclFile();

            Assert.IsTrue(tree.Accept(interpreter));
        }
예제 #3
0
        static void Main(string[] args)
        {
            String       input  = @"package P
context A
inv:
let fact(n: var) = if n = 1 then n else n * fact(n - 1) endif;
let n = 5;
fact(n+1) = 720
inv:
let a = 6;
let b = 6;
a = b
endpackage";
            ICharStream  stream = CharStreams.fromstring(input);
            ITokenSource lexer  = new HelloLexer(stream);
            ITokenStream tokens = new CommonTokenStream(lexer);
            HelloParser  parser = new HelloParser(tokens);

            parser.BuildParseTree = true;
            IParseTree   tree    = parser.oclFile();
            HelloPrinter printer = new HelloPrinter();

            //ParseTreeWalker.Default.Walk(printer, tree);
            tree.Accept(printer);
            Console.ReadLine();
        }
예제 #4
0
        public void StringTest1()
        {
            var stream = CharStreams.fromstring(@"package RobotsTestModel
            context aMotorsForward
            inv@0:
            ""ABC""->toLower() = ""abc""
            inv@0:
            ""123""->toInteger() = 123
            inv@0:
            ""123""->toReal() = 123
            inv@0:
            ""abc""->toUpper() = ""ABC""
            inv@0:
            ""abc""->concat(""cde"")->toUpper() = ""ABCCDE""
            inv@0:
            ""abc""->substring(1, 1) = ""a""
            endpackage");

            ITokenSource lexer  = new OclLexer(stream);
            ITokenStream tokens = new CommonTokenStream(lexer);
            var          parser = new OclParser(tokens)
            {
                BuildParseTree = true
            };
            IParseTree tree = parser.oclFile();

            Assert.IsTrue(tree.Accept(interpreter));
        }
예제 #5
0
 public override Expression Visit(IParseTree node)
 {
     // Hack. There is no language construct that says "all Visit*()"
     // methods must be implemented all tree node types used.
     // So, get the node type, and use reflection on this class to find
     // a visit method overriden for the node type. If not, throw
     // "not implemented".
     if (node as TerminalNodeImpl == null)
     {
         Type   type      = node.GetType();
         Type   this_type = this.GetType();
         string type_name = type.Name;
         // node type:   Parenthesized_expressionContext
         // method name: VisitParenthesized_expression
         Regex  regex               = new Regex("Context$");
         string name                = regex.Replace(type_name, "");
         string method_name         = "Visit" + name;
         IEnumerable <MethodInfo> m = this_type.GetTypeInfo().GetDeclaredMethods(method_name);
         if (!m.GetEnumerator().MoveNext())
         {
             ParserRuleContext where = node as ParserRuleContext;
             IToken token = where.Start;
             int    index = token.StartIndex;
             // No method by the given name exists, which means it's unimplemented.
             throw new Helpers.EvaluationException("unimplemented feature (" + name + ")", index);
         }
     }
     return(node.Accept(this));
 }
예제 #6
0
        public void NumberTest1()
        {
            var stream = CharStreams.fromstring(@"package RobotsTestModel
            context aMotorsForward
            inv@0:
            1->max(2) = 2
            inv@0:
            5->div(2) = 2
            inv@0:
            5->min(2) = 2
            inv@0:
            5->mod(2) = 1
            inv@0:
            5->abs() = 5
            endpackage");

            ITokenSource lexer  = new OclLexer(stream);
            ITokenStream tokens = new CommonTokenStream(lexer);
            var          parser = new OclParser(tokens)
            {
                BuildParseTree = true
            };
            IParseTree tree = parser.oclFile();

            Assert.IsTrue(tree.Accept(interpreter));
        }
예제 #7
0
 public string Visit(IParseTree tree)
 {
     try
     {
         return(tree.Accept(this));
     }
     catch
     {
         if (tree is ParserRuleContext)
         {
             //AntlrHelper.LogConversionError(ex, parserRuleContext, FileNode.FileName.Text, FileNode.FileData, Logger);
         }
         return(DefaultResult);
     }
 }
        /// <summary>
        /// <inheritDoc></inheritDoc>
        /// <p/>
        /// The default implementation initializes the aggregate result to
        /// <see cref="AbstractParseTreeVisitor{Result}.DefaultResult()">defaultResult()</see>
        /// . Before visiting each child, it
        /// calls
        /// <see cref="AbstractParseTreeVisitor{Result}.ShouldVisitNextChild(IRuleNode, Result)">shouldVisitNextChild</see>
        /// ; if the result
        /// is
        /// <code>false</code>
        /// no more children are visited and the current aggregate
        /// result is returned. After visiting a child, the aggregate result is
        /// updated by calling
        /// <see cref="AbstractParseTreeVisitor{Result}.AggregateResult(Result, Result)">aggregateResult
        ///     </see>
        /// with the
        /// previous aggregate result and the result of visiting the child.
        /// </summary>
        public virtual Result VisitChildren(IRuleNode node)
        {
            Result result = DefaultResult();
            int    n      = node.ChildCount;

            for (int i = 0; i < n; i++)
            {
                if (!ShouldVisitNextChild(node, result))
                {
                    break;
                }
                IParseTree c           = node.GetChild(i);
                Result     childResult = c.Accept(this);
                result = AggregateResult(result, childResult);
            }
            return(result);
        }
예제 #9
0
        public void FuncTest1()
        {
            var stream = CharStreams.fromstring(@"package ObjectMetamodel
            context FunctionNode
            inv@2:
            self.params@1 <> self.callParams@2
            endpackage");

            ITokenSource lexer  = new OclLexer(stream);
            ITokenStream tokens = new CommonTokenStream(lexer);
            var          parser = new OclParser(tokens)
            {
                BuildParseTree = true
            };
            IParseTree tree = parser.oclFile();

            Assert.IsTrue(tree.Accept(interpreter));
        }
예제 #10
0
        // public override bool Visit(IParseTree tree)
        // {
        //     throw new NotImplementedException();
        // }

        //public override bool VisitTerminal(ITerminalNode node)
        //{
        //    Errors.Add("ERROR: Line 3, Column 4: wtf??");
        //    return true;
        //}

        public override bool VisitChildren(IRuleNode node)
        {
            bool result = DefaultResult;
            int  n      = node.ChildCount;

            for (int i = 0; i < n; i++)
            {
                if (!ShouldVisitNextChild(node, result))
                {
                    break;
                }
                IParseTree c           = node.GetChild(i);
                bool       childResult = c.Accept(this);
                //result = AggregateResult(result, childResult);
                result = result || childResult;
            }
            return(result);
        }
예제 #11
0
        public Ust Visit(IParseTree tree)
        {
            try
            {
                if (tree == null)
                {
                    return(null);
                }

                return(tree.Accept(this));
            }
            catch (Exception ex) when(!(ex is ThreadAbortException))
            {
                if (tree is ParserRuleContext parserRuleContext)
                {
                    Logger.LogConversionError(ex, parserRuleContext, root.SourceCodeFile);
                }
                return(DefaultResult);
            }
        }
예제 #12
0
파일: TypeVisitor.cs 프로젝트: maxblu/coolc
        public override Node VisitChildren(IRuleNode node)
        {
            NodeList result = new NodeList();
            int      n      = node.ChildCount;

            for (int i = 0; i < n; i++)
            {
                if (!ShouldVisitNextChild(node, result))
                {
                    break;
                }
                IParseTree c           = node.GetChild(i);
                Node       childResult = c.Accept(this);
                if (childResult == null)
                {
                    continue;
                }
                result.Childs.Add(childResult);
            }
            return(result);
        }
        public override object VisitChildren([NotNull] IRuleNode node)
        {
            object result = null;
            int    n      = node.ChildCount;

            for (int i = 0; i < n; i++)
            {
                if (!ShouldVisitNextChild(node, result))
                {
                    break;
                }
                IParseTree c = node.GetChild(i);
                if (c is TerminalNodeImpl || c is ErrorNodeImpl)
                {
                    continue;
                }
                object childResult = c.Accept(this);
                result = AggregateResult(result, childResult);
            }
            return(result);
        }
예제 #14
0
        public UstNode Visit(IParseTree tree)
        {
            try
            {
                if (tree == null)
                {
                    return(null);
                }

                return(tree.Accept(this));
            }
            catch (Exception ex)
            {
                var parserRuleContext = tree as ParserRuleContext;
                if (parserRuleContext != null)
                {
                    AntlrHelper.LogConversionError(ex, parserRuleContext, FileNode.FileName.Text, FileNode.FileData, Logger);
                }
                return(DefaultResult);
            }
        }
예제 #15
0
        public override ParseTreeNode VisitChildren(IRuleNode node)
        {
            ParseTreeNode result = new ParseTreeNode();

            /*if(node.RuleContext is Java8Parser.CompilationUnitContext
             ||node.RuleContext is Java8Parser.NormalClassDeclarationContext
             ||node.RuleContext is Java8Parser.FieldDeclarationContext
             ||node.RuleContext is Java8Parser.MethodDeclarationContext
             ||node.RuleContext is Java8Parser.InterfaceDeclarationContext
             ||node.RuleContext is Java8Parser.InterfaceMethodDeclarationContext)
             * {
             *  result = DefaultResult;
             * }*/
            int n = node.ChildCount;

            for (int i = 0; i < n; i++)
            {
                if (!ShouldVisitNextChild(node, result))
                {
                    break;
                }
                IParseTree    c           = node.GetChild(i);
                ParseTreeNode childResult = c.Accept(this);
                //result = AggregateResult(result, childResult);
                if (childResult != null)
                {
                    if (childResult.ItemType == IClassParser.ItemType.__InternalPlaceHolder ||
                        childResult.ItemType == IClassParser.ItemType.Field)   //expand sub items
                    {
                        result.Children = result.Children.Concat(childResult.Children).ToList();
                    }
                    else
                    {
                        result.Children.Add(childResult);
                    }
                }
            }
            return(result);
        }
예제 #16
0
        public ExpressionNode Parse(string expression)
        {
            var stream = CharStreams.fromString(expression);
            var lexer  = new AudioSynthesisGrammarLexer(stream);
            var tokens = new CommonTokenStream(lexer);
            var parser = new AudioSynthesisGrammarParser(tokens);

            parser.BuildParseTree = true;
            parser.RemoveErrorListeners();
            parser.AddErrorListener(new ThrowingErrorListener <IToken>());

            IParseTree tree    = parser.compileUnit();
            var        visitor = new AudioSynthesisVisitor();
            var        res     = tree.Accept(visitor);

            if (res is null)
            {
                throw new ParseError("Unexpected null building AST.");
            }

            return(res);
        }
예제 #17
0
        /// <summary>
        /// this is the default implementation of antlr
        /// AbstractParseTreeVisitor.VisitChildren
        /// the differences are the comments
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        public override Node VisitChildren(IRuleNode node)
        {
            NodeList result = new NodeList();
            //Result result = DefaultResult;
            int n = node.ChildCount;

            for (int i = 0; i < n; i++)
            {
                if (!ShouldVisitNextChild(node, result))
                {
                    break;
                }
                IParseTree c           = node.GetChild(i);
                Node       childResult = c.Accept(this);
                //result = AggregateResult(result, childResult);/// maybe we should override this method instead
                if (childResult == null)
                {
                    continue;
                }
                result.Childs.Add(childResult);
            }
            return(result);
        }
 public VbaParseTree Visit(IParseTree tree)
 {
     return(tree.Accept(this));
 }
 /// <summary>
 /// <inheritDoc></inheritDoc>
 /// <p/>
 /// The default implementation calls
 /// <see cref="IParseTree.Accept{T}(IParseTreeVisitor{T})">IParseTree.Accept&lt;T&gt;(IParseTreeVisitor&lt;Result&gt;)
 ///     </see>
 /// on the
 /// specified tree.
 /// </summary>
 public virtual Result Visit(IParseTree tree)
 {
     return(tree.Accept(this));
 }
예제 #20
0
        //Scope<TypeSymbol> varTypes;
        //Scope<TypeSymbol> functionTypes;

        public override ASTNode Visit(IParseTree tree)
        {
            //varTypes = new Scope<TypeSymbol>();
            //functionTypes = new Scope<TypeSymbol>();
            return(tree.Accept(this));
        }
예제 #21
0
        internal CodeAnalyzerResult AnalyzeModule(string moduleName, string moduleCode)
        {
            RubberduckParseResult rubberduckParseResult = Parse(moduleName, moduleCode);
            RubberduckParserState parserState           = rubberduckParseResult.ParserState;

            if (parserState.Status != ParserState.Ready)
            {
                return(new CodeAnalyzerResult(moduleName)
                {
                    VbaCodeIssues = GetModuleExceptions(moduleName, parserState)
                });
            }

            List <VbaCodeIssue> vbaCodeIssues = new[]
            {
                Inspect <ApplicationWorksheetFunctionInspection>(moduleName, parserState, ResultFetchMethod.NoHelper),
                Inspect <AssignedByValParameterInspection>(moduleName, parserState, ResultFetchMethod.NoHelper),
                Inspect <ConstantNotUsedInspection>(moduleName, parserState, ResultFetchMethod.NoHelper),
                //Inspect<EmptyIfBlockInspection>(moduleName, parserState, ResultFetchMethod.UsingHelper),
                Inspect <EmptyStringLiteralInspection>(moduleName, parserState, ResultFetchMethod.NoHelper),
                Inspect <EncapsulatePublicFieldInspection>(moduleName, parserState, ResultFetchMethod.NoHelper),
                Inspect <FunctionReturnValueNotUsedInspection>(moduleName, parserState, ResultFetchMethod.NoHelper),
                Inspect <ImplicitActiveSheetReferenceInspection>(moduleName, parserState, ResultFetchMethod.NoHelper),
                Inspect <ImplicitActiveWorkbookReferenceInspection>(moduleName, parserState, ResultFetchMethod.NoHelper),
                Inspect <ImplicitByRefModifierInspection>(moduleName, parserState, ResultFetchMethod.NoHelper),
                Inspect <ImplicitPublicMemberInspection>(moduleName, parserState, ResultFetchMethod.NoHelper),
                Inspect <ImplicitVariantReturnTypeInspection>(moduleName, parserState, ResultFetchMethod.NoHelper),
                Inspect <MemberNotOnInterfaceInspection>(moduleName, parserState, ResultFetchMethod.NoHelper),
                Inspect <MissingAnnotationArgumentInspection>(moduleName, parserState, ResultFetchMethod.NoHelper),
                Inspect <ModuleScopeDimKeywordInspection>(moduleName, parserState, ResultFetchMethod.NoHelper),
                Inspect <MoveFieldCloserToUsageInspection>(moduleName, parserState, ResultFetchMethod.NoHelper),
                Inspect <MultilineParameterInspection>(moduleName, parserState, ResultFetchMethod.UsingHelper),
                Inspect <MultipleDeclarationsInspection>(moduleName, parserState, ResultFetchMethod.UsingHelper),
                Inspect <NonReturningFunctionInspection>(moduleName, parserState, ResultFetchMethod.NoHelper),
                Inspect <ObsoleteCallStatementInspection>(moduleName, parserState, ResultFetchMethod.UsingHelper),
                Inspect <ObsoleteCommentSyntaxInspection>(moduleName, parserState, ResultFetchMethod.UsingHelper),
                Inspect <ObsoleteGlobalInspection>(moduleName, parserState, ResultFetchMethod.NoHelper),
                Inspect <ObsoleteLetStatementInspection>(moduleName, parserState, ResultFetchMethod.UsingHelper),
                Inspect <ObsoleteTypeHintInspection>(moduleName, parserState, ResultFetchMethod.NoHelper),
                Inspect <OptionBaseInspection>(moduleName, parserState, ResultFetchMethod.UsingHelper),
                Inspect <OptionBaseInspection>(moduleName, parserState, ResultFetchMethod.UsingHelper),
                Inspect <OptionExplicitInspection>(moduleName, parserState, ResultFetchMethod.UsingHelper),
                Inspect <ParameterCanBeByValInspection>(moduleName, parserState, ResultFetchMethod.NoHelper),
                Inspect <ParameterNotUsedInspection>(moduleName, parserState, ResultFetchMethod.NoHelper),
                Inspect <ProcedureCanBeWrittenAsFunctionInspection>(moduleName, parserState, ResultFetchMethod.UsingHelper),
                Inspect <ProcedureNotUsedInspection>(moduleName, parserState, ResultFetchMethod.NoHelper),
                Inspect <SelfAssignedDeclarationInspection>(moduleName, parserState, ResultFetchMethod.NoHelper),
                Inspect <UnassignedVariableUsageInspection>(moduleName, parserState, ResultFetchMethod.NoHelper),
                Inspect <UndeclaredVariableInspection>(moduleName, parserState, ResultFetchMethod.NoHelper),
                Inspect <UntypedFunctionUsageInspection>(moduleName, parserState, ResultFetchMethod.NoHelper),
                Inspect <VariableNotAssignedInspection>(moduleName, parserState, ResultFetchMethod.NoHelper),
                Inspect <VariableNotUsedInspection>(moduleName, parserState, ResultFetchMethod.NoHelper),
                Inspect <VariableTypeNotDeclaredInspection>(moduleName, parserState, ResultFetchMethod.NoHelper),
                Inspect <WriteOnlyPropertyInspection>(moduleName, parserState, ResultFetchMethod.NoHelper)
            }.SelectMany(x => x).ToList();

            IParseTree parseTree = rubberduckParseResult.GetParseTree(moduleName);

            return(new CodeAnalyzerResult(moduleName)
            {
                VbaCodeIssues = vbaCodeIssues, ParseTree = parseTree.Accept(new SerializableObjectStructureVisitor())
            });
        }
 public Expression Visit(IParseTree tree) => tree.Accept(this);