syntaxantlrgrammarleft-recursion

Antlr weird parentheses syntax


enter image description here

Cant understand this round bracket meaning. Its not necessary to write it, but sometimes it can produce left-recursion error. Where should we use it in grammar rules?


Solution

  • Its not necessary to write it,

    That is correct, it is not necessary. Just remove them.

    but sometimes it can produce left-recursion error.

    If that really is the case, you can open an issue here: https://github.com/antlr/antlr4/issues

    EDIT

    Seeing kaby76's comment, just to make sure: you cannot just remove them from a grammar file regardless. They can be removed from your example rule.

    When used like this:

    rule
     : ID '=' ( NUMBER | STRING ) // match either `ID '=' NUMBER` 
                                  //           or `ID '=' STRING`
     ;
    

    they cannot be removed because removing them wold result in:

    rule
     : ID '=' NUMBER | STRING // match either `ID '=' NUMBER` 
                              //           or `STRING`
     ;
    

    Or with repetition:

    rule
     : ( ID STRING )+ // match: `ID STRING ID STRING ID STRING ...`
     ;
    

    and this:

    rule
     : ID STRING+ // match: `ID STRING STRING STRING ...`
     ;