Created
May 3, 2015 21:25
-
-
Save cheery/8ebd82b42024eaf5a635 to your computer and use it in GitHub Desktop.
Hand-written LR parser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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