I’m writing a grammar that supports arbitrary boolean expressions. The grammar is used to represent a program, which is later passed through the static analysis tool. The static analysis tool has certain limitations so I want to apply the following rewrite rules:
Strict inequalities are approximated with epsilon:
expression_a > expression_b -> expression_a >= expression_b + EPSILON
Inequality is approximated using “or” statement:
expression_a != expression_b -> expression_a > expression_b || expression_a < expression_b
Is there any easy way to do it using ANTLR? Currently my grammar looks like so:
comparison : expression ('=='^|'<='^|'>='^|'!='^|'>'^|'<'^) expression;
I’m not sure how to apply a different rewrite rule depending on what the operator is. I want to tree stay as it is if the operator is (“==”, “<=” or “>=”) and to recursively transform it otherwise, according to the rules defined above.
You can do it partly.
You can’t tell ANTLR to rewrite
a > bto^('>=' a ^('+' b epsilon))and then definea != bto become^('||' ^('>' a b) ^('<' a b))and then have ANTLR automatically rewrite both^('>' a b)and^('<' a b)to^('>=' a ^('+' b epsilon))and^('<=' a ^('-' b epsilon))respectively.A bit of manual work is needed here. The trick is that you can’t just use a token like
>=if this token isn’t actually parsed. A solution to this is to use imaginary tokens.A quick demo:
The parser generated from the grammar above will produce the following:
a == ba != ba > ba < b