[pypy-svn] r12995 - pypy/branch/pycompiler/module/recparser
ludal at codespeak.net
ludal at codespeak.net
Thu Jun 2 12:48:39 CEST 2005
Author: ludal
Date: Thu Jun 2 12:48:39 2005
New Revision: 12995
Added:
pypy/branch/pycompiler/module/recparser/codegen.py
Log:
* starting a rpython compiler implementation based on compiler module
Added: pypy/branch/pycompiler/module/recparser/codegen.py
==============================================================================
--- (empty file)
+++ pypy/branch/pycompiler/module/recparser/codegen.py Thu Jun 2 12:48:39 2005
@@ -0,0 +1,108 @@
+
+import pythonutil
+from compiler.visitor import ASTVisitor
+from compiler.bytecode import *
+
+def compile(source, filename, mode, flags=None, dont_inherit=None):
+ """Replacement for builtin compile() function"""
+ # source to ast conversion
+ if mode == "single":
+ tree = pythonutil.ast_single_input( source )
+ elif mode == "eval":
+ tree = pythonutil.ast_eval_input( source )
+ elif mode == "exec":
+ tree = pythonutil.ast_srcfile_input( source, filename )
+ else:
+ raise RuntimeError("Not found")
+ return compile_ast( tree, filename, flags=None, dont_inherit=None)
+
+
+def compile_ast( tree, filename, flags=None, dont_inherit=None ):
+ v = CompilerVisitor( filename, flags, dont_inherit )
+ tree.visit(v)
+ return tree, v
+
+
+class PrintContext(object):
+ def __init__(self):
+ self.lineno = 0
+
+ def emit(self, insn ):
+ print "% 5d %s" % (self.lineno, insn)
+
+ def emit_arg(self, insn, arg ):
+ print "% 5d %8s %s" % (self.lineno, insn, arg)
+
+ def set_lineno(self, lineno):
+ self.lineno = lineno
+
+
+class Block(object):
+ def __init__(self):
+ self.insns = []
+ self.start_pos = 0
+
+ def append(self, insn ):
+ self.insns.append( insn )
+
+ def get_size(self):
+ s = 0
+ for i in insns:
+ s += i.size()
+ return s
+
+ def set_start_pos(self, pos ):
+ self.start_pos = pos
+
+
+
+class CompilerVisitor(ASTVisitor):
+ """Basic code generator for Python Bytecode"""
+ def __init__(self, filename, flags, dont_inherit ):
+ self.scopes = []
+ self.blocks = []
+ self.code = None
+ self.current_block = None
+
+ ### Visitor functions
+
+ def visitModule( self, node ):
+ # setup doc
+ self.newBlock()
+ node.node.visit( self )
+
+ # build code object
+ for block in self.blocks:
+ pass
+
+ def visitExpression(self, node):
+ pass
+
+ def visitFunction(self, node):
+ pass
+
+ def visitIf(self, node):
+ end = Block()
+ for test, suite in node.tests:
+ if is_constant_false(test):
+ continue
+ test.visit(self) # emit test code in current block
+ self.a
+ nextTest = Block()
+
+ ### Block handling functions
+ def newBlock(self):
+ """Create a new block and make it current"""
+ b = Block()
+ self.blocks.append(b)
+ self.current_block = b
+ return b
+
+
+
+if __name__ == "__main__":
+ testf = file("pycodegen2.py").read()
+ ast, v = compile(testf,"pycodegen2.py","exec")
+ print ast
+ print v
+
More information about the Pypy-commit
mailing list