How can we know which of the following logical operations ( or, and, not ) in the bellow context free grammar have higher precedence? Is there a general approach to this kind of problems?
X → X or Y | Y
Y → Y and Z | Z
Z → not Z | (X) | true | false
Here's an example approach:
expr -> addExpr;
addExpr -> multExpr (('+'|'-') multExpr)*;
multExpr -> terminalExpr (('*'|'/') terminalExpr)*;
terminalExpr -> integer | variable | '(' expr ')';
But the associativity is ambiguous. Here's a more explicit way in BNF:
expr -> addExpr;
addExpr -> addExpr '+' multExpr | addExpr '-' multExpr | multExpr;
multExpr -> multExpr '*' terminalExpr | multExpr '/' terminalExpr | terminalExpr;
terminalExpr -> integer | variable | '(' expr ')';
These grammars define the operators *
and /
as having more precedence as +
and -
. You declare the operation with higher precedence deeper in the parse tree, so they will be tried first by the parser.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With