Skip to content

Instantly share code, notes, and snippets.

@cheery
Created May 3, 2015 21:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cheery/8ebd82b42024eaf5a635 to your computer and use it in GitHub Desktop.
Save cheery/8ebd82b42024eaf5a635 to your computer and use it in GitHub Desktop.
Hand-written LR parser
def state_0(ch):
if ch == None:
return None
if ch == "1":
return state_4
if ch == 'int':
return state_1
if ch == 'plus':
return state_1
assert False
def state_1(ch):
if ch == None:
return None
if ch == "+":
return state_2
assert False
def state_2(ch):
if ch == "1":
return state_4
if ch == 'int':
return state_3
assert False
def state_3(ch):
if ch == None:
return reduce(3, 'plus', ch)
if ch == '+':
return reduce(3, 'plus', ch)
assert False
def state_4(ch):
if ch == None:
return reduce(1, 'int', ch)
if ch == '+':
return reduce(1, 'int', ch)
assert False
def reduce(count, goto, ch):
print 'reduce', count, goto
for i in range(count):
stack.pop(-1)
stack.append(stack[-1](goto))
return stack[-1](ch)
stack = [state_0]
for ch in ["1", "+", "1", "+", "1", None]:
state = stack[-1](ch)
if state is None:
print 'accept'
break
print 'shift', state, repr(ch)
stack.append(state)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment