antlr4: how to know which alternative is chosen given a context

微笑、不失礼 提交于 2019-12-12 08:49:57

问题


Assume there is a rule about 'type'. It is either a predefined type (referred by IDENTIFIER) or a typeDescriptor.

type
:   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.

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.


回答1:


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
  ;

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.



来源:https://stackoverflow.com/questions/22002799/antlr4-how-to-know-which-alternative-is-chosen-given-a-context

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!