我正在用Jison编写一个简单的表达式解析器。下面是我的语法:
{
"operators": [
["left", "+", "-"],
["left", "*", "/", "%"]
],
"bnf": {
"program": [
["statement EOF", "return $1;"]
],
"statement": [
["expression NEWLINE", "$$ = $1 + ';';"]
],
"expression": [
["NUMBER", "$$ = yytext;"],
["expression binary expression", "$$ = $1 + $2 + $3;"]
],
"binary": [
["+", "$$ = ' + ';"],
["-", "$$ = ' - ';"],
["*", "$$ = ' * ';"],
["/", "$$ = ' / ';"],
["%", "$$ = ' % ';"],
["binary NEWLINE", "$$ = $1;"]
]
}
}
当我尝试运行它时,它给了我以下错误:
Conflict in grammar: multiple actions possible when lookahead token is + in state
13
- reduce by rule: expression -> expression binary expression
- shift token (then go to state 8)
Conflict in grammar: multiple actions possible when lookahead token is - in state
13
- reduce by rule: expression -> expression binary expression
- shift token (then go to state 9)
Conflict in grammar: multiple actions possible when lookahead token is * in state
13
- reduce by rule: expression -> expression binary expression
- shift token (then go to state 10)
Conflict in grammar: multiple actions possible when lookahead token is / in state
13
- reduce by rule: expression -> expression binary expression
- shift token (then go to state 11)
Conflict in grammar: multiple actions possible when lookahead token is % in state
13
- reduce by rule: expression -> expression binary expression
- shift token (then go to state 12)
States with conflicts:
State 13
expression -> expression binary expression . #lookaheads= NEWLINE + - * / %
expression -> expression .binary expression
binary -> .+
binary -> .-
binary -> .*
binary -> ./
binary -> .%
binary -> .binary NEWLINE
然而,它最终仍然产生正确的输出。例如,2 + 3 * 5 / 7 % 11
被正确地翻译成2 + 3 * 5 / 7 % 11;
。
在我看来,我的语法似乎是明确的,那么Jison为什么要抱怨呢?
Update:正如@icktoofay解释的,这是一个运算符结合性问题。通过将操作符解析为非终端符号,操作符优先级和结合性信息将丢失。因此,我解决了这个问题,如下:
{
"operators": [
["left", "+", "-"],
["left", "*", "/", "%"]
],
"bnf": {
"program": [
["statement EOF", "return $1;"]
],
"statement": [
["expression NEWLINE", "$$ = $1 + ';';"]
],
"expression": [
["NUMBER", "$$ = yytext;"],
["expression + expression", "$$ = $1 + ' + ' + $3;"],
["expression - expression", "$$ = $1 + ' - ' + $3;"],
["expression * expression", "$$ = $1 + ' * ' + $3;"],
["expression / expression", "$$ = $1 + ' / ' + $3;"],
["expression % expression", "$$ = $1 + ' % ' + $3;"],
["expression + NEWLINE expression", "$$ = $1 + ' + ' + $4;"],
["expression - NEWLINE expression", "$$ = $1 + ' - ' + $4;"],
["expression * NEWLINE expression", "$$ = $1 + ' * ' + $4;"],
["expression / NEWLINE expression", "$$ = $1 + ' / ' + $4;"],
["expression % NEWLINE expression", "$$ = $1 + ' % ' + $4;"]
]
}
}
也就是说,该语法只允许一个可选的换行符跟在二进制操作符后面。如何重写它以允许任意数量的换行符跟随二进制操作符?也必须有一些方法,我不必为每个操作符写两个规则。
我不是很熟悉Jison,但是看起来您定义的规则是这样的:
expression ::= number;
expression ::= expression binary expression;
考虑表达式1 - 2 - 3
。这可以解释为(1 - 2) - 3
或1 - (2 - 3)
。是哪一个?你的语法含糊不清。一般的数学规则说它应该是左结合律。你需要让你的语法反映出:
expression ::= number;
expression ::= expression binary number;