我正在 Jison 中编写一个简单的表达式解析器,允许任意数量的换行符跟随表达式中的二元运算符。到目前为止,这是我的语法:
{
"operators": [
["left", "+", "-"],
["left", "*", "/", "%"]
],
"bnf": {
"program": [
["statement EOF", "return $1;"]
],
"statement": [
["expression newlines", "$$ = $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 + newlines expression", "$$ = $1 + ' + ' + $4;"],
["expression - newlines expression", "$$ = $1 + ' - ' + $4;"],
["expression * newlines expression", "$$ = $1 + ' * ' + $4;"],
["expression / newlines expression", "$$ = $1 + ' / ' + $4;"],
["expression % newlines expression", "$$ = $1 + ' % ' + $4;"]
],
"newlines": [
["NEWLINE", ""],
["newlines NEWLINE", ""]
]
}
}
如您所见,我正在为每个二元运算符编写两条规则。这在我看来是非常多余的。我宁愿有一个匹配零个或多个NEWLINE
令牌(Kleene star)而不是一个或多个令牌(Kleene plus)的产品。你会如何在 Jison 中做到这一点?