CS 3723/3721 Programming Languages
Shift-Reduce Parser: Homework, Fall 2004


The Homework: This may be the only homework this semester to be handed directly to the instructor. Please hand in answers to the example at the end. It can be hand-written on a sheet of paper.


Overview: Parsers are algorithms and programs that will unravel the syntax of a sentence described by a formal grammar. Most parsers will not handle an arbitrary grammar, but place limitations on the form of grammar allowed. These parsers go through the motions of building a parse tree without actually generating the tree. While the parse is going on, extra code can carry a variety of tasks related to translating the source into some other form.


Initial Example:


New example without an answer:

    Consider the following grammar:
    
            S ---> b M b              ("S" is the start symbol)
            M ---> ( L
            M ---> a
            L ---> M a )
    
    Use the following shift-reduce table for this grammar:
    
               |  b  |  a  |  (  |  )  |  $   |
          -----+-----+-----+-----+-----+------+
            S  |     |     |     |     |  acc |     ( "s" means "shift")
            M  |  s  |  s  |     |     |      |
            L  |  r  |  r  |     |     |      |     ( "r" means "reduce")
            b  |     |  s  |  s  |     |  r   |
            a  |  r  |  r  |     |  s  |      |     ( "acc" means "accept")
            (  |  s  |  s  |  s  |     |      |
            )  |  r  |  r  |     |     |      |
    
    1. Carry out the shift-reduce parse of the following sentence, showing the stack, current symbol, remaining symbols, and next action to take at each stage. (This sentence has the extra artifical symbol $ stuck in at the beginning and the end.)
      
           $ b ( ( a a ) a ) b $
      
      (Remember that you should initially shift the starting $ and then shift the next symbol.)

    2. Give the resulting parse tree.


    Key ideas: The shift-reduce parser using a stack is a common strategy. The version shown here is relatively simple, but there are much more sophisticated versions called LR parsers and LALR parsers (beyond the scope of the course). These parsers are the most capable and are the ones usually employed for real compilers. An LR parser handles the most complex grammar possible using a simple left-to-right scan, and it can determine a syntax error at the earliest possible point.


    Revision date: 2004-02-05. (Please use ISO 8601, the International Standard Date and Time Notation.)