Skip to content

Instantly share code, notes, and snippets.

@barik
Last active August 29, 2015 13:56
Show Gist options
  • Save barik/9264636 to your computer and use it in GitHub Desktop.
Save barik/9264636 to your computer and use it in GitHub Desktop.
AST Example
class BinOp(Node):
def __init__(self, left, op, right, lineno):
self.op = op
self.left = left
self.right = right
self.lineno = lineno
def __str__(self):
return 'BinOp({0}, {1}, {2})'.format(self.op, self.left, self.right)
def emit(self, depth):
print self.__str__()
def type_check(self):
left = self.left.type_check()
right = self.right.type_check()
# Used for addition and multiplication, but also for logical OR and AND. These items
# return the same as their input.
if self.op == '+' or self.op == '*':
if left == right == ('int', []) or left == right == ('bool', []):
return left
else:
raise TypecheckException("incompatible types to binary operator " + self.op, self.lineno)
# Items that work with int and bool but return bool.
elif self.op == '=' or self.op == '!=':
if left == right == ('int', []) or left == right == ('bool', []):
return 'bool', []
else:
raise TypecheckException("incompatible types to comparison operator", self.lineno)
# Items that work with int but return bool.
elif (self.op == '>' or
self.op == '<' or
self.op == '>=' or
self.op == '<='):
if left == right == ('int', []):
return 'bool', []
else:
raise TypecheckException("incompatible types to binary operator " + self.op, self.lineno)
# Items that work with int and return int.
elif self.op == '/' or self.op == '%' or self.op == '-':
if left == right == ('int', []):
return left
else:
raise TypecheckException("incompatible types to binary operator", self.lineno)
...
class If(Node):
def __init__(self, test, body, orelse, lineno):
self.test = test
self.body = body
self.orelse = orelse
self.lineno = lineno
pass
def __str__(self):
return 'If({0}, {1}, {2}, {3})'\
.format(self.test, self.body, self.orelse, self.lineno)
def emit(self, depth):
print self.__str__()
def type_check(self):
test = self.test.type_check()
if test != ('bool', []):
raise TypecheckException("if test is not bool", self.lineno)
for s in self.body:
s.type_check()
if self.orelse is not None:
self.orelse.type_check()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment