I am using Antlr4 to parse Java.g4 grammar file. The parser rule I was working with is :
typeArgument
: typeType
| '?' (('extends' | 'super') typeType)?
;
I have implemented the visitor method for this parser rule in the following way:
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();
}
I have indicated the confusion in my code with a comment.I am parsing a typeArgument like <? extends SomeClassIdentifier>.
Why ctx.getChild(1).getText() returns "extends" instead of "extends SomeClassIdentifier"?
According to rule '?' (('extends' | 'super') typeType)? there should be only two child contexts i.e. one for ? and another for ('extends' | 'super') typeType'. Please help me clear my confusion anyone!!!