简体   繁体   中英

Infinite recursion - predictive parser

Well, I have a problem to process this grammar:

R -> a R | e

e = empty production.

When I try derivate these inputs: "a" , "aa" , "aaa" .. I get in a infinite recursion.

def match(t):
    global pos
    global lookahead
    if lookahead == t:
        try:
            pos += 1
            lookahead = inputstr[pos]
        except IndexError:
            pass
    else:
        raise SyntaxError("syntax error!")

def r():
    if lookahead == 'a':
        match('a') 
        r()
    else:
        pass # e-production

inputstr = raw_input()
lookahead = inputstr[0]
pos = 0
r()

I know, the lookahead is not changing, but how can I solve this? I'm beginner in grammars and parsers.

The pass inside the IndexError is wrong. Once the input is exhausted, and every match action was correct, the program should terminate with an OK status. However, in your original code, it does not terminate , but keeps reading beyond input buffer and catching its own IndexErrors. This causes the infinite recursion. There are three places errors are caught in a predictive parser:

  • an incorrect match.
  • falling off a switch-case statement in a variable without epsilon rules.
  • a return from s() when the input hasn't been read until the end.

To fix this I have added the last if statement. Altogether the correct predictive parser is this:

#!/usr/bin/python

import sys

def finish(msg):
    print msg
    sys.exit()

def eat(t):
    global pos
    global lookahead
    if lookahead == t:
        try:
            pos += 1
            lookahead = inputstr[pos]
        except IndexError:
            #pass is wrong here ...
            finish("OK")
    else:
        finish("ERROR")


def r():
    if lookahead == 'a':
        eat('a') 
        r()
    else:
        pass # e-production

inputstr = raw_input()
lookahead = inputstr[0]
pos = 0
r()
##########################
# This needs to be added #
##########################
if pos != len(inputstr):
    finish("ERROR")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM