javaparsingantlr4grammar

ANTLR4 an optional symbol at begining of a rule


I'm learning how ANTLR4 works. I don't understand how to deal with optional symbol at the very beginning of a rule.

I have this simple grammar:

genericRule: optional otherPart ;

optional: ( 'A' | 'B' | 'C' ) * ;
otherPart: 'D' | 'E' | 'F' ;

When i try to match the string with only the char 'E' the Parse Tree Inspector gives me this result:

Wrong result

How i can exclude the first empty rule optional if my input doesn't start with optional tokens 'A', 'B' or 'C' ?

I would like to have this Parse Tree:

Correct result


Solution

  • Bring the "optional" part up a level (to the place where it's optional)

    grammar ExprParser;
    
    genericRule: optional* otherPart ;
    
    optional:  'A' | 'B' | 'C'  ;
    otherPart: 'D' | 'E' | 'F' ;
    

    enter image description here

    In your grammar you've said genericRule MUST have an optional node (and that the optional node may not have any content (children)).