antlr3

Antr3 rule rewriting in Antlr4


I were upgrading my antlr3 grammar to antlr4 but found the rule rewiring is not supported in antrl3, appreciate any advice to make below grammar work in Antlr4?

fragment date
    : DATE (MINUS DATE)* -> ^(TO DATE+)
    ;

fragment simpleExpression
    : expr (OR expr)* -> expr+
    ;

fragment simpleExpressionWithLiteral
    : exprWithLiteral (OR exprWithLiteral)* -> exprWithLiteral+
    ;

fragment conditionalExpression
    : orExpression -> ^(COND orExpression)?
    ;

fragment orExpression
    : andExpression (OR^ andExpression)*
    ;

fragment andExpression
    : atom (AND^ atom)*
    ;

fragment atom
    : exprWithLiteral
    | NOT exprWithLiteral -> ^(NOT exprWithLiteral)
    | NOT LPAREN orExpression RPAREN-> ^(NOT orExpression)
    | LPAREN orExpression RPAREN -> orExpression
    ;

fragment exprWithLiteral
    : expr
    | StringLiteral
    ;

fragment expr
    : WORD
    | NUMBER
    ;

Solution

  • The part after -> is not rule rewiring but tree rewriting. ANTLR3 produced an AST which you could manually change using this tree rewriting syntax. ANTLR4 no longer produces ASTs but parse trees, which you cannot change (as they represent the path taken through the grammar).

    So the simple solution is to remove everything on a line starting with ->, example:

    fragment date
        : DATE (MINUS DATE)* -> ^(TO DATE+)
        ;
    

    becomes

    fragment date
        : DATE (MINUS DATE)*
        ;