Created
April 9, 2019 14:48
-
-
Save WangYihang/f11232e9315f44b20e15552b4ad25057 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import string | |
''' | |
Grammar: | |
E -> A(E, E) | |
E -> epsilon | |
A -> a|b|...|z | |
First(E) = {a, b, ... , z, epsilon} | |
First(A) = {a, b, ... , z} | |
Follow(E) = {',', )} | |
Follow(A) = {(} | |
Select(E -> A(E, E)) = {a, b, ... , z} | |
Select(E -> epsilon) = {',', )} | |
Select(A -> a|b|...|z) = {a, b, ... , z} | |
''' | |
def error(reason): | |
print("Error occured: %s" % reason) | |
exit(1) | |
def precedure_E(token): | |
global p | |
print("Precedure of E involved") | |
if token in [',', ')']: | |
print("Production: E -> epsilon") | |
''' | |
E -> epsilon should not consume a token in token list | |
''' | |
p -= 1 | |
return | |
elif token in string.lowercase: | |
print("Production: E -> A(E, E)") | |
precedure_A(token) | |
token = getToken() | |
if token != '(': | |
error("'(' excepted, got %r" % (token)) | |
token = getToken() | |
precedure_E(token) | |
token = getToken() | |
if token != ',': | |
error("',' excepted, got %r" % (token)) | |
token = getToken() | |
precedure_E(token) | |
token = getToken() | |
if token != ')': | |
error("')' excepted, got %r" % (token)) | |
else: | |
error("',' / ')' or lower case letter excepted, got %r" % (token)) | |
def precedure_A(token): | |
print("Precedure of A involved") | |
print("Production: A -> a|b|...|z") | |
if token in string.lowercase: | |
print("A = %r" % (token)) | |
return | |
else: | |
error("lower case letter excepted, got %r" % (token)) | |
data = 'a(b(,c(,)),d(,))' | |
data = 'a(b(,c(,)),d(,),)' | |
data = 'a(b(,c(,)),d(,)' | |
p = 0 | |
def getToken(): | |
global p | |
if p < len(data): | |
token = data[p] | |
print("Token %r dispatched" % (token)) | |
p += 1 | |
return token | |
return '' | |
def main(): | |
print("Data: %s" % (data)) | |
precedure_E(getToken()) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment