Python ast 模块,Subscript() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用ast.Subscript()

项目:viper    作者:ethereum    | 项目源码 | 文件源码
def get_target(self, target):
        if isinstance(target, ast.Subscript) and self.context.in_for_loop:  # Check if we are doing assignment of an iteration loop.
            raise_exception = False
            if isinstance(target.value, ast.Attribute):
                list_name = "%s.%s" % (target.value.value.id, target.value.attr)
                if list_name in self.context.in_for_loop:
                    raise_exception = True

            if isinstance(target.value, ast.Name) and \
               target.value.id in self.context.in_for_loop:
                list_name = target.value.id
                raise_exception = True

            if raise_exception:
                raise StructureException("Altering list '%s' which is being iterated!" % list_name, self.stmt)

        if isinstance(target, ast.Name) and target.id in self.context.forvars:
            raise StructureException("Altering iterator '%s' which is in use!" % target.id, self.stmt)
        target = Expr.parse_variable_location(target, self.context)
        if target.location == 'storage' and self.context.is_constant:
            raise ConstancyViolationException("Cannot modify storage inside a constant function: %s" % target.annotation)
        if not target.mutable:
            raise ConstancyViolationException("Cannot modify function argument: %s" % target.annotation)
        return target
项目:viper    作者:ethereum    | 项目源码 | 文件源码
def __init__(self, expr, context):
        self.expr = expr
        self.context = context
        self.expr_table = {
            LLLnode: self.get_expr,
            ast.Num: self.number,
            ast.Str: self.string,
            ast.NameConstant: self.constants,
            ast.Name: self.variables,
            ast.Attribute: self.attribute,
            ast.Subscript: self.subscript,
            ast.BinOp: self.arithmetic,
            ast.Compare: self.compare,
            ast.BoolOp: self.boolean_operations,
            ast.UnaryOp: self.unary_operations,
            ast.Call: self.call,
            ast.List: self.list_literals,
            ast.Dict: self.struct_literals,
            ast.Tuple: self.tuple_literals,
        }
        expr_type = self.expr.__class__
        if expr_type in self.expr_table:
            self.lll_node = self.expr_table[expr_type]()
        else:
            raise Exception("Unsupported operator: %r" % ast.dump(self.expr))
项目:Lyra    作者:caterinaurban    | 项目源码 | 文件源码
def resolve_type_annotation(annotation):
    """Type annotation resolution."""

    if isinstance(annotation, ast.Name):
        if annotation.id == 'bool':
            return BooleanLyraType()
        elif annotation.id == 'int':
            return IntegerLyraType()
        elif annotation.id == 'float':
            return FloatLyraType()
        elif annotation.id == 'str':
            return StringLyraType()

    if isinstance(annotation, ast.Subscript):
        if annotation.value.id == 'List':
            value = resolve_type_annotation(annotation.slice.value)
            return ListLyraType(value)

    raise NotImplementedError(f"Type annotation {annotation} is not yet supported!")
项目:ITAP-django    作者:krivers    | 项目源码 | 文件源码
def cleanupSlices(a):
    """Remove any slice shenanigans, because Python lets you include unneccessary values"""
    if not isinstance(a, ast.AST):
        return a
    if type(a) == ast.Subscript:
        if type(a.slice) == ast.Slice:
            # Lower defaults to 0
            if a.slice.lower != None and type(a.slice.lower) == ast.Num and a.slice.lower.n == 0:
                a.slice.lower = None
            # Upper defaults to len(value)
            if a.slice.upper != None and type(a.slice.upper) == ast.Call and \
                type(a.slice.upper.func) == ast.Name and a.slice.upper.func.id == "len":
                if compareASTs(a.value, a.slice.upper.args[0], checkEquality=True) == 0:
                    a.slice.upper = None
            # Step defaults to 1
            if a.slice.step != None and type(a.slice.step) == ast.Num and a.slice.step.n == 1:
                a.slice.step = None
    return applyToChildren(a, cleanupSlices)
项目:pyt    作者:python-security    | 项目源码 | 文件源码
def get_call_names_helper(node, result):
    """Recursively finds all function names."""
    if isinstance(node, ast.Name):
        if node.id not in BLACK_LISTED_CALL_NAMES:
            result.append(node.id)
        return result
    elif isinstance(node, ast.Call):
        return result
    elif isinstance(node, ast.Subscript):
        return get_call_names_helper(node.value, result)
    elif isinstance(node, ast.Str):
        result.append(node.s)
        return result
    else:
        result.append(node.attr)
        return get_call_names_helper(node.value, result)
项目:bandit-ss    作者:zeroSteiner    | 项目源码 | 文件源码
def get_attribute_name(node, import_aliases=None):
    import_aliases = import_aliases or {}
    if not isinstance(node, ast.Attribute):
        raise ValueError('node must be an instance of ast.Attribute')
    base = node.attr
    name = ''
    node = node.value
    while isinstance(node, ast.Attribute):
        name = node.attr + '.' + name
        node = node.value
    if isinstance(node, (ast.Call, ast.Subscript)):
        return None
    if not isinstance(node, ast.Name):
        raise ValueError('could not resolve node for attribute')
    name = (node.id + '.' + name)[:-1]
    return import_aliases.get(name, name) + '.' + base
项目:bandit-ss    作者:zeroSteiner    | 项目源码 | 文件源码
def _solve(self):
        import_aliases = (self.context._context['import_aliases'] if self.context else None)
        cursor_node = self.tainted_node.parent
        while cursor_node != self.target_node:
            test_node = cursor_node
            cursor_node = cursor_node.parent
            if isinstance(test_node, ast.BinOp):
                continue
            elif isinstance(test_node, ast.Call):
                if isinstance(test_node.func, ast.Attribute) and isinstance(test_node.func.value, ast.Str) and test_node.func.attr == 'format':
                    return True
                function = s_utils.get_call_function(test_node, import_aliases=import_aliases)
                if function in ('os.path.abspath', 'os.path.join', 'str'):
                    continue
                elif function == 'os.path.relpath' and s_utils.node_is_child_of_parent(test_node.args[0], self.tainted_node):
                    continue
            elif isinstance(test_node, ast.Subscript):
                continue
            return False
        return True
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_subscript(self):
        sub = ast.Subscript(ast.Name("x", ast.Store()), ast.Index(ast.Num(3)),
                            ast.Load())
        self.expr(sub, "must have Load context")
        x = ast.Name("x", ast.Load())
        sub = ast.Subscript(x, ast.Index(ast.Name("y", ast.Store())),
                            ast.Load())
        self.expr(sub, "must have Load context")
        s = ast.Name("x", ast.Store())
        for args in (s, None, None), (None, s, None), (None, None, s):
            sl = ast.Slice(*args)
            self.expr(ast.Subscript(x, sl, ast.Load()),
                      "must have Load context")
        sl = ast.ExtSlice([])
        self.expr(ast.Subscript(x, sl, ast.Load()), "empty dims on ExtSlice")
        sl = ast.ExtSlice([ast.Index(s)])
        self.expr(ast.Subscript(x, sl, ast.Load()), "must have Load context")
项目:fatoptimizer    作者:vstinner    | 项目源码 | 文件源码
def _get_ast_name_node(node):
    while True:
        # only accept '*var'
        if isinstance(node, ast.Starred):
            # '*var = value' => 'var'
            node = node.value
        elif isinstance(node, ast.Subscript):
            # 'obj[slice] = value' => 'obj'
            node = node.value
        elif isinstance(node, ast.Attribute):
            # 'obj.attr = value' => 'obj'
            node = node.value
        elif (isinstance(node, ast.Call)
             and isinstance(node.func, ast.Attribute)):
            # 'obj.method().attr = value' => 'obj.method'
            node = node.func
        else:
            return node
项目:tabkit    作者:yandex-tabkit    | 项目源码 | 文件源码
def make_subscript(varname, idx, ctx=None, lineno=0, col_offset=0):
    ctx = ctx or ast.Load()
    return ast.Subscript(
        value = ast.Name(
            id = varname,
            ctx = ast.Load(),
            lineno = lineno,
            col_offset = col_offset,
        ),
        slice = ast.Index(
            value = ast.Num(
                n = idx,
                lineno = lineno,
                col_offset = col_offset,
            ),
            lineno = lineno,
            col_offset = col_offset,
        ),
        ctx = ctx,
        lineno = lineno,
        col_offset = col_offset,
    )
项目:TerpreT    作者:51alg    | 项目源码 | 文件源码
def parse_factor_expression(call_or_name_node):
    if isinstance(call_or_name_node, ast.Name):  # a.set_to(b) is shorthand for a.set_to(Copy(b))
        name_node = call_or_name_node
        return None, [name_node.id]

    elif isinstance(call_or_name_node, ast.Call):  # a.set_to(f(b))
        call_node = call_or_name_node
        return call_node.func.id,  [name_or_number(node) for node in call_node.args]

    elif isinstance(call_or_name_node, ast.Num):  # a.observe_value(0)
        num_node = call_or_name_node
        return None, [int(num_node.n)]

    elif isinstance(call_or_name_node, ast.Subscript):
        print ast.dump(call_or_name_node)
        pdb.set_trace()

    else:
        assert False, "Can't parse factor " + ast.dump(call_or_name_node)
项目:TerpreT    作者:51alg    | 项目源码 | 文件源码
def var_to_dvar(var_node):
    if isinstance(var_node, ast.Name):
        name = var_node
        new_name = ast.Name()
        new_id =  "d%s" % name.id
        new_name.id = new_id
        return new_name

    elif isinstance(var_node, ast.Subscript):
        subscript = var_node
        name = subscript.value
        new_name = ast.Name(id="d%s" % name.id)
        new_subscript = ast.Subscript(value=new_name, slice=subscript.slice)
        return new_subscript

    else:
        print "Error: don't know how to dvar a %s" % ast.dump(var_node)
        print r.pretty(var_node)
        assert False
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_subscript(self):
        sub = ast.Subscript(ast.Name("x", ast.Store()), ast.Index(ast.Num(3)),
                            ast.Load())
        self.expr(sub, "must have Load context")
        x = ast.Name("x", ast.Load())
        sub = ast.Subscript(x, ast.Index(ast.Name("y", ast.Store())),
                            ast.Load())
        self.expr(sub, "must have Load context")
        s = ast.Name("x", ast.Store())
        for args in (s, None, None), (None, s, None), (None, None, s):
            sl = ast.Slice(*args)
            self.expr(ast.Subscript(x, sl, ast.Load()),
                      "must have Load context")
        sl = ast.ExtSlice([])
        self.expr(ast.Subscript(x, sl, ast.Load()), "empty dims on ExtSlice")
        sl = ast.ExtSlice([ast.Index(s)])
        self.expr(ast.Subscript(x, sl, ast.Load()), "must have Load context")
项目:Typpete    作者:caterinaurban    | 项目源码 | 文件源码
def _infer_assignment_target(target, context, value_type, solver):
    """Infer the type of a target in an assignment

    Attributes:
        target: the target whose type is to be inferred
        context: the current context level
        value_type: the type of the value assigned to the target

    Target cases:
        - Variable name. Ex: x = 1
        - Tuple. Ex: a, b = 1, "string"
        - List. Ex: [a, b] = [1, "string"]
        - Subscript. Ex: x[0] = 1, x[1 : 2] = [2,3], x["key"] = value
        - Compound: Ex: a, b[0], [c, d], e["key"] = 1, 2.0, [True, False], "value"
    """
    target_type = _infer_one_target(target, context, solver)
    solver.add(axioms.assignment(target_type, value_type, solver.z3_types),
               fail_message="Assignment in line {}".format(target.lineno))

    # Adding weight of 2 to give the assignment soft constraint a higher priority over others.
    solver.optimize.add_soft(target_type == value_type, weight=2)
项目:Typpete    作者:caterinaurban    | 项目源码 | 文件源码
def _delete_element(target, context, lineno, solver):
    """Remove (if needed) a target from the context

    Cases:
        - del var_name: remove its type mapping from the context directly.
        - del subscript:
                    * Tuple/String --> Immutable. Raise exception.
                    * List/Dict --> Do nothing to the context.
    """
    if isinstance(target, (ast.Tuple, ast.List)):  # Multiple deletions
        for elem in target.elts:
            _delete_element(elem, context, lineno, solver)
    elif isinstance(target, ast.Name):
        context.delete_type(target.id)
    elif isinstance(target, ast.Subscript):
        expr.infer(target, context, solver)
        indexed_type = expr.infer(target.value, context, solver)
        solver.add(axioms.delete_subscript(indexed_type, solver.z3_types),
                   fail_message="Deletion in line {}".format(lineno))
    elif isinstance(target, ast.Attribute):
        raise NotImplementedError("Attribute deletion is not supported.")
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_subscript(self):
        sub = ast.Subscript(ast.Name("x", ast.Store()), ast.Index(ast.Num(3)),
                            ast.Load())
        self.expr(sub, "must have Load context")
        x = ast.Name("x", ast.Load())
        sub = ast.Subscript(x, ast.Index(ast.Name("y", ast.Store())),
                            ast.Load())
        self.expr(sub, "must have Load context")
        s = ast.Name("x", ast.Store())
        for args in (s, None, None), (None, s, None), (None, None, s):
            sl = ast.Slice(*args)
            self.expr(ast.Subscript(x, sl, ast.Load()),
                      "must have Load context")
        sl = ast.ExtSlice([])
        self.expr(ast.Subscript(x, sl, ast.Load()), "empty dims on ExtSlice")
        sl = ast.ExtSlice([ast.Index(s)])
        self.expr(ast.Subscript(x, sl, ast.Load()), "must have Load context")
项目:femtocode    作者:diana-hep    | 项目源码 | 文件源码
def unpack_trailer(atom, power_star):
    out = atom
    for trailer in power_star:
        if isinstance(trailer, FcnCall):
            trailer.function = out
            inherit_lineno(trailer, out)
            out = trailer
        elif isinstance(trailer, Attribute):
            trailer.value = out
            inherit_lineno(trailer, out, alt=False)
            if hasattr(out, "alt"):
                trailer.alt = out.alt
            out = trailer
        elif isinstance(trailer, Subscript):
            trailer.value = out
            inherit_lineno(trailer, out)
            out = trailer
        else:
            assert False
    return out
项目:metapensiero.pj    作者:azazel75    | 项目源码 | 文件源码
def Call_new(t, x):
    """Translate ``Foo(...)`` to ``new Foo(...)`` if function name starts
    with a capital letter.
    """
    def getNameString(x):
        if isinstance(x, ast.Name):
            return x.id
        elif isinstance(x, ast.Attribute):
            return str(x.attr)
        elif isinstance(x, ast.Subscript):
            if isinstance(x.slice, ast.Index):
                return str(x.slice.value)

    NAME_STRING = getNameString(x.func)

    if (NAME_STRING and re.search(r'^[A-Z]', NAME_STRING)):
        # TODO: generalize args mangling and apply here
        # assert not any([x.keywords, x.starargs, x.kwargs])
        subj = x
    elif isinstance(x.func, ast.Name) and x.func.id == 'new':
        subj = x.args[0]
    else:
        subj = None
    if subj:
        return Call_default(t, subj, operator='new ')
项目:tidy    作者:cyrus-    | 项目源码 | 文件源码
def _get_pat_and_asc(ctx, binding):
        if isinstance(binding, ast.Subscript):
            value = binding.value
            if isinstance(value, ast.Name) and value.id == 'let':
                slice = binding.slice
                if isinstance(slice, ast.Index):
                    return (slice.value, None)
                elif isinstance(slice, ast.Slice):
                    lower, upper, step = slice.lower, slice.upper, slice.step
                    if lower is not None and upper is not None and step is None:
                        asc = typy._process_asc_ast(ctx, upper)
                        return lower, asc
                    else:
                        raise _errors.TyError("Invalid ascription format.", slice)
                else:
                    raise _errors.TyError("Invalid ascription format.", slice)
            else:
                raise _errors.TyError("Invalid with format.", value)
        else:
            raise _errors.TyError("Invalid with format.", binding)
项目:tidy    作者:cyrus-    | 项目源码 | 文件源码
def _is_ascribed_match_head(cls, e):
        if isinstance(e, ast.Subscript):
            value = e.value
            if cls._is_unascribed_match_head(value):
                slice = e.slice
                if isinstance(slice, ast.Slice):
                    lower, upper, step = slice.lower, slice.upper, slice.step
                    if lower is None and upper is not None and step is None:
                        e.is_match_head = True
                        e.scrutinee = value.scrutinee
                        e.asc_ast = upper
                        return True
                    else:
                        raise _errors.TyError("Invalid ascription format.", slice)
                else:
                    raise _errors.TyError("Invalid ascription format.", slice)
        return False
项目:tidy    作者:cyrus-    | 项目源码 | 文件源码
def translate_pat_Call_constructor(self, ctx, pat, scrutinee_trans):
        lbl = pat.func.id

        tag_loc = ast.Subscript(
            value=scrutinee_trans,
            slice=ast.Index(value=ast.Num(n=0)))
        lbl_condition = ast.Compare(
            left=tag_loc,
            ops=[ast.Eq()],
            comparators=[ast.Str(s=lbl)])

        arg = pat.args[0]
        arg_scrutinee = ast.Subscript(
            value=scrutinee_trans,
            slice=ast.Index(value=ast.Num(n=1)))
        arg_condition, binding_translations = ctx.translate_pat(arg, arg_scrutinee)

        condition = ast.BoolOp(
            op=ast.And(),
            values=[lbl_condition, arg_condition])

        return condition, binding_translations
项目:cohesion    作者:mschwager    | 项目源码 | 文件源码
def get_object_name(obj):
    """
    Return the name of a given object
    """
    name_dispatch = {
        ast.Name: "id",
        ast.Attribute: "attr",
        ast.Call: "func",
        ast.FunctionDef: "name",
        ast.ClassDef: "name",
        ast.Subscript: "value",
    }

    # This is a new ast type in Python 3
    if hasattr(ast, "arg"):
        name_dispatch[ast.arg] = "arg"

    while not isinstance(obj, str):
        assert type(obj) in name_dispatch
        obj = getattr(obj, name_dispatch[type(obj)])

    return obj
项目:pyt    作者:SW10IoT    | 项目源码 | 文件源码
def get_names(self, node, result):
        """Recursively finds all names."""
        if isinstance(node, ast.Name):
            return node.id + result
        elif isinstance(node, ast.Subscript):
            return result
        else:
            return self.get_names(node.value, result + '.' + node.attr)
项目:pyt    作者:SW10IoT    | 项目源码 | 文件源码
def get_call_names_helper(node, result):
    """Recursively finds all function names."""
    if isinstance(node, ast.Name):
        result.append(node.id)
        return result
    elif isinstance(node, ast.Call):
        return result
    elif isinstance(node, ast.Subscript):
        return result
    elif isinstance(node, ast.Str):
        result.append(node.s)
        return result
    else:
        result.append(node.attr)
        return get_call_names_helper(node.value, result)
项目:ITAP-django    作者:krivers    | 项目源码 | 文件源码
def gatherAssignedVars(targets):
    """Take a list of assigned variables and extract the names/subscripts/attributes"""
    if type(targets) != list:
        targets = [targets]
    newTargets = []
    for target in targets:
        if type(target) in [ast.Tuple, ast.List]:
            newTargets += gatherAssignedVars(target.elts)
        elif type(target) in [ast.Name, ast.Subscript, ast.Attribute]:
            newTargets.append(target)
        else:
            log("astTools\tgatherAssignedVars\tWeird Assign Type: " + str(type(target)),"bug")
    return newTargets
项目:pyt    作者:python-security    | 项目源码 | 文件源码
def get_names(self, node, result):
        """Recursively finds all names."""
        if isinstance(node, ast.Name):
            return node.id + result
        elif isinstance(node, ast.Subscript):
            return result
        else:
            return self.get_names(node.value, result + '.' + node.attr)
项目:fz    作者:llllllllll    | 项目源码 | 文件源码
def __getitem__(self, key):
        keyname, key, constants = _normalize_arg(key, self._constants)
        return __class__(
            '%s[%s]' % (self._pname, keyname),
            ast.Subscript(
                value=self._tree,
                slice=ast.Index(value=key),
                ctx=ast.Load(),
            ),
            constants,
        )
项目:pyq    作者:caioariede    | 项目源码 | 文件源码
def match_id(self, id_, node):
        if isinstance(node, (ast.ClassDef, ast.FunctionDef)):
            return node.name == id_

        if isinstance(node, ast.Name):
            return node.id == id_

        if isinstance(node, ast.Attribute):
            return node.attr == id_

        if isinstance(node, ast.Assign):
            for target in node.targets:
                if hasattr(target, 'id'):
                    if target.id == id_:
                        return True
                if hasattr(target, 'elts'):
                    if id_ in self._extract_names_from_tuple(target):
                        return True
                elif isinstance(target, ast.Subscript):
                    if hasattr(target.value, 'id'):
                        if target.value.id == id_:
                            return True

        if isinstance(node, ast.Call):
            if isinstance(node.func, ast.Name) and node.func.id == id_:
                return True

        if id_ == 'print' \
                and hasattr(ast, 'Print') and isinstance(node, ast.Print):
            # Python 2.x compatibility
            return True
项目:deco    作者:alex-sherman    | 项目源码 | 文件源码
def top_level_name(node):
        if type(node) is ast.Name:
            return node.id
        elif type(node) is ast.Subscript or type(node) is ast.Attribute:
            return SchedulerRewriter.top_level_name(node.value)
        return None
项目:deco    作者:alex-sherman    | 项目源码 | 文件源码
def is_valid_assignment(self, node):
        if not (type(node) is ast.Assign and self.is_concurrent_call(node.value)):
            return False
        if len(node.targets) != 1:
            raise self.not_implemented_error(node, "Concurrent assignment does not support multiple assignment targets")
        if not type(node.targets[0]) is ast.Subscript:
            raise self.not_implemented_error(node, "Concurrent assignment only implemented for index based objects")
        return True
项目:vizgen    作者:uva-graphics    | 项目源码 | 文件源码
def get_index(node):
    """
    get the index followed after the given namenode if possible
    """

    parent = node.parent
    if isinstance(parent, ast.Subscript):
        try:
            ind_node = parent.slice.value
            #if there's multiple dimensions in index
            if isinstance(ind_node, ast.Tuple):
                value = []
                for i in range(len(ind_node.elts)):
                    ind_value = py_ast.dump_ast(ind_node.elts[i])
                    value.append(ind_value)
                return value
            else:
                value = py_ast.dump_ast(ind_node)
                return value
        except:
            try:
                value = []
                ind_node = parent.slice.dims
                for i in range(len(ind_node)):
                    ind_value = py_ast.dump_ast(ind_node[i])
                    value.append(ind_value)
                return value
            except:
                return []
    else:
        return []
项目:TerpreT    作者:51alg    | 项目源码 | 文件源码
def update_variable_domains(variable_domains, node_list):
    '''Updates variable_domains by inserting mappings from a variable name to the to the number of
    elements in their data domain.

    Program variables are created in assignments of the form
    "{varName} = Var({size})" or "{varName} = Param({size})".

    '''
    for ch in node_list:
        if isinstance(ch, ast.Assign) and len(ch.targets) == 1:
            name = astunparse.unparse(ch.targets[0]).rstrip()
            rhs = ch.value

            if isinstance(rhs, ast.Call):
                decl_name = rhs.func.id
                args = rhs.args
            elif isinstance(rhs, ast.Subscript) and isinstance(rhs.value, ast.Call):
                decl_name = rhs.value.func.id
                args = rhs.value.args
            else:
                continue

            if decl_name not in ["Param", "Var", "Input", "Output"]:
                continue

            if len(args) > 1:
                error.error('More than one size parameter in variable declaration of "%s".' % (name), ch)
            size = args[0]

            if isinstance(size, ast.Num):
                if name in variable_domains and variable_domains[name] != size.n:
                    error.fatal_error("Trying to reset the domain of variable '%s' to '%i' (old value '%i')." % (name, size.n, variable_domains[name]), size) 
                variable_domains[name] = size.n
            else:
                error.fatal_error("Trying to declare variable '%s', but size parameters '%s' is not understood." % (name, astunparse.unparse(size).rstrip()), size)
项目:TerpreT    作者:51alg    | 项目源码 | 文件源码
def flatten_array_declarations(root):
    class Transformer(ast.NodeTransformer):
        def visit_FunctionDef(self, node):
            return node

        def visit_Assign(self, node):
            if isinstance(node.value, ast.Subscript) and isinstance(node.value.value, ast.Call):
                subscr = node.value
                call = subscr.value

                if len(node.targets) > 1:
                    error.error('Cannot use multiple assignment in array declaration.', node)

                variable_name = node.targets[0].id
                value_type = call.func.id
                declaration_args = call.args

                # Get the indices being accessed.
                shape = slice_node_to_tuple_of_numbers(subscr.slice)

                new_assigns = []
                for indices in itertools.product(*[range(n) for n in shape]):
                    index_name = flattened_array_name(variable_name, indices)
                    new_index_name_node = ast.copy_location(ast.Name(index_name, ast.Store()), node)
                    new_value_type_node = ast.copy_location(ast.Name(value_type, ast.Load()), node)
                    new_declaration_args = [copy.deepcopy(arg) for arg in declaration_args]
                    new_call_node = ast.copy_location(ast.Call(new_value_type_node, new_declaration_args, [], None, None), node)
                    new_assign = ast.Assign([new_index_name_node], new_call_node)
                    new_assign = ast.copy_location(new_assign, node)
                    new_assigns.append(new_assign)
                return new_assigns
            else:
                return node

    return Transformer().visit(root)
项目:TerpreT    作者:51alg    | 项目源码 | 文件源码
def is_declaration_of_type(node, typ):
    if isinstance(node, ast.Subscript):
        return is_declaration_of_type(node.value, typ)
    if not isinstance(node, ast.Call): return False
    if not isinstance(node.func, ast.Name): return False
    return node.func.id == typ
项目:TerpreT    作者:51alg    | 项目源码 | 文件源码
def is_declaration(node):
    if isinstance(node, ast.Subscript):
        return is_declaration(node.value)
    if not isinstance(node, ast.Call): return False
    if not isinstance(node.func, ast.Name): return False
    return node.func.id in ["Input", "Output", "Var", "Hyper", "Param"]
项目:TerpreT    作者:51alg    | 项目源码 | 文件源码
def get_var_name(node):
    if isinstance(node, ast.Name):
        return node.id
    elif isinstance(node, ast.Subscript):
        return get_var_name(node.value)
    elif isinstance(node, ast.Call):
        return None  # This is the Input()[10] case
    else:
        raise Exception("Can't extract var name from '%s'" % (unparse(node).rstrip()))
项目:TerpreT    作者:51alg    | 项目源码 | 文件源码
def generate_io_stmt(input_idx, var_name, value, func_name):
    if value is None:
        return []
    elif isinstance(value, list):
        return [ast.Expr(
                    ast.Call(
                        ast.Attribute(
                            ast.Subscript(
                                ast.Name(var_name, ast.Load()),
                                ast.Index(
                                    ast.Tuple([ast.Num(input_idx),
                                               ast.Num(val_idx)],
                                               ast.Load())),
                                ast.Load()),
                            func_name,
                            ast.Load()),
                        [ast.Num(val)],
                        [], None, None))
                for val_idx, val in enumerate(value)
                if val is not None]
    else:
        return [ast.Expr(
                    ast.Call(
                        ast.Attribute(
                            ast.Subscript(
                                ast.Name(var_name, ast.Load()),
                                ast.Index(ast.Num(input_idx)),
                                ast.Load()),
                            func_name,
                            ast.Load()),
                        [ast.Num(value)],
                        [], None, None))]
项目:TerpreT    作者:51alg    | 项目源码 | 文件源码
def rhs_function(node):
    if not isinstance(node, ast.Assign): return None
    rhs = node.value
    if isinstance(rhs, ast.Call):
        return rhs
    elif isinstance(rhs, ast.BinOp):
        return rhs
    elif isinstance(rhs, ast.UnaryOp):
        return rhs
    elif isinstance(rhs, ast.Subscript):
        return rhs
项目:TerpreT    作者:51alg    | 项目源码 | 文件源码
def var_id(var_node):
    if isinstance(var_node, ast.Name):
        return var_node.id
    elif isinstance(var_node, ast.Subscript):
        return var_node.value.id
项目:XQuant    作者:X0Leon    | 项目源码 | 文件源码
def top_level_name(node):
        if type(node) is ast.Name:
            return node.id
        elif type(node) is ast.Subscript or type(node) is ast.Attribute:
            return SchedulerRewriter.top_level_name(node.value)
        return None
项目:XQuant    作者:X0Leon    | 项目源码 | 文件源码
def is_valid_assignment(self, node):
        if not (type(node) is ast.Assign and self.is_concurrent_call(node.value)):
            return False
        if len(node.targets) != 1:
            raise ValueError("???????????")
        if not type(node.targets[0]) is ast.Subscript:
            raise ValueError("??????????")
        return True
项目:hazzy    作者:KurtJacobson    | 项目源码 | 文件源码
def __init__(self, operators=None, functions=None, names=None):
        """
            Create the evaluator instance.  Set up valid operators (+,-, etc)
            functions (add, random, get_val, whatever) and names. """

        if not operators:
            operators = DEFAULT_OPERATORS
        if not functions:
            functions = DEFAULT_FUNCTIONS
        if not names:
            names = DEFAULT_NAMES

        self.operators = operators
        self.functions = functions
        self.names = names

        self.nodes = {
            ast.Num: self._eval_num,
            ast.Str: self._eval_str,
            ast.Name: self._eval_name,
            ast.UnaryOp: self._eval_unaryop,
            ast.BinOp: self._eval_binop,
            ast.BoolOp: self._eval_boolop,
            ast.Compare: self._eval_compare,
            ast.IfExp: self._eval_ifexp,
            ast.Call: self._eval_call,
            ast.keyword: self._eval_keyword,
            ast.Subscript: self._eval_subscript,
            ast.Attribute: self._eval_attribute,
            ast.Index: self._eval_index,
            ast.Slice: self._eval_slice,
        }

        # py3k stuff:
        if hasattr(ast, 'NameConstant'):
            self.nodes[ast.NameConstant] = self._eval_nameconstant
        elif isinstance(self.names, dict) and "None" not in self.names:
            self.names["None"] = None
项目:Typpete    作者:caterinaurban    | 项目源码 | 文件源码
def _infer_one_target(target, context, solver):
    """
    Get the type of the left hand side of an assignment

    :param target: The target on the left hand side
    :param context: The current context level
    :param solver: The SMT solver
    :return: the type of the target
    """
    if isinstance(target, ast.Name):
        if target.id in context.types_map:
            return context.get_type(target.id)
        else:
            target_type = solver.new_z3_const("assign")
            context.set_type(target.id, target_type)
            return target_type
    elif isinstance(target, ast.Tuple):
        args_types = []
        for elt in target.elts:
            args_types.append(_infer_one_target(elt, context, solver))
        return solver.z3_types.tuples[len(args_types)](*args_types)
    elif isinstance(target, ast.List):
        list_type = solver.new_z3_const("assign")
        for elt in target.elts:
            solver.add(list_type == _infer_one_target(elt, context, solver),
                       fail_message="List assignment in line {}".format(target.lineno))
        return solver.z3_types.list(list_type)
    target_type = expr.infer(target, context, solver)

    if isinstance(target, ast.Subscript):
        solver.add(axioms.subscript_assignment(expr.infer(target.value, context, solver), solver.z3_types),
                   fail_message="Subscript assignment in line {}".format(target.lineno))

    return target_type
项目:empyrion-python-api    作者:huhlig    | 项目源码 | 文件源码
def scan_opcodes_cli(self, co):
        import ast
        with open(co.co_filename, 'rU') as f:
            nodes = ast.parse(f.read(), co.co_filename)

        items = []

        class ModuleFinderVisitor(ast.NodeVisitor):
            def visit_Assign(self, node):
                for x in node.targets:
                    if isinstance(x, ast.Subscript):
                        if isinstance(x.value, ast.Name):
                            items.append(("store", (x.value.id, )))
                        elif isinstance(x.value, ast.Attribute):
                            items.append(("store", (x.value.attr, )))
                        else:
                            print 'Unknown in store: %s' % type(x.value).__name__
                    elif isinstance(x, ast.Name):
                        items.append(("store", (x.id, )))

            def visit_Import(self, node):
                items.extend([("import", (None, x.name)) for x in node.names])

            def visit_ImportFrom(self, node):
                if node.level == 1:
                    items.append(("relative_import", (node.level, [x.name for x in node.names], node.module)))
                else:
                    items.extend([("import", ([x.name for x in node.names], node.module))])

        v = ModuleFinderVisitor()
        v.visit(nodes)

        for what, args in items:
            yield what, args
项目:yui    作者:item4    | 项目源码 | 文件源码
def resolve_attr_id(node):
    if isinstance(node, (ast.Attribute, ast.Subscript)):
        value_id = None
        if isinstance(node.value, (ast.Name, ast.Attribute, ast.Subscript)):
            value_id = resolve_attr_id(node.value)
        elif isinstance(node.value, ast.Call):
            value_id = resolve_attr_id(node.value)
        elif isinstance(node.value, ast.Str):
            value_id = 'str'
        elif isinstance(node.value, ast.Bytes):
            value_id = 'bytes'
        elif isinstance(node.value, (ast.List, ast.ListComp)):
            value_id = 'list'
        elif isinstance(node.value, ast.Tuple):
            value_id = 'tuple'
        elif isinstance(node.value, (ast.Set, ast.SetComp)):
            value_id = 'set'
        elif isinstance(node.value, (ast.Dict, ast.DictComp)):
            value_id = 'dict'
        else:
            raise SyntaxError(
                'unsupport type: {}'.format(ast.dump(node.value))
            )

        if isinstance(node, ast.Attribute):
            return '{}.{}'.format(value_id, node.attr)
        elif isinstance(node, ast.Subscript):
            slice = None
            if isinstance(node.slice.value, ast.Str):
                slice = node.slice.value.s
            elif isinstance(node.slice.value, ast.Num):
                slice = node.slice.value.n
            elif isinstance(node.slice.value, ast.Name):
                slice = resolve_attr_id(node.slice.value)
            return '{}[{}]'.format(value_id, slice)
    elif isinstance(node, ast.Call):
        return '{}()'.format(resolve_attr_id(node.func))
    return node.id
项目:insights-core    作者:RedHatInsights    | 项目源码 | 文件源码
def _build_subscript(value1, value2):
    return Subscript(
        value=value1,
        slice=Index(value=value2),
        ctx=Load())
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def _assertTrueorder(self, ast_node, parent_pos, reverse_check = False):
        def should_reverse_check(parent, child):
            # In some situations, the children of nodes occur before
            # their parents, for example in a.b.c, a occurs before b
            # but a is a child of b.
            if isinstance(parent, ast.Call):
                if parent.func == child:
                    return True
            if isinstance(parent, (ast.Attribute, ast.Subscript)):
                return True
            return False

        if not isinstance(ast_node, ast.AST) or ast_node._fields is None:
            return
        if isinstance(ast_node, (ast.expr, ast.stmt, ast.excepthandler)):
            node_pos = (ast_node.lineno, ast_node.col_offset)
            if reverse_check:
                self.assertTrue(node_pos <= parent_pos)
            else:
                self.assertTrue(node_pos >= parent_pos)
            parent_pos = (ast_node.lineno, ast_node.col_offset)
        for name in ast_node._fields:
            value = getattr(ast_node, name)
            if isinstance(value, list):
                for child in value:
                    self._assertTrueorder(child, parent_pos,
                                         should_reverse_check(ast_node, child))
            elif value is not None:
                self._assertTrueorder(value, parent_pos,
                                      should_reverse_check(ast_node, value))
项目:tidy    作者:cyrus-    | 项目源码 | 文件源码
def translate_Attribute(self, ctx, e):
        n = _util.odict_idx_of(self.idx, e.attr)
        return ast.copy_location(ast.Subscript(
            value=ctx.translate(e.value),
            slice=ast.Num(n=n),
            ctx=ast.Load()
        ), e)
项目:tidy    作者:cyrus-    | 项目源码 | 文件源码
def translate_Subscript(self, ctx, e):
        value = e.value 
        label = e.slice.value.label
        n = _util.odict_idx_of(self.idx, label)
        return ast.copy_location(ast.Subscript(
            value=ctx.translate(value),
            slice=ast.Num(n=n),
            ctx=ast.Load()
        ), e)
项目:tidy    作者:cyrus-    | 项目源码 | 文件源码
def _labeled_translation(idx_mapping, arg_translation):
    lambda_translation = ast.Lambda(
        args=ast.arguments(
            args=[ast.Name(id='x', ctx=ast.Param())],
            vararg=None,
            kwarg=None,
            defaults=[]),
        body=ast.Tuple(
            elts=list(
                ast.Subscript(
                    value=ast.Name(
                        id='x',
                        ctx=ast.Load()),
                    slice=ast.Index(
                        value=ast.Num(n=n)),
                    ctx=ast.Load())
                for n in idx_mapping
            ),
            ctx=ast.Load()
        )
    )
    return ast.Call(
        func=lambda_translation,
        args=[arg_translation],
        keywords=[],
        starargs=[],
        kwargs=None
    )