antlr4:如何知道在给定上下文的情况下选择了哪个 [英] antlr4: how to know which alternative is chosen given a context

查看:113
本文介绍了antlr4:如何知道在给定上下文的情况下选择了哪个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有一个关于类型"的规则.它可以是预定义的类型(由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() == nullctx.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类.在上面的示例中,您将获得SomeTypeContextSomeOtherTypeContext,它们同样适用于生成的侦听器和访客接口.

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:如何知道在给定上下文的情况下选择了哪个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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