ANTLR Grammar for Operator or Output Operator

I wrote the following expression in the ANTLR grammar:

loopStatement
    : 'loop'  (statement|exit)* 'end' 'loop' ';'
    ;

If I understand correctly, it (statement|exit)*means that I can have statementor exit statement. That is, ie statement_1 exit_1, or statement_1, or statement_1 statement_2, exit_1, right?
My parser also works when there is no approval.
For instance:

it works:

loop
x:=x+1;   <<< statement_1
exit when x=9; <<<<exit_1
end loop;

this works too (no exit):

loop
x:=x+1;   <<< statement_1
          <<<<exit_1  (no exit)
end loop;

but this does NOT work (no statement):

loop
          <<< statement_1
exit when x=9; <<<<exit_1
end loop;

Is there something wrong with my grammar?

+3
source share
1 answer

pantelis wrote:

If I understand correctly, it (statement|exit)*means that I can have statementor exit statement.

, (statement|exit)* statement exit ( !). , :

  • ...
  • ...
  • exit exit statement statement exit...
  • ...

exit ? :

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'+
  ;

3 :


1

loop
  x:=x+1;
  exit when x=9;
end loop;

enter image description here


2

loop
  x:=x+1;

end loop;

enter image description here


3

loop

  exit when x=9;
end loop;

enter image description here


4

:

loop

end loop;

enter image description here

+3

All Articles