예제 #1
0
    def for_stmt(self, index, sequence, body, else_body=None):
        counter = self.frame.gettemp('int')
        item = self.factory.makePyObject(self.frame.gettemp("PyObject"))
        seq = self.frame.gettemp("PyObject")

        init = []
        init.append(jast.Set(counter, jast.IntegerConstant(0)))
        init.append(jast.Set(seq, self.visit(sequence).asAny()))

        counter_inc = jast.PostOperation(counter, '++')

        test = jast.Set(item.asAny(),
                        jast.Invoke(seq, "__finditem__", [counter_inc]))
        test = jast.Operation('!=', test, jast.Identifier('null'))

        suite = []
        suite.append(self.set(index, item))
        suite.append(self.visit(body))
        suite = jast.Block(suite)

        if else_body is not None:
            else_body = jast.Block(self.visit(else_body))
            wtmp = self.frame.gettemp('boolean')
            ret = [init, jast.WhileElse(test, suite, else_body, wtmp)]
            self.frame.freetemp(wtmp)
            return ret
        else:
            return [init, jast.While(test, suite)]
예제 #2
0
    def callSuperMethod(self, name, supername, access, ret, sig, throws=[]):
        if self.issuperproxy:
            return
        self.supermethods[supername] = supername
        args = [typeName(ret)]
        argids = []
        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)

        supercall = jast.Invoke(jast.Identifier("super"), name, argids)
        if ret != Void.TYPE:
            supercall = jast.Return(supercall)

        supermethod = jast.Method(supername,
                                  jast.Modifier.ModifierString(access), args,
                                  jast.Block([supercall]), throws)
        self.statements.append(supermethod)
        return
예제 #3
0
    def list_iter(self, node):
        if node.getNumChildren() == 0:
            append, expr = self.listComprehensionStack[-1]
            return [jast.Invoke(append.asAny(), "__call__",
                                         [self.visit(expr).asAny()])]

        return self.visit(node.getChild(0))
예제 #4
0
 def mkcall(self, callee, args):
     if self.isConstructor:
         op = jast.New(self.name, args)
     elif self.isStatic:
         op = jast.InvokeStatic(callee, self.name, args)
     else:
         #print callee, self.name, args
         op = jast.Invoke(callee, self.name, args)
     return op, self.retType
예제 #5
0
    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
예제 #6
0
 def makeClosure(self,nested_scope):
     freenames = nested_scope.freevars
     if len(freenames) == 0: return None
     clos = []
     factory = self.compiler.factory
     for free in freenames:
         i = self.scope.tbl.get(free).env_index
         code = jast.Invoke(self.frame, "getclosure", [jast.IntegerConstant(i)])
         clos.append(factory.makePyObject(code))
     return clos
예제 #7
0
    def bool_op(self, x, y, swap=0):
        tmp = self.frame.gettemp("PyObject")
        test = jast.Invoke(jast.Set(tmp,
                                    self.visit(x).asAny()), "__nonzero__", [])
        yes, no = tmp, self.visit(y).asAny()
        if swap:
            yes, no = no, yes

        op = self.factory.makePyObject(jast.TriTest(test, yes, no))
        self.frame.freetemp(tmp)
        return op
예제 #8
0
 def makeCode(self):
     comp = self.factory.getCompiler(self.def_compiler,
                                     SrcGenCompiler.ClassFrame, self.scope,
                                     self.name)
     code = jast.Block([comp.parse(ast.Suite(self.body)),
                        jast.Return(jast.Invoke(comp.frame.frame,
                                                "getf_locals", []))])
     self.frame = comp.frame
     self.pycode = self.def_compiler.top_compiler.module.getCodeConstant(
         self.name, code, comp.frame)
     return self.pycode
예제 #9
0
 def toCellPrepend(self,code):
     scope = self.scope
     pre = []
     for parmcell in scope.jy_paramcells:
         syminf = scope.tbl.get(parmcell)
         args = [jast.IntegerConstant(syminf.locals_index),
                 jast.IntegerConstant(syminf.env_index)]
         pre.append(jast.Invoke(self.frame, "to_cell", args))
     if not pre: return code
     pre.append(jast.BlankLine())
     return jast.Block(jast.flatten([pre,code]))
예제 #10
0
    def bool_op(self, x, y, op):
        tmp = self.frame.gettemp("PyObject")
        test = jast.Invoke(jast.Set(tmp, x.asAny()),
                           "__nonzero__", [])
        if op == ast.BoolOp.Or:
            yes, no = tmp, y.asAny()
        else:
            no, yes = tmp, y.asAny()

        op = self.factory.makePyObject(jast.TriTest(test, yes, no))
        self.frame.freetemp(tmp)
        return op
예제 #11
0
    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))
예제 #12
0
    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")]))
예제 #13
0
    def asa(self, code, type, message=None):
        ret = self.isa(code, type)
        if ret is not None:
            return ret

        if primitives.has_key(type):
            return jast.InvokeStatic('Py', primitives[type], [code])
        if type == java.lang.Boolean.TYPE:
            return jast.Invoke(code, '__nonzero__', [])

        tname = type.__name__
        tojava = jast.InvokeStatic(
            'Py', 'tojava',
            [code, jast.GetStaticAttribute(tname, 'class')])
        return jast.Cast(tname, tojava)
예제 #14
0
    def visitFor(self, node):
        iter = self.frame.gettemp('PyObject')
        item = self.factory.makePyObject(self.frame.gettemp("PyObject"))
        seq = self.visit(node.iter).asAny() 

        init = []
        init.append(jast.Set(iter, jast.Invoke(seq, "__iter__", [])))

        test = jast.Set(item.asAny(), jast.Invoke(iter, "__iternext__", []))
        test = jast.Operation('!=', test, jast.Identifier('null'))

        suite = []
        suite.append(self.set(node.target, item))
        suite.append(self.suite(node.body))
        suite = jast.Block(suite)

        if node.orelse is not None:
            orelse = jast.Block(self.suite(node.orelse))
            wtmp = self.frame.gettemp('boolean')
            ret = [init, jast.WhileElse(test, suite, orelse, wtmp)]
            self.frame.freetemp(wtmp)
            return ret
        else:
            return [init, jast.While(test, suite)]
예제 #15
0
    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")]))
예제 #16
0
def wrapThrows(stmt, throws, retType):
    if len(throws) == 0: return stmt
    catches = []
    throwableFound = 0
    for i in range(len(throws)):
        throw = throws[i]
        exctype = throw
        excname = jast.Identifier("exc%d" % i)
        body = jast.Block([jast.Throw(excname)])
        catches.append((exctype, excname, body))
        if throw == "java.lang.Throwable":
            throwableFound = 1

    if not throwableFound:
        body = jast.Block([
            jast.Invoke(jast.Identifier("inst"), "_jthrow",
                        [jast.Identifier("t")]),
            nullReturn(retType)
        ])
        catches.append(("java.lang.Throwable", jast.Identifier("t"), body))
    return jast.TryCatches(jast.Block([stmt]), catches)
예제 #17
0
    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
예제 #18
0
    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)
예제 #19
0
    def visitTryExcept(self, node):
        if node.orelse is not None:
            elseBool = self.frame.gettemp("boolean")

        jbody = jast.Block(self.suite(node.body))
        tests = []
        ifelse = None

        tname = jast.Identifier("x$%d" % self.nthrowables)
        self.nthrowables = self.nthrowables + 1

        exctmp = self.frame.gettemp("PyException")
        setexc = jast.Set(exctmp, jast.InvokeStatic("Py", "setException",
                                                    [tname, self.frame.frame]))

        for exchandler in node.handlers:
            if exchandler.type is None:
                ifelse = jast.Block(self.suite(exchandler.body))
                continue

            type = self.visit(exchandler.type)
            t = jast.Invoke(exctmp, "match", [type.asAny()])
            newbody = []

            if exchandler.name is not None:
                exceptionValue = self.factory.makePyObject(
                    jast.GetInstanceAttribute(exctmp, "value"))
                newbody.append(self.set(exchandler.name, exceptionValue))

            #print self.visit(ebody)
            newbody.append(self.suite(exchandler.body))
            #print newbody
            #print jast.Block(newbody)
            tests.append( (t, jast.Block(newbody)) )

        if ifelse is None:
            ifelse = jast.Throw(exctmp)

        if len(tests) == 0:
            catchBody = ifelse
        else:
            catchBody = jast.MultiIf(tests, ifelse)

        catchBody = [setexc, catchBody]
   
        if node.orelse is not None:
            catchBody = [jast.Set(elseBool, jast.False), catchBody]

        catchBody = jast.Block([catchBody])

        self.frame.freetemp(exctmp)

        ret = jast.TryCatch(jbody, "Throwable", tname, catchBody)

        if node.orelse is not None:
            ret = jast.Block([jast.Set(elseBool, jast.True), ret, 
                              jast.If(elseBool,
                                      jast.Block(self.suite(node.orelse)))])
            self.frame.freetemp(elseBool)

        return ret
예제 #20
0
 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)
예제 #21
0
 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)