def dumpCodes(self): self.constants.append([ "PyFunctionTable", self.getFunctionTable(), jast.New(self.name, []) ]) for label, name, code, frame in self.codes: code = frame.toCellPrepend(code) funcid = self.addFunctionCode(name, code) arglist = keyworddict = jast. False if frame.args_arglist(): arglist = jast. True if frame.args_keyworddict(): keyworddict = jast. True names = jast.StringArray(frame.getnames()) cellnames = StringArrayOrNull(frame.getcellnames()) freenames = StringArrayOrNull(frame.getfreenames()) npurecell = frame.get_npurecell() cargs = [ jast.IntegerConstant(frame.args_count()), names, jast.StringConstant(self.filename), jast.StringConstant(name), arglist, keyworddict, self.getFunctionTable(), jast.IntegerConstant(funcid), cellnames, freenames, jast.IntegerConstant(npurecell), jast.IntegerConstant((frame.opt_globals and CO_OPTIMIZED) | ( frame.scope.nested_scopes and CO_NESTED)) ] newcode = jast.InvokeStatic("Py", "newCode", cargs) self.constants.append(("PyCode", jast.Identifier(label), newcode))
def visitImportFrom(self, node): modname = jast.StringConstant(node.module) module = self.get_module(node.module.split('.'), 0) if len(node.names) == 0: self.addModule(node.module, '*') self._loadNames(self._getnames(module), module) return jast.InvokeStatic("org.python.core.imp", "importAll", [modname, self.frame.frame]) topmodname = jast.StringConstant(node.module) modnames = [alias.name for alias in node.names] modnamesArray = jast.FilledArray( "String", map(lambda x: jast.StringConstant(x), modnames)) do_import = jast.InvokeStatic("org.python.core.imp", "importFrom", [topmodname, modnamesArray, self.frame.frame]) imp_accu = self.frame.gettemp('PyObject[]') stmts = [ jast.Set(imp_accu, do_import) ] for i in range(len(node.names)): modname = node.names[i].name asname = node.names[i].asname if asname is None: asname = modname code = jast.Subscript(imp_accu, i) stmts.append(self.set_name(asname, module.getattr(modname).makeReference(code))) stmts.append(jast.Set(imp_accu,jast.Null)) self.frame.freetemp(imp_accu) return stmts
def getFrozen(self): if self.frozen: if self.package is None: return jast.StringConstant("") else: return jast.StringConstant(self.package) else: return jast.Null
def importall_stmt(self, module): modname = jast.StringConstant(module.value.name) self.addModule(module.value.name, '*') #print 'import *', module.value.name self._loadNames(self._getnames(module), module) return jast.InvokeStatic("org.python.core.imp", "importAll", [modname, self.frame.frame])
def addPyProxyInterface(self): self.statements.append( jast.Declare('private PyInstance', jast.Identifier('__proxy'))) code = jast.Set(jast.Identifier("__proxy"), jast.Identifier("inst")) code = jast.Block([code]) self.statements.append( jast.Method("_setPyInstance", "public", ["void", ("PyInstance", "inst")], code)) code = jast.Block([jast.Return(jast.Identifier("__proxy"))]) self.statements.append( jast.Method("_getPyInstance", "public", ["PyInstance"], code)) self.statements.append( jast.Declare('private PySystemState', jast.Identifier('__sysstate'))) code = jast.Set(jast.Identifier("__sysstate"), jast.Identifier("inst")) code = jast.Block([code]) self.statements.append( jast.Method("_setPySystemState", "public", ["void", ("PySystemState", "inst")], code)) code = jast.Block([jast.Return(jast.Identifier("__sysstate"))]) self.statements.append( jast.Method("_getPySystemState", "public", ["PySystemState"], code)) frozen = self.module.getFrozen() this = jast.Identifier("this") initargs = [ this, jast.StringConstant(self.modname), jast.StringConstant(self.name), jast.Identifier("args"), self.packages, self.properties, frozen, jast.StringArray(self.modules) ] initproxy = jast.InvokeStatic("Py", "initProxy", initargs) code = jast.Block([initproxy]) self.statements.append( jast.Method("__initProxy__", "public", ["void", ("Object[]", "args")], code)) self.interfaces.append(org.python.core.PyProxy)
def dumpInitModule(self): meths = [] dict = jast.Identifier("dict") sargs = [ jast.StringConstant("__name__"), jast.New("PyString", [jast.StringConstant(self.name)]) ] rargs = [ jast.Invoke(jast.New("_PyInner", []), "getMain", []), dict, dict ] code = jast.Block([ jast.Invoke(dict, "__setitem__", sargs), jast.InvokeStatic("Py", "runCode", rargs) ]) meths.append( jast.Method("moduleDictInit", "public static", ["void", ("PyObject", "dict")], code)) return meths
def importfrom_stmt(self, top, names): module = self.get_module(top, 0) if names == '*': return self.importall_stmt(module) #print 'import * from', module #names = module.dir() modnames = [] asnames = [] for modname, asname in names: if asname is None: asname = modname asnames.append(asname) modnames.append(modname) topmodname = jast.StringConstant(".".join(top)) modnamesArray = jast.FilledArray( "String", map(lambda x: jast.StringConstant(x), modnames)) do_import = jast.InvokeStatic( "org.python.core.imp", "importFrom", [topmodname, modnamesArray, self.frame.frame]) if not self.imp_accu: imp_accu = self.imp_accu = jast.Identifier("imp_accu") self.makeFreeDecl("PyObject[]", imp_accu) else: imp_accu = self.imp_accu stmts = [jast.Set(imp_accu, do_import)] for i in range(len(asnames)): asname = asnames[i] modname = modnames[i] code = jast.Subscript(imp_accu, i) stmts.append( self.set_name(asname, module.getattr(modname).makeReference(code))) stmts.append(jast.Set(imp_accu, jast.Null)) return stmts
def addClassDictInit(self): self.interfaces.append(org.python.core.ClassDictInit) namelist = jast.InvokeStatic( "Py", "java2py", [jast.StringArray(self.supermethods.keys())]) code = jast.Invoke(jast.Identifier("dict"), "__setitem__", [jast.StringConstant("__supernames__"), namelist]) code = jast.Block([code]) self.statements.append( jast.Method("classDictInit", "static public", ["void", ("PyObject", "dict")], code))
def getNew(self): args = [jast.StringConstant(self.name), PyObjectArray(self.bases), self.pycode, jast.Null] if self.isSuperclassJava(): args.append(jast.Identifier("%s.class" % self.proxyname)) clos = self.def_compiler.frame.makeClosure(self.scope) if clos: args.append(PyObjectArray(clos)) return jast.InvokeStatic("Py", "makeClass", args)
def visitListComp(self, node): # Since this code generated here is placed in its own # java method, we need a new set of temp vrbls. oldtmps = self.frame.temporaries self.frame.temporaries = {} lst = self.factory.makeList([]) lsttmp, lstcode = self.makeTemp(lst) append = self.factory.makePyObject(jast.Invoke(lsttmp.asAny(), "__getattr__", [jast.StringConstant("append")])) appendtmp, appendcode = self.makeTemp(append) self.list_comprehension_count += 1 tmp_append = "_[%d]" % self.list_comprehension_count #tmp_append = "_[1]" n = ast.Expr(ast.Call(ast.Name(tmp_append, ast.Name.Load, node), [ node.elt ], [], None, None, node), node); for lc in node.generators[::-1]: for ifs in lc.ifs[::-1]: n = ast.If(ifs, [ n ], None, ifs); n = ast.For(lc.target, lc.iter, [ n ], None, lc); #visit(new Delete(new exprType[] { new Name(tmp_append, Name.Del) })); stmts = [ lstcode ] stmts.append(self.set_name(tmp_append, append)) #stmts.append(appendcode) stmts.append(self.visit(n)) stmts.append(jast.Return(lsttmp.asAny())) decs = self.frame.getDeclarations() if len(decs) != 0: stmts.insert(0, decs) idx = self.module.addFunctionCode("__listcomprehension", jast.Block(stmts)) self.freeTemp(lsttmp) self.freeTemp(appendtmp) self.frame.temporaries = oldtmps return self.factory.makePyObject( jast.InvokeLocal("__listcomprehension$%d" % (idx+1), [jast.Identifier("frame")]))
def invoke(self, code, name, args, keyargs): if keyargs: return self.getattr(code, name).call(args, keyargs) name = Object(jast.StringConstant(name), StringType) nargs = len(args) if nargs == 0: return self.domethod(code, "invoke", name) elif nargs == 1: return self.domethod(code, "invoke", name, args[0]) elif nargs == 2: return self.domethod(code, "invoke", name, args[0], args[1]) else: return self.domethod(code, "invoke", name, PyObjectArray(args))
def import_stmt(self, names): ret = [] for dotted, asname in names: modnameConst = jast.StringConstant(".".join(dotted)) if asname: code = jast.InvokeStatic("org.python.core.imp", "importOneAs", [modnameConst, self.frame.frame]) code = self.get_module(dotted, 0).makeReference(code) ret.append(self.set_name(asname, code)) else: code = jast.InvokeStatic("org.python.core.imp", "importOne", [modnameConst, self.frame.frame]) code = self.get_module(dotted, 1).makeReference(code) ret.append(self.set_name(dotted[0], code)) return ret
def visitImport(self, node): ret = [] for alias in node.names: modnameConst = jast.StringConstant(alias.name) dotted = alias.name.split('.') if alias.asname: code = jast.InvokeStatic("org.python.core.imp","importOneAs", [modnameConst, self.frame.frame]) code = self.get_module(dotted, 0).makeReference(code) ret.append(self.set_name(alias.asname, code)) else: code = jast.InvokeStatic("org.python.core.imp","importOne", [modnameConst, self.frame.frame]) code = self.get_module(dotted, 1).makeReference(code) ret.append(self.set_name(dotted[0], code)) return ret
def dumpMain(self): meths = [] if self.javamain: code = [] newargs = jast.Identifier("newargs") code.append( jast.Declare("String[]", newargs, jast.NewArray("String", ["args.length+1"]))) code.append( jast.Set(jast.Identifier("newargs[0]"), jast.StringConstant(self.name))) args = [ jast.Identifier('args'), jast.IntegerConstant(0), jast.Identifier('newargs'), jast.IntegerConstant(1), jast.Identifier('args.length') ] code.append( jast.InvokeStatic("java.lang.System", "arraycopy", args)) args = [ jast.GetStaticAttribute( self.getclassname(self.name + '.' + self.pyinner.name), "class"), jast.Identifier('newargs'), self.getPackages(qual=1), self.getMainProperties(qual=1), self.getFrozen(), jast.StringArray(self.modules.keys()) ] code.append([jast.InvokeStatic("Py", "runMain", args)]) maincode = jast.Block(code) meths.append( jast.Method("main", "public static", ["void", ("String[]", "args")], maincode, ["java.lang.Exception"])) return meths
def list_comprehension(self, node): # Since this code generated here is placed in its own # java method, we need a new set of temp vrbls. oldtmps = self.frame.temporaries self.frame.temporaries = {} expr = node.getChild(0) suite = node.getChild(1) lst = self.factory.makeList([]) lsttmp, lstcode = self.makeTemp(lst) append = self.factory.makePyObject( jast.Invoke(lsttmp.asAny(), "__getattr__", [jast.StringConstant("append")])) appendtmp, appendcode = self.makeTemp(append) self.listComprehensionStack.append((appendtmp, expr)) stmts = [lstcode, appendcode] stmts.append(self.visit(suite)) stmts.append(jast.Return(lsttmp.asAny())) decs = self.frame.getDeclarations() if len(decs) != 0: stmts.insert(0, decs) self.listComprehensionStack.pop(-1) idx = self.module.addFunctionCode("__listcomprehension", jast.Block(stmts)) self.freeTemp(lsttmp) self.freeTemp(appendtmp) self.frame.temporaries = oldtmps return self.factory.makePyObject( jast.InvokeLocal("__listcomprehension$%d" % (idx + 1), [jast.Identifier("frame")]))
def compile(self, data, filename, name): if self.javapackage is not None: name = self.javapackage + '.' + name data = data + '\n\n' mod = PythonModule(name, filename, frozen=self.deep) fact = ObjectFactory() pi = SrcGenCompiler(mod, fact, options=self.options) fact.parent = pi code = pi.execstring(data) # __file__ code.insert( 0, jast.Invoke(jast.Identifier('frame'), "setglobal", [ jast.StringConstant('__file__'), mod.getStringConstant(filename) ])) code.insert(1, jast.BlankLine()) code = jast.Block(code) mod.addMain(code, pi) self.addDependencies(mod) return mod
def getStringConstant(self, value): code = jast.InvokeStatic("Py", "newString", [jast.StringConstant(value)]) return self.getConstant(value, code, "s")
def getLongConstant(self, value): code = jast.InvokeStatic("Py", "newLong", [jast.StringConstant(str(value))]) return self.getConstant(value, code, "l")
def delattr(self, code, name): name = Object(jast.StringConstant(name), StringType) return self.domethod(code, "__delattr__", name).getStatement()
def setattr(self, code, name, value): PyObject.attributes[name] = value name = Object(jast.StringConstant(name), StringType) ret = self.domethod(code, "__setattr__", name, value) #print ret return ret.getStatement()
def callMethod(self, name, access, ret, sig, throws=[], dosuper=1): args = [typeName(ret)] argids = [] objects = [] throws = filterThrows(throws) for c in sig: if isinstance(c, TupleType): argname = c[1] c = c[0] else: argname = "arg" + str(len(argids)) args.append((typeName(c), argname)) argid = jast.Identifier(argname) argids.append(argid) objects.append(makeObject(argid, c)) objects = jast.FilledArray("Object", objects) stmts = [] this = jast.Identifier("this") if isinstance(access, IntType) and isAbstract(access): dosuper = 0 access = access & ~ABSTRACT if not dosuper and not self.isAdapter: getattr = jast.InvokeStatic("Py", "jgetattr", [this, jast.StringConstant(name)]) else: getattr = jast.InvokeStatic("Py", "jfindattr", [this, jast.StringConstant(name)]) inst = jast.Identifier("inst") if len(throws) == 0: jcall = "_jcall" else: jcall = "_jcallexc" jcall = makeReturn(jast.Invoke(inst, jcall, [objects]), ret) jcall = wrapThrows(jcall, throws, ret) if dosuper: supercall = jast.Invoke(jast.Identifier("super"), name, argids) if ret != Void.TYPE: supercall = jast.Return(supercall) supermethod = None if not self.issuperproxy and name not in self.getCandSupermethods( incl=0): supermethod = jast.Method("super__" + name, jast.Modifier.ModifierString(access), args, jast.Block([supercall]), throws) self.supermethods["super__" + name] = "super__" + name else: if self.isAdapter: supercall = nullReturn(ret) else: supercall = None supermethod = None if not dosuper and not self.isAdapter: test = jcall else: test = jast.If(jast.Operation("!=", inst, jast.Null), jcall, supercall) code = jast.Block([jast.Declare("PyObject", inst, getattr), test]) meth = jast.Method(name, jast.Modifier.ModifierString(access), args, code, throws) if supermethod is not None: self.statements.append(supermethod) self.statements.append(meth)
def getattr(self, code, name): if not PyObject.attributes.has_key(name): PyObject.attributes[name] = None name = Object(jast.StringConstant(name), StringType) return self.domethod(code, "__getattr__", name)
def setCode(self,method,ref,value): if type(ref) is type(""): args = (jast.StringConstant(ref),value.asAny()) else: args = (jast.IntegerConstant(ref),value.asAny()) return jast.Invoke(self.frame,method,args)
def delCode(self,method,ref): if type(ref) is type(""): ref = (jast.StringConstant(ref),) else: ref = (jast.IntegerConstant(ref),) return jast.Invoke(self.frame,method,ref)
def getNew(self): return jast.InvokeStatic("imp", "load", [jast.StringConstant(self.name)])
ret = JavaString() elif type == org.python.core.PyObject: ret = PyObject() elif type == org.python.core.PyString: ret = PyObject() else: ret = JavaObject(type) types[type] = ret return ret Generic = findType(org.python.core.PyObject) IntType = findType(java.lang.Integer.TYPE) StringType = findType(java.lang.String) if __name__ == '__main__': foo = Object(jast.Identifier("foo"), Generic) one = Object(jast.IntegerConstant(1), IntType) hello = Object(jast.StringConstant("hello"), StringType) print foo, one, hello print foo.binop("add", foo) print foo.binop("add", one) print foo.binop("add", hello) print foo.nonzero() print foo.getitem(foo) print foo.getitem(one) print foo.call([one, hello]) print foo.call([one, hello, foo])