parsingprogramming-languagesbottom-up

What production rule should I use to reduce in bottom-up parsing?


So far, my understanding of the algorithm of bottom-up parsing is this.

  1. shift a token into the stack
  2. check the stack from top if some elements including the top can be reduced by some production rule
  3. if the elements can be reduced, pop and push the left hand side of the production rule.
  4. continue those steps until top is the start symbol and next input is EOF

So to support my question with an example grammar,

S → aABe

A → Abc
A → b
B → d

if we have input string as

abbcde$

we will shift a in stack and because there are no production rule that reduces a, we shift the next token b. Then we can find a production rule A → b and reduce b to A.

Then my question is this. We have aA on stack and the next input is b. Then how can the parser determine whether we reduce b to A we wait for c to come and use the rule A → Abc?

Well of course, reducing b to A at that point results in an error. But how does the parser know at that point that we should wait for c?

I'm sorry if I missed something while studying.


Solution

  • That's an excellent question, and it will be addressed in the next part of your course.

    For now, it's sufficient to pretend that there is some magic black box which tells the parser when it should reduce (and, sometimes, which of several possible productions to use).

    The various parsing algorithms explain the construction of this black box. Note that one possible solution is to fork reality and try both actions in parallel, but a more common solution is to process the grammar in order to work out how to predict the correct action.