我已经看过用于JavaScript的PEG.js解析器生成器。它看起来很漂亮!
我没有太多指定语法的经验。我正在寻求帮助,将1的示例语法扩展到允许
你能帮助我找到帮助吗?
答案 0 :(得分:5)
这里的快速演示:
{
variables = {
PI : Math.PI,
E : Math.E
};
functions = {
squared : function(n) { return n * n; },
incr : function(n) { return n + 1; }
}
}
start
= additive
additive
= left:multiplicative "+" right:additive { return left + right; }
/ multiplicative
multiplicative
= left:power "*" right:additive { return left * right; }
/ power
// evaluated left to right!
power
= left:primary "^" right:additive { return Math.pow(left, right); }
/ primary
primary
= integer
/ "(" e:additive ")" { return e; }
/ i:id "(" e:additive ")" { return functions[i.join("")](e); }
/ i:id { return variables[i.join("")]; }
integer
= digits:[0-9]+ { return parseInt(digits.join(""), 10); }
id
= [a-zA-Z]+
如果您现在使用输入
测试解析器(在线)PI+incr(squared(3))^2
您将看到它被评估为:
103.1415926535898
答案 1 :(得分:-1)
{
variables = {
PI : Math.PI,
E : Math.E
};
functions = {
squared : function(n) { return n * n; },
incr : function(n) { return n + 1; }
}
}
start
= additive
additive
= left:multiplicative "+" right:additive { return left + right; }
/ multiplicative
multiplicative
= left:power "*" right:power { return left * right; }
/ power
// evaluated left to right!
power
= left:primary "^" right:primary { return Math.pow(left, right); }
/ primary
primary
= number
/ integer
/ "(" e:additive ")" { return e; }
/ i:id "(" e:additive ")" { return functions[i.join("")](e); }
/ i:id { return variables[i.join("")]; }
number_frac
= "." chars:[0-9]* { return "." + chars.join(''); }
number
= chars:[0-9]+ frac:number_frac? { return parseFloat(chars.join('') + frac); }
integer
= digits:[0-9]+ { return parseInt(digits.join(""), 10); }
id
= [a-zA-Z]+