我正在使用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中。我想知道有什么方法吗?