If what you need is simple enough, you might get by by modifying the calculator. For instance:
Add an IDENTIFIER
token after NUMBER
in the list of tokens:
[a-z] return 'IDENTIFIER'
This allows a single lower case letter to serve as identifie.
Modify the e '^' e
rule to return a string rather than the computed value:
| e '^' e
{$$ = "Math.pow(" + $1 + "," + $3 + ");"}
Add a new rule to the list of rules for e
:
| IDENTIFIER
(No explicit action needed.)
With these changes parsing, x^2
results in "Math.pow(x,2);"
To support the operators, the other rules would have to be modified like the one for e '^' e
to return strings rather than the result of the math.
This is extremely primitive and won't optimize things that could be optimized. For instance, 1^2
will be output as "Math.pow(1, 2)"
when it could be optimized to 1
.