Skip to content

Instantly share code, notes, and snippets.

@atton
Created November 26, 2013 13:07
Show Gist options
  • Save atton/7658001 to your computer and use it in GitHub Desktop.
Save atton/7658001 to your computer and use it in GitHub Desktop.
source for read astcompiler on pypy
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# script location : pypy top directory
import sys
from pypy.objspace.std import StdObjSpace
from pypy.interpreter.pyparser import pyparse, pytoken
from pypy.interpreter.pyparser.test import expressions
from pypy.interpreter.pyparser.error import SyntaxError, IndentationError
from pypy.interpreter.pycode import PyCode
from pypy.interpreter import eval, module
from pypy.interpreter.error import OperationError
from pypy.interpreter.astcompiler import codegen, astbuilder, symtable, optimize
from pypy.tool import stdlib_opcode as ops
def compile_with_astcompiler(expr, mode, space):
p = pyparse.PythonParser(space)
info = pyparse.CompileInfo("<test>", mode)
cst = p.parse_source(expr, info)
ast = astbuilder.ast_from_node(space, cst, info)
return codegen.compile_ast(space, ast, info)
def ensure__main__(space):
w_main = space.wrap('__main__')
w_modules = space.sys.get('modules')
try:
return space.getitem(w_modules, w_main)
except OperationError, e:
if not e.match(space, space.w_KeyError):
raise
mainmodule = module.Module(space, w_main)
space.setitem(w_modules, w_main, mainmodule)
return mainmodule
space = StdObjSpace()
mainmodule = ensure__main__(space)
w_globals = mainmodule.w_dict
source = open(sys.argv[1]).read() # load source from argv[1]
pycode = compile_with_astcompiler(source, "exec", StdObjSpace())
pycode.exec_code(space, w_globals, w_globals)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment