Ejemplo n.º 1
0
def p_expression_set(p):
    '''expression : LBRACE csv RBRACE
                  | LBRACE csv COMMA RBRACE
                  | LBRACE RBRACE
    '''
    if len(p) == 3:
        p[0] = ast.Set((), ast.Store())
    else:
        p[0] = ast.Set(p[2], ast.Store())
Ejemplo n.º 2
0
def ast_repr(x):
    """Similar to repr(), but returns an AST instead of a String, which when
    evaluated will return the given value."""
    if type(x) in (int, float): return ast.Num(n=x)
    elif type(x) in (str, unicode): return ast.Str(s=x)
    elif type(x) is list: return ast.List(elts=map(ast_repr, x))
    elif type(x) is dict:
        return ast.Dict(keys=map(ast_repr, x.keys()),
                        values=map(ast_repr, x.values()))
    elif type(x) is set:
        return ast.Set(elts=map(ast_repr, x))
    elif type(x) is Literal:
        return x.body
    elif x is None:
        return ast.Name(id="None")
    elif x is True:
        return ast.Name(id="True")
    elif x is False:
        return ast.Name(id="False")
    elif isinstance(x, ast.AST):
        fields = [ast.keyword(a, ast_repr(b)) for a, b in ast.iter_fields(x)]
        return ast.Call(func=ast.Name(id=x.__class__.__name__),
                        args=[],
                        keywords=fields,
                        starargs=None,
                        kwargs=None)
    raise Exception("Don't know how to ast_repr this: ", x)
Ejemplo n.º 3
0
def value2pyliteral(val):  # noqa: C901
    """
    Transforms a python value into a literal in AST form.
    """
    if val is None:
        return ast.NameConstant(value=None)
    elif val is ...:
        return ast.Ellipsis()
    elif val is True:
        return ast.NameConstant(value=True)
    elif val is False:
        return ast.NameConstant(value=False)
    elif isinstance(val, int):
        return ast.Num(n=val)
    elif isinstance(val, float):
        return ast.Num(n=val)
    elif isinstance(val, str):
        return ast.Str(s=val)
    elif isinstance(val, bytes):
        return ast.Bytes(s=val)
    elif isinstance(val, tuple):
        return ast.Tuple(elts=[value2pyliteral(item) for item in val])
    elif isinstance(val, list):
        return ast.List(elts=[value2pyliteral(item) for item in val])
    elif isinstance(val, dict):
        return ast.Dict(
            # .keys() and .values() have been documented to return things in the
            # same order since Py2
            keys=[value2pyliteral(item) for item in val.keys()],
            values=[value2pyliteral(item) for item in val.values()],
        )
    elif isinstance(val, set):
        return ast.Set(elts=[value2pyliteral(item) for item in val])
    else:
        raise ValueError(f"Can't translate {val!r} into a literal")
Ejemplo n.º 4
0
def size_container_folding(value):
    """
    Convert value to ast expression if size is not too big.

    Converter for sized container.
    """
    if len(value) < MAX_LEN:
        if isinstance(value, list):
            return ast.List(map(to_ast, value), ast.Load())
        elif isinstance(value, tuple):
            return ast.Tuple(map(to_ast, value), ast.Load())
        elif isinstance(value, set):
            return ast.Set(map(to_ast, value))
        elif isinstance(value, dict):
            keys = map(to_ast, value.iterkeys())
            values = map(to_ast, value.itervalues())
            return ast.Dict(keys, values)
        elif isinstance(value, numpy.ndarray):
            return ast.Call(func=ast.Attribute(ast.Name('numpy', ast.Load()),
                                               'array', ast.Load()),
                            args=[to_ast(value.tolist())],
                            keywords=[],
                            starargs=None,
                            kwargs=None)
        else:
            raise ConversionError()
    else:
        raise ToNotEval()
Ejemplo n.º 5
0
def ast_repr(x):
    """Similar to repr(), but returns an AST instead of a String, which when
    evaluated will return the given value."""
    tx = type(x)
    if tx in (int, float):
        return ast.Num(n=x)
    elif tx is bytes:
        return ast.Bytes(s=x)
    elif isinstance(x, str):
        return ast.Str(s=x)
    elif tx is list:
        return ast.List(elts=list(map(ast_repr, x)))
    elif tx is dict:
        return ast.Dict(keys=list(map(ast_repr, x.keys())),
                        values=list(map(ast_repr, x.values())))
    elif tx is set:
        return ast.Set(elts=list(map(ast_repr, x)))
    elif tx is Literal:
        return x.body
    elif tx is Captured:
        return compat.Call(ast.Name(id="Captured"),
                           [x.val, ast_repr(x.name)], [])
    elif tx in (bool, type(None)):
        return ast.NameConstant(value=x)
    elif isinstance(x, ast.AST):
        fields = [ast.keyword(a, ast_repr(b)) for a, b in ast.iter_fields(x)]
        # This hard-codes an expectation that ast classes will be
        # bound to the name `ast`.  There must be a better way.
        return compat.Call(
            ast.Attribute(value=ast.Name(id='ast', ctx=ast.Load()),
                          attr=x.__class__.__name__,
                          ctx=ast.Load()), [], fields)

    raise Exception("Don't know how to ast_repr this: ", x)
Ejemplo n.º 6
0
 def test_empty_iterable_literals(self):
     self.assertSrcRoundtrips('()')
     self.assertSrcRoundtrips('[]')
     self.assertSrcRoundtrips('{}')
     # Python has no literal for empty sets, but code_gen should produce an
     # expression that evaluates to one.
     self.assertEqual(astorexpr(ast.Set([])), set())
Ejemplo n.º 7
0
 def to_node(self):
     if self.is_tuple != '':
         elements = self.__create_elements()
         return ast.Tuple(elts=elements, ctx=ast.Load)
     elif self.is_list != '':
         elements = self.__create_elements()
         return ast.List(elts=elements, ctx=ast.Load)
     elif self.is_dict != '':
         if self.values is None:
             return ast.Dict(keys=[], values=[])
         elif self.__is_dict():
             keys, values = self.__create_keys_values()
             return ast.Dict(keys=keys, values=values)
         else:
             elements = self.__create_elements()
             return ast.Set(elts=elements, ctx=ast.Load)
     elif self.name is not None:
         return self.name.to_node()
     elif self.number is not None:
         return self.number.to_node()
     elif self.none is not None:
         return self.none.to_node()
     elif self.boolean is not None:
         return self.boolean.to_node()
     elif self.string is not None:
         return self.string[0].to_node()
Ejemplo n.º 8
0
def _new_constant(node, value):
    if isinstance(value, ast.AST):
        # convenient shortcut: return the AST object unchanged
        return value

    # FIXME: test the config directly here?

    if value is None:
        new_node = ast.Constant(value=None)
    elif isinstance(value, (bool, int, float, complex, str, bytes)):
        new_node = ast.Constant(value=value)
    elif isinstance(value, (tuple, frozenset)):
        if not _is_constant(value):
            raise TypeError("container items are not constant")
        new_node = ast.Constant(value=value)
    elif isinstance(value, list):
        elts = [_new_constant(node, elt) for elt in value]
        new_node = ast.List(elts=elts, ctx=ast.Load())
    elif isinstance(value, dict):
        keys = []
        values = []
        for key, value in value.items():
            keys.append(_new_constant(node, key))
            values.append(_new_constant(node, value))
        new_node = ast.Dict(keys=keys, values=values, ctx=ast.Load())
    elif isinstance(value, set):
        elts = [_new_constant(node, elt) for elt in value]
        new_node = ast.Set(elts=elts, ctx=ast.Load())
    else:
        raise TypeError("unknown type: %s" % type(value).__name__)

    copy_lineno(node, new_node)
    return new_node
Ejemplo n.º 9
0
def generate_set(max_depth=None):
    from expression import generate_expression
    length = random.randrange(MAX_LIST_LENGTH)
    elts = [
        generate_expression(max_depth=max_depth - 1) for _ in range(length)
    ]
    return ast.Set(elts)
Ejemplo n.º 10
0
 def _py2ast(v, ctx):
     if isinstance(v, (int, long, float)):
         return ast.Num(v)
     elif isinstance(v, str):
         return ast.Str(v)
     elif isinstance(v, list):
         return ast.List([BaseASTOptimizer._py2ast(x, ctx) for x in v], ctx)
     elif isinstance(v, dict):
         items = v.items()
         keys = [BaseASTOptimizer._py2ast(k, ctx) for k, v in items]
         vals = [BaseASTOptimizer._py2ast(v, ctx) for k, v in items]
         return ast.Dict(keys, vals)
     elif isinstance(v, tuple):
         return ast.Tuple([BaseASTOptimizer._py2ast(x, ctx) for x in v],
                          ctx)
     elif isinstance(v, set):
         assert isinstance(ctx, ast.Load)
         return ast.Set([BaseASTOptimizer._py2ast(x, ctx) for x in v])
     elif v is None:
         assert isinstance(ctx, ast.Load)
         return ast.Name('None', ctx)
     elif v is True:
         assert isinstance(ctx, ast.Load)
         return ast.Name('True', ctx)
     elif v is False:
         assert isinstance(ctx, ast.Load)
         return ast.Name('False', ctx)
     else:
         assert False, ('_py2ast', v)
Ejemplo n.º 11
0
 def visit_SetComp(self, node: ast.SetComp) -> ast.Name:
     self.simplified = True
     return simplify_list_comp(
         node,
         self.new_stmts,
         ast.Set(elts=[], ),
         'add',
     )
Ejemplo n.º 12
0
def parse_set(tp: ast.Tuple) -> ast.Set:
    elements = tp.elements
    if len(elements) != 3:
        raise ParseError(f'incorrect format of set!: {tp}')
    pattern = parse_node(elements[1])
    if not isinstance(pattern, ast.Name):
        raise ParseError(f'set!: not an identifier in {tp}')
    value = parse_node(elements[2])
    return ast.Set(pattern, value)
def make_set(cursor_trail, tree):
    """Set(expr* elts)
    """

    selected_node = core_logic.get_node_at_cursor(cursor_trail, tree)
    expr = selected_node if isinstance(selected_node,
                                       ast.expr) else make_expression()

    return ast.Set(elts=[expr])
Ejemplo n.º 14
0
def compile_terminal(sexp: List, closure: Dict) -> ast.AST:
    """
    Compiles primitive type variable (language built-in) to AST node.

    `closure` contains name bindings for target function. Variables of
    non-primitive (built-in) types (without corresponding AST node) 
    are given a unique random name, converted to ast.Name and stored
    in closure for the target function.
    """
    if type(sexp) is bool:
        return ast.NameConstant(value=sexp), closure

    elif type(sexp) in (int, float, complex):
        return ast.Num(n=sexp), closure

    elif type(sexp) is str:
        return ast.Str(s=sexp), closure

    elif type(sexp) is bytes:
        return ast.Bytes(s=sexp), closure

    elif type(sexp) is list:
        elts = []
        for e in sexp:
            e, closure = compile_terminal(e, closure)
            elts.append(e)
        return ast.List(elts=elts, ctx=ast.Load()), closure

    elif type(sexp) is tuple:
        elts = []
        for e in sexp:
            e, closure = compile_terminal(e, closure)
            elts.append(e)
        return ast.Tuple(elts=elts, ctx=ast.Load()), closure

    elif type(sexp) is dict:
        keys, values = [], []
        for k, v in sexp.items():
            k, closure = compile_terminal(k, closure)
            v, closure = compile_terminal(v, closure)
            keys.append(k)
            values.append(v)
        return ast.Dict(keys=keys, values=values), closure

    elif type(sexp) is set:
        elts = []
        for e in sexp:
            e, closure = compile_terminal(e, closure)
            elts.append(e)
        return ast.Set(elts=elts), closure

    else:
        # Generate random name and store variable in closure.
        name = '_%s' % uuid.uuid4().hex
        closure[name] = sexp
        return ast.Name(id=name, ctx=ast.Load()), closure
Ejemplo n.º 15
0
def _node_with_elts(node: ast.AST, new_elts: typ.List[ast.expr]) -> ast.expr:
    if isinstance(node, ast.Call):
        node.args = new_elts
        return node
    elif isinstance(node, ast.List):
        return ast.List(elts=new_elts)
    elif isinstance(node, ast.Set):
        return ast.Set(elts=new_elts)
    elif isinstance(node, ast.Tuple):
        return ast.Tuple(elts=new_elts)
    else:
        raise TypeError(f"Unexpected node type {type(node)}")
Ejemplo n.º 16
0
    def _parse_assign_statement(self, env):
        """ <assign_statement>

        Parses the <assign_statement> language structure.

            assign_statement -> '@' unary_expression '=' logical_expression ';'

        """

        self._match('@')
        unary = self._parse_unary_expression(env)
        self._match('=')
        logical = self._parse_logical_expression(env)
        self._match(';')
        return ast.Set(unary, logical)
Ejemplo n.º 17
0
    def test__get_literal_value(self):
        new_context = context.Context()

        value = ast.Num(42)
        expected = value.n
        self.assertEqual(expected, new_context._get_literal_value(value))

        value = ast.Str('spam')
        expected = value.s
        self.assertEqual(expected, new_context._get_literal_value(value))

        value = ast.List([ast.Str('spam'), ast.Num(42)], ast.Load())
        expected = [ast.Str('spam').s, ast.Num(42).n]
        self.assertListEqual(expected, new_context._get_literal_value(value))

        value = ast.Tuple([ast.Str('spam'), ast.Num(42)], ast.Load())
        expected = (ast.Str('spam').s, ast.Num(42).n)
        self.assertTupleEqual(expected, new_context._get_literal_value(value))

        value = ast.Set([ast.Str('spam'), ast.Num(42)])
        expected = set([ast.Str('spam').s, ast.Num(42).n])
        self.assertSetEqual(expected, new_context._get_literal_value(value))

        value = ast.Dict(['spam', 'eggs'], [42, 'foo'])
        expected = dict(spam=42, eggs='foo')
        self.assertDictEqual(expected, new_context._get_literal_value(value))

        value = ast.Ellipsis()
        self.assertIsNone(new_context._get_literal_value(value))

        value = ast.Name('spam', ast.Load())
        expected = value.id
        self.assertEqual(expected, new_context._get_literal_value(value))

        if six.PY3:
            value = ast.NameConstant(True)
            expected = str(value.value)
            self.assertEqual(expected, new_context._get_literal_value(value))

        if six.PY3:
            value = ast.Bytes(b'spam')
            expected = value.s
            self.assertEqual(expected, new_context._get_literal_value(value))

        self.assertIsNone(new_context._get_literal_value(None))
Ejemplo n.º 18
0
def to_node(value):
    if isinstance(value, str):
        return ast.Str(s=value)
    elif isinstance(value, (int, float)):
        return ast.Num(n=value)
    elif isinstance(value, list):
        return ast.List(elts=list(map(to_node, value)), ctx=ast.Load())
    elif isinstance(value, tuple):
        return ast.Tuple(elts=list(map(to_node, value)), ctx=ast.Load())
    elif isinstance(value, dict):
        keys = list(map(to_node, value.keys()))
        values = list(map(to_node, value.values()))
        return ast.Dict(keys=keys, values=values)
    elif isinstance(value, set):
        return ast.Set(elts=list(map(to_node, value)))
    assert value is None or isinstance(value, ast.AST), \
        'value must be None or AST instance, got {}'.format(
            type(value).__name__
        )
    return value
Ejemplo n.º 19
0
 def to_ast(self, value):
     if (type(value) in (int, long, float, complex)):
         return ast.Num(value)
     elif isinstance(value, bool):
         return ast.Attribute(ast.Name('__builtin__', ast.Load()),
                              'True' if value else 'False', ast.Load())
     elif isinstance(value, str):
         return ast.Str(value)
     elif isinstance(value, list) and len(value) < ConstantFolding.MAX_LEN:
         #SG: unsure whether it Load or something else
         return ast.List(map(self.to_ast, value), ast.Load())
     elif isinstance(value, tuple) and len(value) < ConstantFolding.MAX_LEN:
         return ast.Tuple(map(self.to_ast, value), ast.Load())
     elif isinstance(value, set) and len(value) < ConstantFolding.MAX_LEN:
         return ast.Set(map(self.to_ast, value))
     elif isinstance(value, dict) and len(value) < ConstantFolding.MAX_LEN:
         keys = map(self.to_ast, value.iterkeys())
         values = map(self.to_ast, value.itervalues())
         return ast.Dict(keys, values)
     else:
         raise ConstantFolding.ConversionError()
Ejemplo n.º 20
0
    def test__get_literal_value(self):
        new_context = context.Context()

        value = ast.Num(42)
        expected = value.n
        self.assertEqual(expected, new_context._get_literal_value(value))

        value = ast.Str("spam")
        expected = value.s
        self.assertEqual(expected, new_context._get_literal_value(value))

        value = ast.List([ast.Str("spam"), ast.Num(42)], ast.Load())
        expected = [ast.Str("spam").s, ast.Num(42).n]
        self.assertListEqual(expected, new_context._get_literal_value(value))

        value = ast.Tuple([ast.Str("spam"), ast.Num(42)], ast.Load())
        expected = (ast.Str("spam").s, ast.Num(42).n)
        self.assertTupleEqual(expected, new_context._get_literal_value(value))

        value = ast.Set([ast.Str("spam"), ast.Num(42)])
        expected = {ast.Str("spam").s, ast.Num(42).n}
        self.assertSetEqual(expected, new_context._get_literal_value(value))

        value = ast.Dict(["spam", "eggs"], [42, "foo"])
        expected = dict(spam=42, eggs="foo")
        self.assertDictEqual(expected, new_context._get_literal_value(value))

        value = ast.Ellipsis()
        self.assertIsNone(new_context._get_literal_value(value))

        value = ast.Name("spam", ast.Load())
        expected = value.id
        self.assertEqual(expected, new_context._get_literal_value(value))

        value = ast.Bytes(b"spam")
        expected = value.s
        self.assertEqual(expected, new_context._get_literal_value(value))

        self.assertIsNone(new_context._get_literal_value(None))
Ejemplo n.º 21
0
 def visit_Compare(self, node):
     # TODO: Implement or/and.
     if len(node.ops) > 1:
         return node
     if isinstance(node.ops[0], ast.In):
         return ast.BinOp(left=node.left,
                          op=ast.LShift(),
                          right=node.comparators[0])
     if isinstance(node.ops[0], ast.Eq):
         return ast.BinOp(left=node.left,
                          op=ast.LShift(),
                          right=ast.Set(node.comparators))
     if isinstance(node.ops[0], ast.NotIn):
         node_copy = copy.deepcopy(node)
         node_copy.ops[0] = ast.In()
         return ast.UnaryOp(op=ast.Invert(),
                            operand=self.visit_Compare(node_copy))
     if isinstance(node.ops[0], ast.NotEq):
         node_copy = copy.deepcopy(node)
         node_copy.ops[0] = ast.Eq()
         return ast.UnaryOp(op=ast.Invert(),
                            operand=self.visit_Compare(node_copy))
     return node
Ejemplo n.º 22
0
def new_constant(value, node=None):
    if isinstance(value, bool):
        new_node = ast.Name(id='True' if value else 'False', ctx=ast.Load())
    elif isinstance(value, (int, float, long, complex)):
        new_node = ast.Num(n=value)
    elif isinstance(value, (unicode, str)):
        new_node = ast.Str(s=value)
    elif isinstance(value, (tuple, list)):
        cls = ast.Tuple if isinstance(value, tuple) else ast.List
        elts = [new_constant(elt, node) for elt in value]
        new_node = cls(elts=elts, ctx=ast.Load)
    elif isinstance(value, set):
        elts = [new_constant(elt, node) for elt in value]
        new_node = ast.Set(elts=elts)
    elif isinstance(value, dict):
        keys = [new_constant(k, node) for k in value.keys()]
        values = [new_constant(v, node) for v in value.values()]
        new_node = ast.Dict(keys=keys, values=values)
    elif isinstance(value, frozenset):
        elts = [new_constant(elt, node) for elt in value]
        arg = ast.Tuple(elts=elts, ctx=ast.Load())
        func = ast.Name(id='frozenset', ctx=ast.Load())
        new_node = ast.Call(func=func,
                            args=[arg],
                            keywords=[],
                            starargs=None,
                            kwargs=None)
    elif value is None:
        new_node = ast.Name(id='None', ctx=ast.Load())
    else:
        raise TypeError("unknown type: %s" % type(value).__name__)

    node and copy_lineno(node, new_node)
    new_node.__preinit__(parent=node.parent if node else node.parent)
    new_node.__postinit__()
    return new_node
Ejemplo n.º 23
0
    def visit_set_statement(self, stmt: coll_stmt.SetStatement) -> None:
        # There is no literal for empty sets, so we have to write "set()"
        inner: Any
        if len(stmt.elements) == 0:
            inner = ast.Call(func=ast.Name(id="set", ctx=ast.Load()),
                             args=[],
                             keywords=[])
        else:
            inner = ast.Set(
                elts=[
                    au.create_var_name(self._variable_names, x, True)
                    for x in stmt.elements
                ],
                ctx=ast.Load(),
            )

        self._ast_nodes.append(
            ast.Assign(
                targets=[
                    au.create_var_name(self._variable_names, stmt.ret_val,
                                       False)
                ],
                value=inner,
            ))
Ejemplo n.º 24
0
def as_ast(dct):
    """See https://docs.python.org/2/library/ast.html"""
    if dct['ast_type'] == "Module":
        return ast.Module(dct["body"])
    elif dct['ast_type'] == "Interactive":
        return ast.Interactive(dct["body"])
    elif dct['ast_type'] == "Expression":
        return ast.Expression(dct["body"])
    elif dct['ast_type'] == "Suite":
        return ast.Suite(dct["body"])
    elif dct['ast_type'] == "FunctionDef":
        return ast.FunctionDef(dct["name"], dct["args"], dct["body"],
                               dct["decorator_list"])
    elif dct['ast_type'] == "ClassDef":
        return ast.ClassDef(dct["name"], dct["bases"], dct["body"],
                            dct["decorator_list"])
    elif dct['ast_type'] == "Return":
        return ast.Return(dct["value"])
    elif dct['ast_type'] == "Delete":
        return ast.Delete(dct["targets"])
    elif dct['ast_type'] == "Assign":
        return ast.Assign(dct["targets"], dct["value"])
    elif dct['ast_type'] == "AugAssign":
        return ast.AugAssign(dct["target"], dct["op"], dct["value"])
    elif dct['ast_type'] == "Print":
        return ast.Print(dct["dest"], dct["values"], dct["nl"])
    elif dct['ast_type'] == "For":
        return ast.For(dct["target"], dct["iter"], dct["body"], dct["orelse"])
    elif dct['ast_type'] == "While":
        return ast.While(dct["test"], dct["body"], dct["orelse"])
    elif dct['ast_type'] == "If":
        return ast.If(dct["test"], dct["body"], dct["orelse"])
    elif dct['ast_type'] == "With":
        return ast.With(dct["context_expr"], dct["optional_vars"], dct["body"])
    elif dct['ast_type'] == "Raise":
        return ast.Raise(dct["type"], dct["inst"], dct["tback"])
    elif dct['ast_type'] == "TryExcept":
        return ast.TryExcept(dct["body"], dct["handlers"], dct["orelse"])
    elif dct['ast_type'] == "TryFinally":
        return ast.TryFinally(dct["body"], dct["finalbody"])
    elif dct['ast_type'] == "Assert":
        return ast.Assert(dct["test"], dct["msg"])
    elif dct['ast_type'] == "Import":
        return ast.Import(dct["names"])
    elif dct['ast_type'] == "ImportFrom":
        return ast.ImportFrom(dct["module"], dct["names"], dct["level"])
    elif dct['ast_type'] == "Exec":
        return ast.Exec(dct["body"], dct["globals"], dct["locals"])
    elif dct['ast_type'] == "Global":
        return ast.Global(dct["names"])
    elif dct['ast_type'] == "Expr":
        return ast.Expr(dct["value"])
    elif dct['ast_type'] == "Pass":
        return ast.Pass()
    elif dct['ast_type'] == "Break":
        return ast.Break()
    elif dct['ast_type'] == "Continue":
        return ast.Continue()
    elif dct['ast_type'] == "BoolOp":
        return ast.BoolOp(dct["op"], dct["values"])
    elif dct['ast_type'] == "BinOp":
        return ast.BinOp(dct["left"], dct["op"], dct["right"])
    elif dct['ast_type'] == "UnaryOp":
        return ast.UnaryOp(dct["op"], dct["operand"])
    elif dct['ast_type'] == "Lambda":
        return ast.Lambda(dct["args"], dct["body"])
    elif dct['ast_type'] == "IfExp":
        return ast.IfExp(dct["test"], dct["body"], dct["orelse"])
    elif dct['ast_type'] == "Dict":
        return ast.Dict(dct["keys"], dct["values"])
    elif dct['ast_type'] == "Set":
        return ast.Set(dct["elts"])
    elif dct['ast_type'] == "ListComp":
        return ast.ListComp(dct["elt"], dct["generators"])
    elif dct['ast_type'] == "SetComp":
        return ast.SetComp(dct["elt"], dct["generators"])
    elif dct['ast_type'] == "DictComp":
        return ast.DictComp(dct["key"], dct["value"], dct["generators"])
    elif dct['ast_type'] == "GeneratorExp":
        return ast.GeneratorExp(dct["elt"], dct["generators"])
    elif dct['ast_type'] == "Yield":
        return ast.Yield(dct["value"])
    elif dct['ast_type'] == "Compare":
        return ast.Compare(dct["left"], dct["ops"], dct["comparators"])
    elif dct['ast_type'] == "Call":
        return ast.Call(dct["func"], dct["args"], dct["keywords"],
                        dct["starargs"], dct["kwargs"])
    elif dct['ast_type'] == "Repr":
        return ast.Repr(dct["value"])
    elif dct['ast_type'] == "Num":
        return ast.Num(dct["n"])
    elif dct['ast_type'] == "Str":
        # Converting to ASCII
        return ast.Str(dct["s"].encode('ascii', 'ignore'))
    elif dct['ast_type'] == "Attribute":
        return ast.Attribute(dct["value"], dct["attr"], dct["ctx"])
    elif dct['ast_type'] == "Subscript":
        return ast.Subscript(dct["value"], dct["slice"], dct["ctx"])
    elif dct['ast_type'] == "Name":
        return ast.Name(dct["id"], dct["ctx"])
    elif dct['ast_type'] == "List":
        return ast.List(dct["elts"], dct["ctx"])
    elif dct['ast_type'] == "Tuple":
        return ast.Tuple(dct["elts"], dct["ctx"])
    elif dct['ast_type'] == "Load":
        return ast.Load()
    elif dct['ast_type'] == "Store":
        return ast.Store()
    elif dct['ast_type'] == "Del":
        return ast.Del()
    elif dct['ast_type'] == "AugLoad":
        return ast.AugLoad()
    elif dct['ast_type'] == "AugStore":
        return ast.AugStore()
    elif dct['ast_type'] == "Param":
        return ast.Param()
    elif dct['ast_type'] == "Ellipsis":
        return ast.Ellipsis()
    elif dct['ast_type'] == "Slice":
        return ast.Slice(dct["lower"], dct["upper"], dct["step"])
    elif dct['ast_type'] == "ExtSlice":
        return ast.ExtSlice(dct["dims"])
    elif dct['ast_type'] == "Index":
        return ast.Index(dct["value"])
    elif dct['ast_type'] == "And":
        return ast.And()
    elif dct['ast_type'] == "Or":
        return ast.Or()
    elif dct['ast_type'] == "Add":
        return ast.Add()
    elif dct['ast_type'] == "Sub":
        return ast.Sub()
    elif dct['ast_type'] == "Mult":
        return ast.Mult()
    elif dct['ast_type'] == "Div":
        return ast.Div()
    elif dct['ast_type'] == "Mod":
        return ast.Mod()
    elif dct['ast_type'] == "Pow":
        return ast.Pow()
    elif dct['ast_type'] == "LShift":
        return ast.LShift()
    elif dct['ast_type'] == "RShift":
        return ast.RShift()
    elif dct['ast_type'] == "BitOr":
        return ast.BitOr()
    elif dct['ast_type'] == "BitXor":
        return ast.BitXor()
    elif dct['ast_type'] == "BitAnd":
        return ast.BitAnd()
    elif dct['ast_type'] == "FloorDiv":
        return ast.FloorDiv()
    elif dct['ast_type'] == "Invert":
        return ast.Invert()
    elif dct['ast_type'] == "Not":
        return ast.Not()
    elif dct['ast_type'] == "UAdd":
        return ast.UAdd()
    elif dct['ast_type'] == "USub":
        return ast.USub()
    elif dct['ast_type'] == "Eq":
        return ast.Eq()
    elif dct['ast_type'] == "NotEq":
        return ast.NotEq()
    elif dct['ast_type'] == "Lt":
        return ast.Lt()
    elif dct['ast_type'] == "LtE":
        return ast.LtE()
    elif dct['ast_type'] == "Gt":
        return ast.Gt()
    elif dct['ast_type'] == "GtE":
        return ast.GtE()
    elif dct['ast_type'] == "Is":
        return ast.Is()
    elif dct['ast_type'] == "IsNot":
        return ast.IsNot()
    elif dct['ast_type'] == "In":
        return ast.In()
    elif dct['ast_type'] == "NotIn":
        return ast.NotIn()
    elif dct['ast_type'] == "comprehension":
        return ast.comprehension(dct["target"], dct["iter"], dct["ifs"])
    elif dct['ast_type'] == "ExceptHandler":
        return ast.ExceptHandler(dct["type"], dct["name"], dct["body"])
    elif dct['ast_type'] == "arguments":
        return ast.arguments(dct["args"], dct["vararg"], dct["kwarg"],
                             dct["defaults"])
    elif dct['ast_type'] == "keyword":
        return ast.keyword(dct["arg"], dct["value"])
    elif dct['ast_type'] == "alias":
        return ast.alias(dct["name"], dct["asname"])
    else:
        return dct
Ejemplo n.º 25
0
 def test_empty_set(self):
     self.assertASTEqual(ast.parse(ast.unparse(ast.Set(elts=[]))),
                         ast.parse('{*()}'))
Ejemplo n.º 26
0
 def test_invalid_set(self):
     self.check_invalid(ast.Set(elts=[]))
Ejemplo n.º 27
0
 def test_Set(self):
     self.verify(ast.Set([ast.Num(42)]), '{42}')
     self.verify(ast.Set([ast.Num(2), ast.Num(3)]), '{2,3}')
Ejemplo n.º 28
0
 def test_set(self):
     self.expr(ast.Set([None]), "None disallowed")
     s = ast.Set([ast.Name("x", ast.Store())])
     self.expr(s, "must have Load context")
Ejemplo n.º 29
0
 def visit_Str(self, node):
     return ast.Set(words_dict[node.s])
Ejemplo n.º 30
0
def mk_set(elements):
    return ast.Set(elts=list(elements))