如何在Antlr中输入代码行号以解析树

时间:2019-09-13 15:26:36

标签: java antlr

我正在使用antlr语法生成JavaScript代码的parseTree。有没有一种方法可以使用antlr将行号添加到解析树中??

     String a = "function a(){\n" +
                "            var a =10;\n" +
                "            if(a>20){\n" +
                "                a=a+1;\n" +
                "            }else{\n" +
                "                a=a-1;\n" +
                "            }\n" +
                "        }";
       try{
            CharStream charStream = CharStreams.fromString(a);
            JavaScriptLexer javaScriptLexer =new JavaScriptLexer(charStream);
            CommonTokenStream commonTokenStream = new CommonTokenStream(javaScriptLexer);
            JavaScriptParser javaScriptParser = new JavaScriptParser(commonTokenStream);
            ParseTree parseTree = javaScriptParser.program();
            System.out.println(parseTree.toStringTree(javaScriptParser));


        }catch (Exception e){
            System.out.println(e);
        }

此代码提供输出

(program (sourceElements (sourceElement (statement (functionDeclaration function a ( ) { (functionBody (sourceElements (sourceElement (statement (variableStatement (varModifier var) (variableDeclarationList (variableDeclaration a = (singleExpression (literal (numericLiteral 10))))) (eos ;)))) (sourceElement (statement (ifStatement if ( (expressionSequence (singleExpression (singleExpression a) > (singleExpression (literal (numericLiteral 20))))) ) (statement (block { (statementList (statement (expressionStatement (expressionSequence (singleExpression (singleExpression a) = (singleExpression (singleExpression a) + (singleExpression (literal (numericLiteral 1)))))) (eos ;)))) })) else (statement (block { (statementList (statement (expressionStatement (expressionSequence (singleExpression (singleExpression a) = (singleExpression (singleExpression a) - (singleExpression (literal (numericLiteral 1)))))) (eos ;)))) }))))))) })))) <EOF>)

我需要将行号以及其他详细信息添加到parseTree中。我想知道有什么方法吗?

0 个答案:

没有答案