【发布时间】:2021-01-15 16:21:44
【问题描述】:
我的语法如下:
node: '{' type ',' '"expression"' ':' rightSide '}' ;
rightSide:
call # callAlternative
| identifier # identifierAlternative
;
现在在我的访问者中,我实现了 visitNode(Parser.NodeContext ctx) 方法,并希望访问 rightSide 规则的正确方法,无论匹配哪个替代。 # 标签用于为每个备选方案生成专用方法,righSide 规则不再有访问方法。同样visitNode中的ctx只有ctx.rightSide(),没有ctx.callAlternative()和/或ctx.identifierAlternative()。
如何做到这一点?
@Override
public SomeObj visitNode(Parser.NodeContext ctx) {
// how to detect which of the two alternatives was matched? ctx only has ctx.rightSide()
// What is the something in ctx.something ?
if(....){ // how to decide here??
visitIdentifierAlternative(ctx.something);
} else visitCallAlternative(ctx.something);
return new SomeObj();
}
@Override
public SomeObj visitIdentifierAlternative(Parser.IdentifierAlternativeContext ctx) {
// Do things only to be done for IdentifierAlternative
return new SomeObj();
}
@Override
public SomeObj visitCallAlternative(Parser.CallAlternativeContext ctx) {
// Do things only to be done for CallAlternative
return new SomeObj();
}
【问题讨论】:
标签: java parsing antlr antlr4 grammar