产生式如下
Expr = Add <EOF>
Add = Multiply | Add + Multiply | Add - Multiply
Multiply = Num | Multiply * Multiply | Multiply / Multiply | ( Add )
Num = 有理数
对于括号的处理,关键在MultiplicativeExpression方法中判断运算符左右两侧的变量是否为(Add)
function MultiplicativeExpression(source) {
if (source[0].type === "Number") {
let node = {
type: "MultiplicativeExpression",
children: [source[0]]
}
source[0] = node;
return MultiplicativeExpression(source);
}
if (source[0].type === "parentness") {
let addExpr = [];
let i = 0;
while (i++ < source.length && source[i].type !== "parenthese") {
addExpr.push(source[i]);
}
source.splice(0, addExpr.length + 2, AdditiveExpression([...addExpr]));
source[0].type = "MultiplicativeExpression";
}
if (source[2] && source[2].type === "parenthese") {
let addExpr = [];
let i = 2;
while (i++ < source.length && source[i].type !== "parenthese") {
addExpr.push(source[i]);
}
source.splice(2, addExpr.length + 2, AdditiveExpression([...addExpr]));
source[2].type = "MultiplicativeExpression";
}
...
展开