6.9.3.9. Parser

As described in the Dragon book, 4.7 Fig 4.30. p219, but with the addition of action functions on reduce corresponding to evaluation of S-attributes.

We hope to upgrade this to L-attributes later.

Start python section to interscript/parsers/lalr1.py[21 /24 ] Next Prev Last
   637: #line 814 "lalr1_parser.ipk"
   638:   def parse(self, data, reduce='func'):
   639:     act = self.action_table
   640:     go = self.goto_table
   641:     stack = gstack()
   642: 
   643:     stack.push(0)
   644:     n = len(data)
   645:     ip = 0
   646: 
   647:     while 1:
   648:       s = stack.top
   649:       if ip < len(data): token = data[ip]
   650:       else: token = (EOF,None)
   651:       a = token[0]
   652:       action = act[s][a]
   653:       #print 'Symbol',a,'Value',token[1],'State',s,'Action',action
   654:       if action[0]=='s':
   655:         s = action[1]
   656:         ip = ip + 1
   657:         stack.push(token)
   658:         stack.push(s)
   659:       elif action[0]=='r':
   660:         prodn = action[1]-1
   661:         prod = self.productions[prodn]
   662:         nt = prod.LHS
   663:         #print 'Reduce ',nt,'-->',
   664:         #for sym in prod.RHS: print sym,
   665:         #print
   666:         n = len(prod.RHS)
   667:         vals = []
   668:         while n:
   669:           stack.pop()
   670:           vals.insert(0,stack.pop())
   671:           n = n -1
   672:         vals.insert(0,prod)
   673:         args = tuple(vals)
   674:         #print 'args=',args
   675:         res = None
   676:         if hasattr(prod,reduce):
   677:           if callable(getattr(prod,reduce)):
   678:             res = apply(getattr(prod,reduce),args)
   679:         s = stack.top
   680:         stack.push((nt,res))
   681:         stack.push(go[s][nt])
   682:       elif act[s][a][0]=='a':
   683:         stack.pop()
   684:         res = stack.pop()
   685:         stack.pop()
   686:         assert not stack.s
   687:         print 'Accept'
   688:         return res
   689:       else:
   690:         raise 'Parse Error'
   691: 
End python section to interscript/parsers/lalr1.py[21]