我正在使用Antlr4来解析Java.g4语法文件。我正在使用的解析器规则是:
typeArgument
: typeType
| '?' (('extends' | 'super') typeType)?
;
我通过以下方式实现了此解析器规则的访问者方法:
public String visitTypeArgument(JavaParser.TypeArgumentContext ctx) {
StringBuilder typArg = new StringBuilder();
if(ctx.getChild(0).getText().equalsIgnoreCase("?")){
// '?' (('extends' | 'super') typeType)?
typArg.append("?").append(" ");
TypeTypeContext typTypCtx = ctx.typeType();
if(typTypCtx != null){
typArg.append(ctx.getChild(1).getText()).append(" "); // <- Confusion is here
typArg.append(this.visitTypeType(typTypCtx));
}
}
else{
TypeTypeContext typTypCtx = ctx.typeType();
typArg.append(this.visitTypeType(typTypCtx));
}
return typArg.toString();
}
我已经用注释指出了代码中的困惑。我正在解析像 <? extends SomeClassIdentifier>
这样的 typeArgument .
为什么ctx.getChild(1).getText()
返回“extends”而不是“extends SomeClassIdentifier”?
根据规则'?' (('extends' | 'super') typeType)?
应该只有两个子上下文,即一个用于 ?
另一个为 ('extends' | 'super') typeType'
。请帮助我消除我的困惑!
最佳答案
According to rule '?' (('extends' | 'super') typeType)? there should be only two child contexts i.e. one for ? and another for ('extends' | 'super') typeType'.
我认为这是不正确的。在没有看到更多语法的情况下,我认为您应该从这条规则中得到三个子元素,假设输入文本中存在可选的(?)短语:
?
作为隐式词法分析器标记- 或者
扩展
或者super
作为隐式词法分析器标记 typeType
作为它自己的子上下文,可能有它自己的一组子上下文,因为您的规则是递归的,因为typeType
本身可以包含typeType
这有帮助吗?检查一下 child 的树,我认为这是有道理的。根据您的输入文本,右递归规则的上下文树可能会变得相当深。
关于java - Antlr4 子上下文索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45286097/