How to tell the precedence of operators in a context free grammar

♀尐吖头ヾ 提交于 2020-01-13 19:34:09

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/26471876/how-to-tell-the-precedence-of-operators-in-a-context-free-grammar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!