Catching errors in ANTLR and finding parent

主宰稳场 提交于 2019-12-23 04:04:41

问题


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

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

And give it the input "abc def".

Then I will get an error at "def" which should be an integer. At this point I then want to get the parent which is "expr" (since it fails inside the INTEGER part) and it's parent "prog". Kind of like printing stack trace in java.

I tried to look at the node from RecognitionException parsed to displayRecognitionError, but it is null, and using CommonErrorNode the parent is null.

Should I maybe take a completely different approach?


回答1:


CommonTree has:

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

is that what you want?

Oh, you want the parent rule. I'd say use exceptions to catch errors where you want. add exception catch in rule where you want to trap expr errors then turn off default catching for other rules.

Use

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

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



来源:https://stackoverflow.com/questions/4627244/catching-errors-in-antlr-and-finding-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!