I must do a grammar for some compiler that I’m creating:
Binary operators && and || and unary operators # and * in a way that they:
I) || that have precedence over &&
II) && be associative to the left : a && b && c means ((a&&b)&&c)
III) || be associative to the right
IV) unary operators have equal precedence and more than binary operators
I was thinking something like this:
E -> E || T | E && T | T
T -> T # F | T * F
F -> (E) | Numbers
Numbers -> 0 | 1 | 2 | 3 | ... | 9
Would it be wrong ?
Any ideas ?
For simple expressions like these, you could always start from the least precedence.
So you want to have a bunch of
&&ed expressions, each of which are||ed expressions of equally precedented unary operators.Before writing that down, look at these two rules:
and
The first rule makes
+left associative while the second one makes it right associative (think about it). So you want your&&to be left associative and||to be right associative:The rule for unary operators is fairly easy:
Finally, the most precedent is parentheses, which is as if you had an unbreakable token. Except, inside the parentheses you can have any expression:
The
numberitself can be expressed by a regular expression, such as'[1-9][0-9]*'