Created
July 21, 2008 21:45
-
-
Save gelicide/309 to your computer and use it in GitHub Desktop.
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
# Translation note: | |
# init() will not be needed. Our input is already ready to be read. (Alliteration :D) | |
# Translated from http://compilers.iecc.com/crenshaw/tutor1.txt | |
TAB = "\t" | |
class scanner: | |
def __init__(self): | |
self.input = list(raw_input()) | |
self.look = 0 | |
def step(self): | |
'''Move look forward''' | |
self.look += 1 | |
def nextchar(self): | |
'''Returns the next char to be read, but | |
does not progress look | |
''' | |
return self.input[self.look + 1] | |
def char(self): | |
'''Current char''' | |
return self.input[self.look] | |
scan = scanner() | |
def error(s): | |
print "Error: %s" % s | |
def abort(s): | |
error(s) | |
exit() | |
def expected(s): | |
abort("Expected %s" % s) | |
def match(x): | |
if scan.char() == x: | |
scan.step() | |
else: | |
expected(x) | |
def getname(): | |
if not scan.char().isalpha(): | |
expected('Name') | |
ret = scan.char().upper() | |
scan.step() | |
return ret | |
def getnum(): | |
if not scan.char().isdigit(): | |
expected('Integer') | |
ret = scan.char() | |
scan.step() | |
return ret | |
def emit(s, ln=False): | |
print TAB, s | |
if ln: | |
def term(): | |
emit("MOVE #" + getnum() + ",D0", True) | |
def expression(): | |
term() | |
emit("MOVE D0, D1", True) | |
if scan.char() == "+": | |
add() | |
elif scan.char() == "-": | |
subtract() | |
else: | |
expected("Addop") | |
def add(): | |
match("+") | |
term() | |
emit("ADD D1,D0", True) | |
def subtract(): | |
match("-") | |
term() | |
emit("SUB D1,D0", True) | |
emit("NEG D0", True) | |
if __name__ == "__main__": | |
expression() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment