1
votes

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!!!

1
Did you check the number of child contexts? You should see 3 when all optional parts exist in the input (otherwise just one, the question mark). Hence you will find the type in the 3rd child context. The child list is created linearly from the matched tokens, regardless of grouping in parentheses or such. - Mike Lischke
@Mike Thank you. I didn't know that child list is created linearly from matched tokens, regardless of grouping in parentheses. Thanks a ton! - MSS

1 Answers

1
votes

According to rule '?' (('extends' | 'super') typeType)? there should be only two child contexts i.e. one for ? and another for ('extends' | 'super') typeType'.

I don't think this is correct. Without seeing more of your grammar, I think you should get three children from this rule, assuming the optional (?) phrase is present in the input text:

  1. ? as an implicit lexer token
  2. either extends or super as an implicit lexer token
  3. typeType as a child context of its own, possibly with its own set of children, since your rule is recursive in that typeType can itself contain a typeType

Does that help? Examine the tree of children and I think it will make sense. The context tree for right-recursive rules can get pretty deep depending on your input text.