I have had a look at the PEG.js parser generator for JavaScript. It looks pretty nice!
I don't have much experience with specifying grammars. I am searching for help to extend the example grammar at 1 a bit to allow for
Can you help me with where to find help to do that?
Here's quick demo:
{
  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]+
If you now test the parser (online) with the input:
PI+incr(squared(3))^2
you will see it being evaluated as:
103.1415926535898
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With