简体   繁体   中英

ANTLR4 NEWLINE at each expression but optional for the last

I am trying to build a simple application that is recognizing simple mathematical expressions, each being separated by NEWLINE. Everything works fine, but I don't know how to make the NEWLINE optional after the last expression. This is part of my grammar file with only the necessary stuff:

statements
: statement+ EOF
;

statement
: variableId ASSIGN expression NEWLINE+                                     
;

NEWLINE             : '\r'? '\n';

Currently also the last statement must be followed by NEWLINE. If a make the NEWLINE optional (*) then I am able to insert 2 statements on the same line, which I do not want.

Thanks in advance.

Try:

statements
: statement (NEWLINE+ statement)* NEWLINE* EOF
;

Statement
: variable ASSIGN expression
;

This approach uses the NEWLINE as a separator rather than a terminator, which seems to be what you're looking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM