Search code examples
compiler-constructionantlrantlr4ebnf

ANTLR: ignore statements in parser


I have defined the following things in ANTLR4:

prog: stat+ ;

stat: 
    ID '=' expr STATEMENT_TERMINATOR                            #Assignment
|   QUESTIONMARK text=STRING? expr? STATEMENT_TERMINATOR        #Print
|   ID '=' QUESTIONMARK prompt=STRING? STATEMENT_TERMINATOR     #Input
|   NEWLINE                                                     #StatementTerminator
|   STATEMENT_TERMINATOR                                        #NewLine
;

I wonder how I can make the parser ignore the NEWLINE and STATEMENT_TERMINATORS at the end of my program. Reason why I ask is:

I want to return the result of the last statement as the result - but if there is an additional NEWLINE or STATEMENT_TERMINATOR at the end, I get no meaningful return value.

-> skip

also doesn't work: "Reference to undefined rule 'skip'".

Can I make ANTLR ignore statements at the parser level as well?


Solution

  • You can use skip command only for lexer rules, not parser rules. In your case I suggest to rewrite grammar by the following way:

    prog: stat+ ;
    
    stat: 
        ID '=' expr STATEMENT_TERMINATOR                            #Assignment
    |   QUESTIONMARK text=STRING? expr? STATEMENT_TERMINATOR        #Print
    |   ID '=' QUESTIONMARK prompt=STRING? STATEMENT_TERMINATOR     #Input
    ;
    
    NEWLINE: [\r\n] -> skip;
    STATEMENT_TERMINATOR: ';' -> skip;
    

    Also you can use channel(HIDDEN) command for these terminals.

    Onward In Visitor (or Listener) you can access to the last statement by such way: context.stat(context.stat.Length - 1)