如何在上下文自由语法中告诉运算符的优先级 [英] How to tell the precedence of operators in a context free grammar
问题描述
我们如何知道下面的语法中的哪些逻辑操作(或,和不是)具有更高的优先级?这种问题有一个通用的方法吗?
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或Y | Y
X → X or Y | Y
Y→Y和Z | Z
Y → Y and Z | Z
Z→不是Z | (X)|真| false
Z → not Z | (X) | true | false
推荐答案
这是一个示例方法:
expr -> addExpr;
addExpr -> multExpr (('+'|'-') multExpr)*;
multExpr -> terminalExpr (('*'|'/') terminalExpr)*;
terminalExpr -> integer | variable | '(' expr ')';
但是关联性不明确。这是BNF中更明确的方式:
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 ')';
这些语法定义运算符 *
code> + 和 -
具有更高优先级的code> / 。您在解析树中声明具有更高优先级的操作,因此它们将首先由解析器尝试。
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.
这篇关于如何在上下文自由语法中告诉运算符的优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!