jeudi 28 mars 2019

How to implement a correct If Then Else Statement in an Antlr Grammar?

I'm working on a statement's extention on a .g4 grammar (named Simple.g4) in ANTLR, I'm trying to implement an "if then else Statement" including a new instruction called ifStatement in section statement but I'm having issue with the code I generated.

Is this the correct form to implement the if statement?

Here is the code I'm working with using Eclipse IDE + ANTLR Plugin:

grammar Simple;


//PARSER RULES


block       : '{' statement* '}';




statement   : assignment    ';' 
            | deletion      ';' 
            | print         ';'
            | varDec        ';' 
            | ifStatement   ';' 
            | funDec        ';' 
            | block;




assignment  : ID '=' exp;


deletion    : 'delete' ID;                                  

print       : 'print' exp;

exp   : '(' exp ')'                             #baseExp
        | '-' exp                               #negExp     
        | left=exp op=('*' | '/') right=exp     #binExp
        | left=exp op=('+' | '-') right=exp     #binExp
        | ID                                    #varExp     
        | INT                                   #valExp     
        | BOOL                                  #valExp     
        | expression cmp='>' expression         #boolExp    
        | expression cmp='<' expression         #boolExp    /
        | expression cmp='==' expression        #boolExp
        | expression cmp='!=' expression        #boolExp
        | expression cmp='>=' expression        #boolExp
        | expression cmp='<=' expression        #boolExp                                            



// If-Then-Else

 ifStatement : 'if' '(' exp ')' 'then' exp 'else' exp               



// LEXER RULES


TRUE   : 'true' ;
FALSE  : 'false';
IF     : 'if'   ;
THEN   : 'then' ;
ELSE   : 'else' ;
VAR    : 'var'  ;  
INT    : 'int'  ;
BOOL   : 'bool' ;

//IDs

fragment CHAR   : 'a'..'z' |'A'..'Z' ;
ID              : CHAR (CHAR | DIGIT)* ;

fragment DIGIT  : '0'..'9'; 
INT             : DIGIT+;

//Boolean   
BOOL            : 'true' | 'false';

//Escape Sequence
WS              : (' '|'\t'|'\n'|'\r')-> skip;
LINECOMMENTS    : '//' (~('\n'|'\r'))* -> skip;
BLOCKCOMMENTS    : '/*'( ~('/'|'*')|'/'~'*'|'*'~'/'|BLOCKCOMMENTS)* '*/' -> skip;

Aucun commentaire:

Enregistrer un commentaire