问题描述
假设有一个关于类型"的规则.它是预定义的类型(由 IDENTIFIER 引用)或 typeDescriptor.
Assume there is a rule about 'type'. It is either a predefined type (referred by IDENTIFIER) or a typeDescriptor.
type
: IDENTIFIER
| typeDescriptor
;
在我的程序中,我有一个 typeContext 'ctx' 的实例.我怎么知道是选择了路径 IDENTIFIER,还是选择了 typeDescriptor.
In my program, I have got an instance of typeContext 'ctx'. How do I know if the path IDENTIFIER is chosen, or typeDescriptor is chosen.
我知道一种方法是测试 ctx.IDENTIFIER() == null
和 ctx.typeDescriptor() == null
.但是当有更多选择时,它似乎不太好用.有没有办法返回一个索引来指示选择了哪个规则?谢谢.
I recognise one way which is to test ctx.IDENTIFIER() == null
and ctx.typeDescriptor() == null
. But it seems not working very well when there are a lot more alternatives. Is there a way to return an index to indicate which rule is chosen? Thanks.
推荐答案
不,您可以使用您描述的方法(检查项目是否为非空),或者您可以使用#
运算符.
No, you can either use the method you described (checking if an item is non-null), or you can label the outer alternatives of the rule using the #
operator.
type
: IDENTIFIER # someType
| typeDescriptor # someOtherType
;
当您标记外部替代项时,它将为每个标签生成 ParserRuleContext
类.在上面的示例中,您将获得一个 SomeTypeContext
或一个 SomeOtherTypeContext
,它们同样适用于生成的侦听器和访问者接口.
When you label the outer alternatives, it will produce ParserRuleContext
classes for each of the labels. In the example above, you'll either get a SomeTypeContext
or a SomeOtherTypeContext
, which applies equally to the generated listener and visitor interfaces.
这篇关于antlr4:如何知道在给定上下文的情况下选择了哪个选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!