获取活跃的 Antlr 规则
是否可以获取调用操作方法的“活动”ANTLR 规则?
像 Antlr-Pseudo-Code 中的日志函数这样的东西应该显示某些规则的开始和结束位置,而无需在每次 log() 调用时交出 $start- 和 $end-tokens:
@members{
private void log() {
System.out.println("Start: " + $activeRule.start.pos +
"End: " + $activeRule.stop.pos);
}
}
expr: multExpr (('+'|'-') multExpr)* {log(); }
;
multExpr
: atom('*' atom)* {log(); }
;
atom: INT
| ID {log(); }
| '(' expr ')'
;
Is it possible to get the "active" ANTLR rule from which a action method was called?
Something like this log-function in Antlr-Pseudo-Code which should show the start and end position of some rules without hand over the $start- and $end-tokens with every log()-call:
@members{
private void log() {
System.out.println("Start: " + $activeRule.start.pos +
"End: " + $activeRule.stop.pos);
}
}
expr: multExpr (('+'|'-') multExpr)* {log(); }
;
multExpr
: atom('*' atom)* {log(); }
;
atom: INT
| ID {log(); }
| '(' expr ')'
;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,没有办法获取解析器当前所在的规则的名称。默认情况下,解析器规则只是返回
void
的 Java 方法。从 Java 方法中,您根本无法在运行时找到它的名称(当在此方法内部时)。如果您在语法的
options { ... }
中设置output=AST
,则每个解析器规则都会创建(并返回)一个ParserRuleReturnScope
的实例code> 称为retval
:因此您可以将其用于您的目的:但这并不是一件非常可靠的事情:变量的名称很可能会在ANTLR 的下一个版本。
No, there is no way to get the name of the rule the parser is currently in. Realize that parser rules are, by default, simply Java methods returning a
void
. From a Java method, you cannot find out the name of it at run-time after all (when inside of this method).If you set
output=AST
in theoptions { ... }
of your grammar, every parser rule creates (and returns) an instance of aParserRuleReturnScope
calledretval
: so you could use that for your purposes:This is however not a very reliable thing to do: the name of the variable may very well change in the next version of ANTLR.
(对于 Antlr4)
我在谷歌上搜索如何获取活动规则的名称并找到了这篇文章。经过更多研究后,我找到了如何做到这一点:
一个更通用的解决方案将上下文传递给周围的规则,您可以从中提取有关最后一个活动规则的所有信息。
文件
RuleName.g4
:文件
input.txt
:执行:
(for Antlr4)
I was googling on how to get the name of the active rule and found this post. After some more research, I have found how to do it :
A more general solution passes the context on to the surrounding rule, from which you can extract all informations about the last active rule.
File
RuleName.g4
:File
input.txt
:Execution :