Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the line number in the ParserVisitor?

I'm trying to get line numbers for more specific error messages in my ParserVisitor (visits the parse tree generated by antlr). However, all I have in this class is the context ctx, and I can do things like ctx.getText() but not getLine(). Is there a way to do this?

Can ctx.getPayload() be used here? If so, how?

Edit: I'm using ANTLR 4 to create java files.

Trying to access the line number in a visitor in a method such as this:

@Override  public Type visitStatAssign(@NotNull BasicParser.StatAssignContext ctx) { ... // some semantic error detected int lineNo = ... System.err.("Semantic error at line " + lineNo);  } 

Edit 2: My lexer and parser rules are fairly standard, for example in the lexer:

INT : 'int' ; CHAR : 'char' ; BOOL : 'bool' ; STRING : 'string' ;  

...is in the parser rule baseType:

baseType : INT | CHAR | BOOL | STRING ;  
like image 558
i_have_no_idea_what_i'm_doing Avatar asked Nov 05 '13 10:11

i_have_no_idea_what_i'm_doing


1 Answers

You can get the first token in the rule with ctx.start or ctx.getStart(). Then use getLine() on the token to get the line number (and getCharPositionInLine() to get the column).

like image 94
njlarsson Avatar answered Sep 18 '22 21:09

njlarsson