Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 314
frankencode Avatar asked Dec 05 '25 09:12

frankencode


1 Answers

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)

like image 149
Ivan Kochurkin Avatar answered Dec 07 '25 16:12

Ivan Kochurkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!