antlr4:获取下一个(可选)令牌的索引

问题描述 投票:1回答:1

我的语言带有可选的子句(CL1CL2)。

语法规则:func : FUNC ID "(" (CL1 (ID | CL11 ID))? ")" (CL2 (ID | CL21 ID))? EOS ;

由于可选项,我什至不能使用getChild(i).getText(),因为“ i”变得不确定。

[运行代码生成时,我需要在IDCL1之后选择CL2。如果我没有CL1的索引,那么我没有ID的索引,它紧随其后。

function fnFoo () meni attrBar ;function fnFoo (arg pBar) meni attrBar ;

我使用了另一种方法:一个。首先检测此类型的令牌是否存在ctx.getTokens(LangParser.CL1)[0]ctx.CL1()b。选择其tokenIndexctx.CL1().getSymbol().tokenIndexC。前进tokenIndex + 1到下一个ID

但是,我意识到,此tokenIndexgetChild(i) API中使用的索引不同。而且没有使用tokenIndex开头的API来选择令牌文本。

一个人如何处理这种情况?

ps:我使用ANTLR 4.8与访问者一起使用nodejs运行时

antlr antlr4 visitor
1个回答
2
投票

类似这样的事情:

func
 : FUNC ID '(' cl1? ')' cl2? EOS 
 ;

cl1
 : CL1 CL11? ID
 ;

cl2
 : CL2 CL21? ID
 ;

然后在funcContext中可以执行以下操作:

if (ctx.cl1()) {
   // cl1 is present
   // do something with ctx.cl1().CL1() and/or ctx.cl1().ID()
}
© www.soinside.com 2019 - 2024. All rights reserved.