Created
August 17, 2012 11:50
-
-
Save dxlbnl/3378262 to your computer and use it in GitHub Desktop.
Pyjaco IST design
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
import ast | |
def transform(node, transformations): | |
""" | |
Match node a node in transformations. | |
""" | |
match = transformations.get(type(node)) | |
if match: | |
# we found a match, convert it to ist. | |
return match.from_ast(node) | |
else: | |
print "did not find type:", type(node) | |
# some random ist nodes. | |
class Module: | |
def __init__(self): | |
print "Creating Module" | |
self.stmts = [] | |
@staticmethod | |
def from_ast(node): | |
mod = Module() | |
for stmt in node.body: | |
mod.add_stmt(transform(stmt, to_ist)) | |
return mod | |
def add_stmt(self, stmt): | |
self.stmts.append(stmt) | |
def __str__(self): | |
return '\n'.join(str(stmt) for stmt in self.stmts) | |
class Expr: | |
def __init__(self, value): | |
print "Creating Expr with value", value | |
self.value = value | |
@staticmethod | |
def from_ast(node): | |
return Expr(transform(node.value, to_ist)) | |
def __str__(self): | |
return str(self.value) | |
class Str: | |
def __init__(self, s): | |
print "Creating Str({})".format(s) | |
self.s = s | |
@staticmethod | |
def from_ast(node): | |
return Str(node.s) | |
def __str__(self): | |
return self.s | |
#The ast -> ist transformation table | |
to_ist = { | |
ast.Module : Module, | |
ast.Expr : Expr, | |
ast.Str : Str | |
} | |
source = "'bla'" | |
print transform(ast.parse(source), to_ist) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment