Пример #1
0
 def _return(self, val):
     if val is None:
         pyval = ast.Const(None)
     else:
         assertResult(val, "return")
         pyval = topy(val)
     return ast.Return(pyval)
Пример #2
0
    def _def(self, name, body, args=None):
        flags, argnames, defaults = funcArgs(args)

        if len(body) > 0 and type(body[0]) == str:
            doc = body[0]
            body2 = body[1:]
        else:
            doc = None
            body2 = body

        bod = ast.Return(block(body2, True))
        return astFunction(str(name), argnames, defaults, flags, doc, bod)
Пример #3
0
    def visitLambda(self, node):
        assert not any(map((lambda a:a==tuple), map(type, node.argnames))), \
         "unpacking tuples in function arguments not supported (lineno %d)" % self.lineno

        code = ast.Return(node.code)
        self.emit('function', Visitor.createFunction(node.argnames, code))
        for default in node.defaults:
            self.visit(default)
        self.emit('maketuple', len(node.defaults))

        self.emit(
            'makefunction',
            dict(varargs=bool(node.varargs),
                 kwargs=bool(node.kwargs),
                 argnames=node.argnames))
Пример #4
0
    def _def(self, name, body, args=None):
        flags, argnames, defaults = funcArgs(args)

        if len(body) > 0:
            bod = block(body, True)
            stmts = bod.nodes
            if len(stmts) > 1 and isinstance(stmts[0], ast.Pass):
                first = 1
            else:
                first = 0
            stmt1 = stmts[first]
            if isinstance(stmt1, ast.Const) and isinstance(stmt1.value, str):
                doc = stmt1.value
                del stmts[:first+1]
                if len(stmts) == 0:
                    bod = ast.Const(None)
            else:
                doc = None
        else:
            bod = ast.Const(None)
            doc = None

        return astFunction(str(name), argnames, defaults, flags, doc, ast.Return(bod))
Пример #5
0
def p_return_stmt(p):
    "return_stmt : RETURN testlist"
    p[0] = ast.Return(p[2])
Пример #6
0
def compileDefop(self, binding, ruledef, smartspace=None, assoc='left',
                 imp=None, lang=None):

    if lang is None:
        raise CompileError("invalid defop")

    assertResult(ruledef, "use in defop")
    assertResult(binding, "use in defop")

    lineno = getmeta(self, 'lineno')

    # {{{ token = extract from ruledef
    def islit(x): return x[0][0] == 'LiteralRule'

    if islit(ruledef):
        token = ruledef[1]
    elif ruledef[0][0] == 'SequenceRule':
        rules = ruledef[1:]
        if len(rules) > 1 and islit(rules[0]):
            token = rules[0][1]
        elif len(rules) > 1 and islit(rules[1]):
            token = rules[1][1]
        else:
            raise CompileError("invalid ruledef")
    else:
        raise CompileError("invalid ruledef")
    # }}}

    if imp:
        if imp['kind'] == 'm':
            funcname = 'macro'
            
        elif imp['kind'] == 'f':
            funcname = 'func'

        else:
            assert 0, "invalid implementation kind: %s" % imp.kind

        impfuncname = 'operator[%s]' % token

        # {{{ impfunc = 
        argflags, argnames, argdefaults = funcArgs(imp.get('args'))
        impfunc = astFunction(impfuncname,
                              argnames,
                              argdefaults,
                              argflags,
                              None, #docstring
                              ast.Return(block(imp['body'], True)))
        impfunc.lineno = lineno
        # }}}
    else:
        funcname = None
        impfuncname = "None"
        impfunc = None

    lastdot = lang.rfind('.')
    if lastdot == -1:
        langexpr = GlobalName(lang)
    else:
        assert 0, "PROBE: Why are we adding an op to an imported language?"
        langname = lang[lastdot+1:]
        langmod = lang[:lastdot]
        langexpr = ast.Getattr(ast.Subscript(logixglobal('lmodules'),
                                             'OP_APPLY',
                                             [ast.Const(langmod)]),
                               langname)

    newOpCall = ast.CallFunc(
        ast.Getattr(ast.Getattr(langexpr, '__impl__'), 'newOp'),
        [ast.Const(token),
         topy(binding),
         topy(ruledef),
         ast.Const(smartspace),
         ast.Const(assoc),
         ast.Const(funcname),
         ast.Name(impfuncname)
         ])

    if impfunc:
        return ast.Stmt([impfunc, newOpCall])
    else:
        return newOpCall
Пример #7
0
def compileDefop(doc):
    binding = doc['binding']
    ruledef = doc['ruledef']
    smartspace = doc.get('smartspace')
    assoc = doc.get('assoc', 'left')
    imp = doc.get('imp')
    lang = doc.get('lang')

    if lang is None:
        raise CompileError("invalid defop")

    assertResult(ruledef, "use in defop")
    assertResult(binding, "use in defop")

    lineno = getattr(doc, "lineno", None)

    # {{{ token = extract from ruledef
    def islit(x): return x[0][0] == 'LiteralRule'

    if islit(ruledef):
        token = ruledef[1]
    elif ruledef[0][0] == 'SequenceRule':
        rules = ruledef[1:]
        if len(rules) > 1 and islit(rules[0]):
            token = rules[0][1]
        elif len(rules) > 1 and islit(rules[1]):
            token = rules[1][1]
        else:
            raise CompileError("invalid ruledef")
    else:
        raise CompileError("invalid ruledef")

    # }}}

    if imp:
        if imp['kind'] == 'm':
            impkind = 'macro'
            
        elif imp['kind'] == 'f':
            impkind = 'func'

        else:
            assert 0, "invalid implementation kind: %s" % imp.kind

        impfuncname = 'operator[%s]' % token

        # {{{ impfunc = 
        argflags, argnames, argdefaults = funcArgs(imp.get('args'))
        impfunc = astFunction(impfuncname,
                              argnames,
                              argdefaults,
                              argflags,
                              None, #docstring
                              ast.Return(block(imp['body'], True)))
        impfunc.lineno = lineno
        # }}}

        impArgs = [ast.Const(impkind), ast.Name(impfuncname)]
    else:
        impArgs = []

    lastdot = lang.rfind('.')
    if lastdot == -1:
        langexpr = GlobalName(lang)
    else:
        assert 0, "PROBE: Why are we adding an op to an imported language?"
        langname = lang[lastdot+1:]
        langmod = lang[:lastdot]
        langexpr = ast.Getattr(ast.Subscript(logixglobal('lmodules'),
                                             'OP_APPLY',
                                             [ast.Const(langmod)]),
                               langname)

    # If unmarshallable objects get into the code-object, you get a
    # blanket error message, so check these before they go in.
    assert isinstance(token, str)
    assert isinstance(smartspace, str) or smartspace == None
    assert isinstance(assoc, str)

    newOpCall = ast.CallFunc(
        ast.Getattr(ast.Getattr(langexpr, '__impl__'), 'newOp'),
        [ast.Const(token),
         topy(binding),
         topy(ruledef),
         ast.Const(smartspace),
         ast.Const(assoc)]
        + impArgs)

    if impArgs != []:
        return ast.Stmt([impfunc, newOpCall])
    else:
        return newOpCall
Пример #8
0
    def funcdef(self, nodelist):
        if len(nodelist) == 6:
            assert nodelist[0][0] == symbol.decorators
            decorators = self.decorators(nodelist[0][1:])
        else:
            assert len(nodelist) == 5
            decorators = None

        lineno = nodelist[-4][2]
        name = nodelist[-4][1]
        args = nodelist[-3][2]

        if not re.match('_q_((html|plain)_)?template_', name):
            # just a normal function, let base class handle it
            self.__template_type.append(None)
            n = transformer.Transformer.funcdef(self, nodelist)

        else:
            if name.startswith(PLAIN_TEMPLATE_PREFIX):
                name = name[len(PLAIN_TEMPLATE_PREFIX):]
                template_type = "plain"
            elif name.startswith(HTML_TEMPLATE_PREFIX):
                name = name[len(HTML_TEMPLATE_PREFIX):]
                template_type = "html"
            elif name.startswith(TEMPLATE_PREFIX):
                name = name[len(TEMPLATE_PREFIX):]
                template_type = "plain"
            else:
                raise RuntimeError, 'unknown prefix on %s' % name

            self.__template_type.append(template_type)

            # Add "IO_INSTANCE = IO_CLASS()" statement at the beginning of
            # the function and a "return IO_INSTANCE" at the end.
            if args[0] == symbol.varargslist:
                names, defaults, flags = self.com_arglist(args[1:])
            else:
                names = defaults = ()
                flags = 0
            doc = None  # self.get_docstring(nodelist[-1])

            # code for function
            code = self.com_node(nodelist[-1])

            # create an instance, assign to IO_INSTANCE
            klass = ast.Name(IO_CLASS)
            args = [ast.Const(template_type == "html")]
            instance = ast.CallFunc(klass, args)
            assign_name = ast.AssName(IO_INSTANCE, OP_ASSIGN)
            assign = ast.Assign([assign_name], instance)

            # return the IO_INSTANCE.getvalue(...)
            func = ast.Getattr(ast.Name(IO_INSTANCE), "getvalue")
            ret = ast.Return(ast.CallFunc(func, []))

            # wrap original function code
            code = ast.Stmt([assign, code, ret])

            if sys.hexversion >= 0x20400a2:
                n = ast.Function(decorators, name, names, defaults, flags, doc,
                                 code)
            else:
                n = ast.Function(name, names, defaults, flags, doc, code)
            n.lineno = lineno

        self.__template_type.pop()
        return n
Пример #9
0
 def _do_ReturnStatement(self, node):
     value = self.transform(node.Expression)
     if value is None:
         value = ast.Const(None)
     return ast.Return(value)