捕获ANTLR中的错误并查找父母 [英] Catching errors in ANTLR and finding parent

查看:130
本文介绍了捕获ANTLR中的错误并查找父母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现我可以通过覆盖displayRecognitionError在解析过程中遇到错误,但是如何找到这个错误的父节点?

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。如果我有语法:
prog:stat expr;
stat:STRING;
expr:INTEGER;

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

并给它输入abc def。

And give it the input "abc def".

然后我将在def中得到一个应该是整数的错误。在这一点上,我想要得到父expr(因为它在INTEGER部分内部失败),它是父prog。类似于在java中打印堆栈跟踪。

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.

我试图查看从RecognitionException中解析为displayRecognitionError的节点,但它为null,并且使用CommonErrorNode,父级为null。

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?

推荐答案

有:

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

是你想要的?

哦,你想要父母的规则。我会说使用异常来捕获你想要的错误。在规则中添加异常捕获,您想要捕获expr错误,然后关闭其他规则的默认捕获。

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.

使用

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

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

,然后在要捕获的规则中添加捕获。

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

这篇关于捕获ANTLR中的错误并查找父母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆