示例#1
0
    def dict(self, *items):
        "{"

        if items == (None,):
            return ast.Dict([])
        else:
            for x in items[1::2]: assertResult(x, "use in dict literal")

            return ast.Dict([(topy(items[i]), topy(items[i+1]))
                             for i in range(0, len(items), 2)])
示例#2
0
 def _do_DictionaryExpression(self, node):
     items = []
     for item in node.Items:
         key = self.transform(item.SliceStart)
         value = self.transform(item.SliceStop)
         items.append((key, value))
     return ast.Dict(items)
示例#3
0
    def flist(obj):
        for x in obj: assertResult(x, 'use in flist')

        return ast.CallFunc(ast.Getattr(logixglobal('flist'), 'new'),
                            [ast.List(map(topy, obj.elems)),
                             ast.Dict([(ast.Const(n), topy(v))
                                       for n,v in obj.items()])])
示例#4
0
    def function(self, name, expr):
        """
        Create a function of one argument with the given name returning the
        given expr.

        @param name: The function name.
        @param expr: The AST to insert into the function.
        """

        fexpr = ast.Stmt([ast.Assign([ast.AssName('__locals', 'OP_ASSIGN')],
                                     ast.Dict([(ast.Const('self'),
                                                ast.Name('self'))])),
                          ast.Assign([ast.Subscript(ast.Getattr(
                                                  ast.Name('self'), 'locals'),
                                                    'OP_ASSIGN',
                                                    [ast.Const(
                                                     name.split('_',1)[1])])],
                                     ast.Name('__locals')),
                          expr])
        f = ast.Lambda(['self'], [], 0, fexpr)
        f.filename = self.name
        return f
示例#5
0
    def dict(obj):
        for k,v in obj.items():
            assertResult(k, "use as dict key")
            assertResult(v, "use in dict")

        return ast.Dict([(topy(k), topy(v)) for k,v in obj.items()])
示例#6
0
def quotedArgs(operands, depth):
    """
    Generate code from an flist of operand expressions, possibly containing splices.
    
    Returns an expression that constructs an flist.
    """

    parts = []
    for x in operands.elems:
        if isinstance(x, rootops.escape):
            extra = x.__operands__.get('extra', [])
            escapelevel = 1 + len(extra)
            if escapelevel > depth:
                raise CompileError("invalid quote escape")
            escape = escapelevel == depth
        else:
            escape = False
            
        if escape:
            if x.__operands__.hasField("splice"):
                assertResult(x[0], "insert into quote")
                parts.append( ('s', topy(x[0])) )  # 's' == splice
            
            elif x.__operands__.hasField("localmodule"):
                parts.append( ('v',topy(localModuleQuote())) )
                     
            else:
                assertResult(x[0], "insert into quote")
                parts.append( ('v', topy(x[0])) )  # 'v' == plain value
            
        else:
            parts.append( ('v', quote(x, depth)) )  # 'v' == plain value

    # {{{ expr = reduce parts to a single expression
    # If there is just a single splice, then that is the expression
    # otherwise generate:  val = ??; val.extend(??); val.extend(??)...
    def frontSection(parts):
        vals = list(itools.takewhile(lambda (tag, exp): tag == 'v', parts))
        if len(vals) == 0:
            return parts[0][1], parts[1:]
        else:
            return ast.List([v[1] for v in vals]), parts[len(vals):]
        
    if len(parts) == 0:
        expr = ast.List([])
    else:
        first, rest = frontSection(parts)
        if len(rest) == 0:
            expr = first
        else:
            # Generate:
            #     val = ...; if not hasattr(val, 'extend'): val = list(val)
            val = macros.gensym("val")
            statements = [
                ast.Assign([compilePlace(val)], first),
                ast.If([(ast.CallFunc(GlobalName('isinstance'),
                                      [topy(val), logixglobal("flist")]),
                         ast.Assign([compilePlace(val)],
                                    ast.CallFunc(ast.Getattr(topy(val), "copy"),
                                                 [])))],
                       #else
                       ast.Assign([compilePlace(val)],
                                  ast.CallFunc(GlobalName('list'), [topy(val)])))]

            while len(rest) > 0:
                ex, rest = frontSection(rest)

                statements.append(ast.Discard(ast.CallFunc(ast.Getattr(topy(val),
                                                                       "extend"),
                                                           [ex])))
            statements.append(topy(val))

            expr = ast.Stmt(statements)
    # }}}

    for v in operands.fields.values():
        assertResult(v, "use as operand")
        
    keywords = ast.Dict([(ast.Const(n), quote(v, depth))
                         for n, v in operands.items()])

    if isinstance(expr, ast.List):
        return ast.CallFunc(ast.Getattr(logixglobal("flist"), 'new'),
                            [expr, keywords])
    else:
        return ast.Add([expr, ast.CallFunc(ast.Getattr(logixglobal("flist"), 'new'),
                                           [ast.List([]), keywords])])
示例#7
0
def compileDict(doc):
    for x in doc:
        assertResult(x[0], "usa as dict key")
        assertResult(x[1], "usa as dict value")
    return ast.Dict([(topy(x[0]), topy(x[1])) for x in doc])
示例#8
0
def compilePlainDoc(doc):
    return ast.CallFunc(logixglobal("plaindoc"),
                        [ast.List([topy(x) for x in doc.content()]),
                         ast.Dict([(ast.Const(str(n)), topy(v))
                                   for n,v in doc.properties()])])
示例#9
0
def quotedDoc(doc, depth):
    """
    Generate code to build a Doc like `doc` with quote-escapes
    replaced by runtime values.
    """

    # Each element of contentParts is either:
    #  an AST - meaning a spliced value - the resulting content
    #           should be `extend`ed by that value
    #  a list of ASTs - a list of regular elements, the resulting
    #                   content should be `extend`ed by an ast.List
    #                   with these elements
    # {{{ contentParts = 
    contentParts = [[]]

    for x in doc.content():
        if isDoc(x, rootops.escape):
            escapelevel = 1 + len(x.get('extra', []))
            if escapelevel > depth:
                raise CompileError("more quote escapes than quotes")
            escape = escapelevel == depth
        else:
            escape = False
            
        if escape:
            if x.hasProperty("splice"):
                assertResult(x[0], "insert into quote")
                contentParts.append(topy(x[0]))
                contentParts.append([])
            elif x.hasProperty("localmodule"):
                contentParts[-1].append(topy(localModuleQuote()))
            else:
                assertResult(x[0], "insert into quote")
                contentParts[-1].append(topy(x[0]))
            
        else:
            contentParts[-1].append(quote(x, depth))
    # }}}

    # These properties are added to the result doc *after*
    # any spliced in docs, so they overwrite any spliced properties
    for v in doc.propertyValues():
        assertResult(v, "use as operand")
    properties = ast.Dict([(compileSymbol(n), quote(v, depth))
                           for n, v in doc.properties()])
        
    # assert isinstance(contentParts[0], list)

    if contentParts == [[]]:
        return ast.CallFunc(logixglobal("Doc"),
                            [compileSymbol(doc.tag),
                             properties])
    else:
        if len(contentParts[0]) > 0:
            docArg = ast.List(contentParts[0])
            rest = contentParts[1:]
        elif len(contentParts) > 0:
            docArg = contentParts[1]
            rest = contentParts[2:]
        
        if len(rest) == 0:
            return ast.CallFunc(logixglobal("Doc"),
                                [compileSymbol(doc.tag),
                                 docArg,
                                 properties])
        else:
            val = macros.gensym("val")
            stmts = [ast.Assign([compilePlace(val)],
                                ast.CallFunc(logixglobal("Doc"),
                                             [compileSymbol(doc.tag),
                                              docArg]))]
            for part in rest:
                if isinstance(part, list):
                    if len(part) == 0:
                        continue
                    ext = ast.List(part)
                else:
                    ext = part
                stmts.append(ast.Discard(ast.CallFunc(ast.Getattr(topy(val),
                                                                  "extend"),
                                                      [ext])))
        
            stmts.append(ast.Discard(ast.CallFunc(ast.Getattr(topy(val),
                                                              "extend"),
                                                  [properties])))
            stmts.append(topy(val))
            return ast.Stmt(stmts)
示例#10
0
 def BUILD_MAP(decompiler, not_used):
     # Pushes a new empty dictionary object onto the stack. The argument is ignored and set to zero by the compiler
     return ast.Dict(())