具有预定义函数和变量的PEG.js扩展

时间:2014-10-09 19:59:17

标签: javascript parsing peg

我已经看过用于JavaScript的PEG.js解析器生成器。它看起来很漂亮!

我没有太多指定语法的经验。我正在寻求帮助,将1的示例语法扩展到允许

  1. 十进制数字
  2. 运营商^
  3. 预定义函数(不是函数声明,只调用我事先指定的一些函数),其中参数本身是一阶表达式,例如: f(g(2 + 4)+ 3)
  4. 变量A-Z(不是声明,只是用法定义 - 这些是指一个也包含程序的输入框,字母A到Z就足够了)
  5. 你能帮助我找到帮助吗?

2 个答案:

答案 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]+