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 ;
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).