ANTLR error trapping and parent search

I found that I can catch errors during parsing by overwriting displayRecognitionError, but how to find the parent "node" of this error?

ex. if I have a grammar: prog: stat expr; stat: STRING expr: INTEGER;

And give it the input "abc def".

Then I get an error in "def", which should be an integer. At this point, I want to get the parent element, which is "expr" (since it is not executed inside the INTEGER part), and it is the parent "prog". A kind of stack trace in java.

I tried to take a look at the node from a RecognitionException handled by displayRecognitionError, but it is null and using CommonErrorNode the parent element is null.

Should I take a completely different approach?

+1
source share
1 answer

CommonTree has:

/** Who is the parent node of this node; if null, implies node is root */ public CommonTree parent; 

- Is this what you want?

Oh, you want a parent rule. I would say use exceptions to catch errors wherever you want. add a catch exception to the rule where you want to catch expr errors, and then disable the default binding for other rules.

Using

@rulecatch {catch (RecognitionException re) {throw re; }}

and then add the catches in the rules where you want to catch.

+2
source

All Articles