Reputation:
Trying to write a antlr grammar that parse the arithmetic expression for only same typed variable. If it is not a same type as left or right side, it should not be parse. This is what I have;
stat
: Left = VARIABLE Op = ASSIGMENT Right = expr # Assigment
;
expr
: '(' Exp = expr ')' # Parens
| MINUS Exp = expr # UnaryMinus
| Left = expr Op = (TIMES | DIV) Right = expr # MulDiv
| Left = expr Op = (PLUS | MINUS) Right = expr # AddSub
| (VARIABLE | CONSTANT) # Element
;
ASSIGMENT : '=' ;
PLUS : '+' ;
MINUS : '-' ;
TIMES : '*' ;
DIV : '/' ;
LPAREN : '(' ;
RPAREN : ')' ;
I don't want anything like x = 5 + 'f' or x = c - 5, (if c is variable that is not integer)
Upvotes: 1
Views: 161
Reputation: 4799
It's called Semantic analysis.
When parsing is done you have to walk through the generated AST and check correctness of each expression and variable.
Upvotes: 1