用PEG.js解析计算

时间:2016-02-16 14:44:13

标签: javascript parsing

我正在尝试使用peg.js库来解析数学表达式。 我在online peg.js中输入了以下语法:

start
    = any

additive
    = left:primary "+" right:any { return left + right; }

multiplicative
    = left:primary "*" right:any { return left * right; }

any
    = multiplicative
    / additive
    / primary

primary
    = float
    / integer
    / "(" any:any ")" { return any; }
    / "" { return 0; }

float "float"
    = left:[0-9]+ "." right:[0-9]+ { return parseFloat(left.join("") + "." +   right.join("")); }

integer "integer"
     = digits:[0-9]+ { return parseInt(digits.join(""), 10); }

但是当我尝试计算:     3*5+1我得到18

1 个答案:

答案 0 :(得分:2)

我认为下面的代码就是你所追求的。

诀窍是让你最弱的运算符(+)有一个引用乘法规则的规则,这样才能在乘法匹配之前进行加法,直到主表达式匹配才能进行加法。

start
    = any

any
    = additive

additive
    = left:multiplicative "+" right:additive { return left + right; }
    / multiplicative

multiplicative
    = left:primary "*" right:multiplicative { return left * right; }
    / primary


primary
    = float
    / integer
    / "(" any:any ")" { return any; }
    / "" { return 0; }

float "float"
    = left:[0-9]+ "." right:[0-9]+ { return parseFloat(left.join("") + "." +   right.join("")); }

integer "integer"
     = digits:[0-9]+ { return parseInt(digits.join(""), 10); }