2

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?
JoseHdez_2
  • 4,040
  • 6
  • 27
  • 44
  • if your language has only assignments and expressions, you could use a global symbol table to store the value of each identifier during parsing so you can calculate the value of each expression on the fly. – 1010 May 19 '15 at 15:22
  • Thanks for replying. Although I think that's what I was already doing... (symbol table being a hash in my case). The question was asking how to parse the resulting `2+3*5` in the *same* grammar. Maybe my desired approach was fundamentally wrong? Regardless, I have no pressing need for a reply anymore, since it turns out my teacher had misunderstood the complexity of the original grammar and has now accepted the project. This question will remain open in case anyone wants to take a shot at giving an answer. – JoseHdez_2 May 21 '15 at 17:11

0 Answers0