ANTLR4.7 listener for a rule when sub rules are la

2019-08-21 03:35发布

问题:

I have an antlr4.7 grammar like this, where all sub rules are labeled.

date_expr
    :   attr op=( '+' | '-' ) dt_interval=ISO8601_INTERVAL
        #dateexpr_Op
    |   DATETIME_NAME
        #dateexpr_Named
    |   d=( DATETIME_LITERAL | DATE_LITERAL | TIME_LITERAL ) 
        #dateexpr_Literal
    |   attr
        #dateexpr_Attr
    |   '(' date_expr ')'
        #dateexpr_Paren
    ;

I would like to annotate the tree when a date_expr rule completes. However, looking at the generated listener class, I see no exitDate_expr. How can I add this? Or, do I have to use a visitor interface for it. I am not much familiar with grammar tools.

Thanks.

回答1:

To achieve beforeAllLabledAlts and afterAllLabledAlts visit points, wrap the labeled alt rule in a singleton rule:

anyDate : dateExpr ;
dateExpr
    :   attr op=( '+' | '-' ) dt_interval=ISO8601_INTERVAL    #dateexpr_Op
    |   DATETIME_NAME                                         #dateexpr_Named
    |   d=( DATETIME_LITERAL | DATE_LITERAL | TIME_LITERAL )  #dateexpr_Literal
    |   attr                                                  #dateexpr_Attr
    |   '(' date_expr ')'                                     #dateexpr_Paren
    ;

The ANTLR tool will then generate the listener interface (and/or visitor interface) with AnyDateContext onEntry and onExit methods.



标签: antlr4