Exemplo n.º 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)]
Exemplo n.º 2
0
 def while_stmt(self, test, body, else_body=None):
     stest = self.visit(test).nonzero()
     sbody = jast.Block(self.visit(body))
     if else_body is not None:
         else_body = jast.Block(self.visit(else_body))
         wtmp = self.frame.gettemp('boolean')
         ret = jast.WhileElse(stest, sbody, else_body, wtmp)
         self.frame.freetemp(wtmp)
         return ret
     else:
         return jast.While(stest, sbody)
Exemplo n.º 3
0
 def visitWhile(self, node):
     stest = self.visit(node.test).nonzero()
     sbody = jast.Block(self.suite(node.body))
     if node.orelse is not None:
         orelse = jast.Block(self.suite(node.orelse))
         wtmp = self.frame.gettemp('boolean')
         ret = jast.WhileElse(stest, sbody, orelse, wtmp)
         self.frame.freetemp(wtmp)
         return ret
     else:
         return jast.While(stest, sbody)
Exemplo n.º 4
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
Exemplo n.º 5
0
def clean(node):
    if not hasattr(node, 'exits'):
        print node
    if node.exits():
        return node
    return jast.Block(
        [node, jast.Return(jast.GetStaticAttribute('Py', 'None'))])
Exemplo n.º 6
0
    def dumpFuncs(self):
        meths = []
        cases = []

        args = ["PyObject", ("PyFrame", "frame")]
        access = "private static"

        callargs = [jast.Identifier("frame")]

        for name, funcid, code in self.funccodes:
            funcname = self.uniquename(name)
            meths.append(jast.Method(funcname, access, args, clean(code)))

            body = jast.Return(jast.InvokeStatic(self.name, funcname,
                                                 callargs))
            cases.append(
                [jast.IntegerConstant(funcid),
                 jast.FreeBlock([body])])

        defaultCase = jast.FreeBlock([jast.Return(jast.Null)])
        switch = jast.Block(
            [jast.Switch(jast.Identifier('index'), cases, defaultCase)])

        meths.insert(
            0,
            jast.Method("call_function", "public",
                        ["PyObject", ("int", "index"),
                         ("PyFrame", "frame")], switch))
        self.superclass = "PyFunctionTable"
        return meths
Exemplo n.º 7
0
    def visitIf(self, node):
        test = self.visit(node.test).nonzero()
        body = jast.Block(self.suite(node.body))

        orelse = None
        if node.orelse is not None:
            orelse = jast.Block(self.suite(node.orelse))

        if isinstance(node.test, ast.Name):
            tname = self.getName(node.test.id)
            if tname is not None and self.isAlwaysFalse(tname):
                if node.orelse is None:
                    return jast.SimpleComment("if "+tname)
                else:
                    return orelse

        return jast.If(test, body, orelse)
Exemplo n.º 8
0
    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)
Exemplo n.º 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]))
Exemplo n.º 10
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
Exemplo n.º 11
0
    def makeClass(self):
        mycode = self.dumpAll()
        supername = self.superclass.__name__
        if self.javaproxy is not None:
            mycode = [mycode, self.javaproxy.dumpAll()]
            self.superclass = self.javaproxy.superclass
            self.interfaces = self.interfaces + self.javaproxy.interfaces
            supername = self.javaproxy.supername

        body = jast.Block(mycode)
        return jast.Class(self.name, self.modifier, supername,
                          map(lambda i: i.__name__, self.interfaces), body)
Exemplo n.º 12
0
    def dumpConstants(self):
        self.dumpCodes()
        stmts = []
        decls = []
        for type, label, value in self.constants:
            decls.append(jast.Declare("private static " + type, label))
            stmts.append(jast.Set(label, value))

        setconstants = jast.Method("initConstants", "private static", ["void"],
                                   jast.Block(stmts))
        decls.append(setconstants)
        return decls
Exemplo n.º 13
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)
Exemplo n.º 14
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))
Exemplo n.º 15
0
    def dumpMain(self):
        if not hasattr(self, 'mainCode'):
            return []
        meths = []

        self.interfaces.append("PyRunnable")
        getmain = jast.Block([
            jast.If(jast.Operation("==", self.mainCode, jast.Null),
                    jast.InvokeStatic(self.name, "initConstants", [])),
            jast.Return(self.mainCode)
        ])
        meths.append(jast.Method("getMain", "public", ["PyCode"], getmain))
        return meths
Exemplo n.º 16
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")]))
Exemplo n.º 17
0
    def if_stmt(self, tests, else_body=None):
        jtests = []
        for test, body in tests:
            tname = self.getName(test)
            if tname is not None and self.isAlwaysFalse(tname):
                continue
            test = self.visit(test).nonzero()
            body = jast.Block(self.visit(body))
            jtests.append((test, body))

        if else_body is not None:
            else_body = jast.Block(self.visit(else_body))

        if len(jtests) == 0:
            if else_body is None:
                return jast.SimpleComment("if " + tname)
            else:
                return else_body

        if len(jtests) == 1:
            return jast.If(jtests[0][0], jtests[0][1], else_body)
        else:
            return jast.MultiIf(jtests, else_body)
Exemplo n.º 18
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)]
Exemplo n.º 19
0
    def makeCode(self): # now handles a,b style args too
        # Add args to funcframe
        ac = self.scope.ac
        # Parse the body
        comp = self.factory.getCompiler(self.def_compiler,
                    SrcGenCompiler.FunctionFrame, self.scope,
                    self.def_compiler.className)
        for argname in ac.names:
            comp.frame.setname(argname, self.factory.makePyObject(None))

        tree = ast.Suite(self.body)
        ac.appendInitCode(tree)
        code = jast.Block([comp.parse(tree)])
        # Set up a code object
        self.pycode = self.def_compiler.top_compiler.module.getCodeConstant(
            self.name, code, comp.frame)
        self.frame = comp.frame
        return self.pycode
Exemplo n.º 20
0
    def callConstructor(self, access, sig, throws=[], dosuper=1):
        args = []
        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 dosuper:
            supercall = jast.InvokeLocal("super", argids)
        else:
            supercall = jast.InvokeLocal("super", [])


##          for saccess, ssig in self.jconstructors:
##              if len(ssig) == len(sig):
##                  supercall = jast.InvokeLocal("super", argids)
##                  break
##          else:
##              supercall = jast.InvokeLocal("super", [])

        frozen = self.module.getFrozen()

        initargs = [objects]
        initproxy = jast.InvokeLocal("__initProxy__", initargs)

        code = jast.Block([supercall, initproxy])
        self.statements.append(
            jast.Constructor(self.name, jast.Modifier.ModifierString(access),
                             args, code, throws))
Exemplo n.º 21
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
Exemplo n.º 22
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")]))
Exemplo n.º 23
0
    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
Exemplo n.º 24
0
    def makeCode(self):  # now handles a,b style args too
        # Add args to funcframe
        ac = self.scope.ac
        # Parse the body
        comp = self.factory.getCompiler(self.def_compiler,
                                        SimpleCompiler.FunctionFrame,
                                        self.scope,
                                        self.def_compiler.className)
        for argname in ac.names:
            comp.frame.setname(argname, self.factory.makePyObject(None))

        tree = self.body
        if ac.init_code.numChildren > 0:
            ac.init_code.jjtAddChild(tree, ac.init_code.numChildren)
            tree = ac.init_code
        code = jast.Block([comp.parse(tree)])
        # Set up a code object
        self.pycode = self.def_compiler.top_compiler.module.getCodeConstant(
            self.name, code, comp.frame)
        self.frame = comp.frame
        return self.pycode
Exemplo n.º 25
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
Exemplo n.º 26
0
for i in [1,2,3]:
    print i

def bar(x):
    print x*10
    y = x+2
    print y

bar(42)

class Baz:
    def eggs(self, x, y, z):
        return x, y, z

b = Baz()
print b.eggs(1,2,3)
"""

if __name__ == '__main__':
    mod = SrcGenCompiler.BasicModule("foo")
    fact = ObjectFactory()
    pi = SrcGenCompiler.SrcGenCompiler(mod, fact)
    fact.parent = pi
    code = jast.Block(pi.execstring(data))
    mod.addMain(code, pi)

    print mod.attributes.keys()
    print mod.imports.keys()
    print mod
    mod.dump("c:\\jython\\tools\\jythonc2\\test")
Exemplo n.º 27
0
 def makeClass(self):
     body = jast.Block(self.dumpAll())
     return jast.Class(self.name, self.modifier, self.superclass,
                       self.interfaces, body)
Exemplo n.º 28
0
                           [jast.StringConstant("__supernames__"), namelist])

        code = jast.Block([code])
        self.statements.append(
            jast.Method("classDictInit", "static public",
                        ["void", ("PyObject", "dict")], code))

    def makeClass(self):
        mycode = self.dumpAll()
        body = jast.Block(mycode)
        return jast.Class(self.name, self.modifier, self.supername,
                          map(lambda i: i.__name__, self.interfaces), body)

    def getDescription(self):
        COMMASPACE = ', '
        ret = self.name + ' extends ' + self.supername
        if len(self.interfaces) > 0:
            ret = ret + ' implements ' + \
                  COMMASPACE.join(map(lambda i: i.__name__, self.interfaces))
        return ret

if __name__ == '__main__':
    import java
    methods = [("init", None, None),
               ("enable", None, ("public", Void.TYPE, [(java.awt.Event,
                                                        'event')]))]
    jp = JavaProxy("Foo", [java.util.Random],
                   methods)  #applet.Applet], methods)

    print jast.Block(jp.dumpAll())
Exemplo n.º 29
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)
Exemplo n.º 30
0
 def makeClass(self):
     mycode = self.dumpAll()
     body = jast.Block(mycode)
     return jast.Class(self.name, self.modifier, self.supername,
                       map(lambda i: i.__name__, self.interfaces), body)