Background
I'm using PEG.js online.
I have a PEG that takes a function (only math assignments and expressions are valid) and returns a literal math expression equivalent, like 3+2*5
.
Example input (function):
main()
{
a = 1
b = a
return a+b
}
Example output (expression): (1)+((1))
Specifics
To 'de-abstract' each variable:
First we read each statement, and we do a hash assignment for each assignment statement.
Example resulting hash:
{
a => 1
b => a
}
Then we take the returned expression and iteratively substitute any tokens that are valid keys by their value. Do as many iterations as assignment statements there were (in this case, 2).
- Example return expression:
a+b
- After iteration 1:
(1)+(a)
- After iteration 2:
(1)+((1))
which is the final output.
Problem
I used to just take that output and call eval()
on it, to get the final value.
But this is an assignment (to build a PEG parser), and the teacher frowned upon "outsourcing" the parsing of the math expression itself.
I have another (much simpler) PEG that takes a math expression and calculates its value. Possible options that I want to avoid:
- I could pipeline the output of the first PEG into the second.
- I could reduce the scope of my PEG and say it only calculates the raw, literal math expression (and not its value as well).
So, the problem is that I want to do both steps in the same grammar, but I don't know how.
I have to take a previous 'dive' to de-abstract the variables into literal numbers.
- If I can calculate the math at the same time that I'm substituting the variables-- how?
- If not-- how can I, once I have 'dived' into the grammar parsing, take a different path?