ANTLR3: how to map the instructions in AST to line number in its java source file

StackOverflow https://stackoverflow.com/questions/18179747

  •  24-06-2022
  •  | 
  •  

Question

How to find the line numbers(of source file) of instructions from AST.

example:

for the following code

24> void foo(){

25> System.out.println(" hi ");

26> }

the ast corresponding to print statement is

         METHOD_CALL
              .
                 .
                    System
                    out
                 println
              ARGUMENT_LIST
                 EXPR
                    " hi "

I want to retrieve the line number of "System" from the generated Tree. The answer for "System" should be 25(line number in the source code).

Was it helpful?

Solution

If your Tree for the System token is in fact a CommonTree, then you can use the CommonTree.getToken() method to get the Token for Symbol. You can then call Token.getLine() to get the line number.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top