在 ANTLR 中捕获错误并找到父级 [英] Catching errors in ANTLR and finding parent

查看:22
本文介绍了在 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. 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 的节点,但它为空,而使用 CommonErrorNode 的父节点为空.

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?

推荐答案

CommonTree 有:

CommonTree has:

/** 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天全站免登陆