antlr4:获取下一个(可选)令牌的索引
antlr4: get index of next (optional) token
我的语言带有可选子句 (CL1
、CL2
)。
语法规则:
func : FUNC ID "(" (CL1 (ID | CL11 ID))? ")" (CL2 (ID | CL21 ID))? EOS ;
由于可选性,我什至不能使用 getChild(i).getText()
,因为 "i" 变得不确定。
在运行代码生成时,我需要在CL1
或CL2
之后选择ID
。
如果我没有 CL1
的索引,我就没有 ID
的索引。
function fnFoo () meni attrBar ;
与
相比将有不同的代币位置
function fnFoo (arg pBar) meni attrBar ;
我使用了另一种方法:
一个。首先检测是否存在这种类型的令牌 ctx.getTokens(LangParser.CL1)[0]
或 ctx.CL1()
b.选择它的 tokenIndex ctx.CL1().getSymbol().tokenIndex
C。前进 tokenIndex + 1
到下一个位置 ID
但在这一点上,我意识到,这个 tokenIndex
与 getChild(i)
API 中使用的索引不同。
并且没有 API 来选择标记文本,使用 tokenIndex
开头。
如何处理这种情况?
ps:我使用 ANTLR 4.8 对访问者使用 nodejs 运行时
这样的事情怎么样:
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()
}
我的语言带有可选子句 (CL1
、CL2
)。
语法规则:
func : FUNC ID "(" (CL1 (ID | CL11 ID))? ")" (CL2 (ID | CL21 ID))? EOS ;
由于可选性,我什至不能使用 getChild(i).getText()
,因为 "i" 变得不确定。
在运行代码生成时,我需要在CL1
或CL2
之后选择ID
。
如果我没有 CL1
的索引,我就没有 ID
的索引。
function fnFoo () meni attrBar ;
与
相比将有不同的代币位置
function fnFoo (arg pBar) meni attrBar ;
我使用了另一种方法:
一个。首先检测是否存在这种类型的令牌 ctx.getTokens(LangParser.CL1)[0]
或 ctx.CL1()
b.选择它的 tokenIndex ctx.CL1().getSymbol().tokenIndex
C。前进 tokenIndex + 1
到下一个位置 ID
但在这一点上,我意识到,这个 tokenIndex
与 getChild(i)
API 中使用的索引不同。
并且没有 API 来选择标记文本,使用 tokenIndex
开头。
如何处理这种情况?
ps:我使用 ANTLR 4.8 对访问者使用 nodejs 运行时
这样的事情怎么样:
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()
}