1

Take this rule / catch for example:

section : (title sstart row+ send);

    catch[Exception e] {System.out.println("Notification: Problem on line " + *line # here*); System.exit(0);}

How could I get the line number of the token that threw the error?

Tristan
  • 1,608
  • 1
  • 20
  • 34

2 Answers2

0

When you look in the generated code where your exception block is placed, you will see that it is part of a method that is meant to parse the section rule, probably something like:

public final SectionContext section() throws RecognitionException {
    SectionContext _localctx = new SectionContext(_ctx, getState());
    ...
}

As you see there's a parse context (_localctx) created for this rule, which will get all sub contexts along with references to the first and last token that make up this rule (see ParserRuleContext.start and ParserRuleContext.stop. This is where you can get the source info from.

It could be that this SectionContext instance is not yet finish at the time of the exception. In that case you can use the parent context instead (the _ctx parameter in the SectionContext creation call).

Mike Lischke
  • 48,925
  • 16
  • 119
  • 181
0

If you have a ParserRuleContext ctx, you can know the line as:

ctx.start.getLine()

And you can know the position in line:

ctx.start.getCharPositionInLine()
vlarios
  • 31
  • 8