an ANTLR Grammar for a statement or an exit statement
I wrote down the following statement in an ANTLR grammar:
loopStatement
: 'loop' (statement|exit)* 'end' 'loop' ';'
;
If I understand correctly, (statement|exit)*
means that I can have a statement
or an exit statement
. That is
i.e statement_1 exit_1
, or statement_1
, or statement_1 statement_2, exit_1
, right?
this works:
loop
x:=x+1; <<< statement_1
exit when x=9; <<<<exit_1
end loop;
this works as well (no exit
):
loop
x:=x+1; <<< statement_1
<<<<exit_1 (no exit)
end loop;
but this 开发者_如何学GoDOES NOT work (no statement
):
loop
<<< statement_1
exit when x=9; <<<<exit_1
end loop;
Is there anything wrong with my grammar?
pantelis wrote:
If I understand correctly,
(statement|exit)*
means that I can have astatement
or anexit statement
.
To be precise, (statement|exit)*
matches the empty string, or zero or more statement
or exit
statements (in no particular order!). So it'd match:
- statement statement statement ...
- exit exit exit ...
- exit exit statement statement exit ...
- ...
But, why not make your exit
statement just a regular statement? I small demo:
loopStatement
: 'loop' statement* 'end' 'loop' ';'
;
statement
: 'exit' 'when' expression ';' // exit statement
| ID ':=' expression ';' // assignment
;
expression
: equalityExpression
;
equalityExpression
: addExpression ('=' addExpression)*
;
addExpression
: atom ('+' atom)*
;
atom
: ID
| Number
| '(' expression ')'
;
ID
: 'a'..'z'+
;
Number
: '0'..'9'+
;
which properly parses all your 3 examples:
1
loop
x:=x+1;
exit when x=9;
end loop;
2
loop
x:=x+1;
end loop;
3
loop
exit when x=9;
end loop;
4
Or nothing at all:
loop
end loop;
精彩评论