有没有办法知道ANTLR解析器当前处于哪个替代规则中?没有办法、规则、ANTLR

2023-09-03 09:52:36 作者:云淡风轻

我想知道antlr当前在哪个替代规则中,它使用ctx.getChildCount()或ctx.id()!=NULL来了解antlr当前在哪个替代规则中。

但我想知道有没有方法可以给出备选规则的具体指标。

关于SQL解析,为何编程语言解析器ANTLR更胜一筹

我看到此问题How to know which alternative rule ANTLR parser is currently in during visit,但它没有答案。

推荐答案

使用alt labels了解您的选择,或者尝试使用 options {contextSuperClass=org.antlr.v4.runtime.RuleContextWithAltNum;}(link),但这可能不是您想要的。contextSuperClass将仅在子规则中告诉您其父规则中的索引是什么:

parent
 : child_a
 | child_b
 | child_c
 | child_d
 | child_e
 ;

child_d
 : ... // in a listener, you can now get index 3 from the parent context
 ;

因此您无法执行以下操作:

parent
 : child_a
 | child_b
 | child_c
 | child_d // get index 3 here
 | child_e
 ;

请注意,contextSuperClass仅在Java中可用,通过查看链接中的备注:我只是将其放入Java运行时,因为我确信我是唯一真正使用它的人。&q;