Exemple #1
0
 def for_tree(cls, tree=None):
     if tree is not None:
         scope = analyze_scope(tree)
         taken_names = scope.locals | scope.globals
     else:
         taken_names = None
     return cls(taken_names=taken_names)
Exemple #2
0
def mangle(gen_sym, node):
    fn_locals = analyze_scope(node).locals
    state, new_node = _mangle(
        dict(gen_sym=gen_sym, mangled=immutabledict()),
        node,
        ctx=dict(fn_locals=fn_locals))
    return state.gen_sym, new_node
Exemple #3
0
def _can_remove_assignment(assign_node, node_list):
    """
    Can remove it if:
    * it is "simple"
    * result it not used in "Store" context elsewhere
    """
    if (len(assign_node.targets) == 1 and type(assign_node.targets[0]) == ast.Name
            and type(assign_node.value) == ast.Name):
        src_name = assign_node.value.id
        dest_name = assign_node.targets[0].id
        if dest_name not in analyze_scope(node_list).locals:
            return True, dest_name, src_name
    return False, None, None
Exemple #4
0
    def from_object(cls, func, ignore_decorators=False):
        """
        Creates a ``Function`` object from an evaluated function.
        """

        src = getsource(func)
        tree = ast.parse(src).body[0]
        if ignore_decorators:
            tree = replace_fields(tree, decorator_list=[])

        global_values = func.__globals__

        closure_vals = get_closure(func)

        scope = analyze_scope(tree)
        func_name = func.__name__

        # Builtins can be either a dict or a module
        builtins = global_values["__builtins__"]
        if not isinstance(builtins, dict):
            builtins = dict(vars(builtins))

        globals_ = {}
        for name in scope.globals:
            if name == func_name:
                globals_[name] = func
            elif name in global_values:
                globals_[name] = global_values[name]
            elif name in builtins:
                globals_[name] = builtins[name]
            elif name in closure_vals:
                continue
            else:
                raise NameError(name)

        compiler_flags = func.__code__.co_flags

        # We only need the flags corresponding to future features.
        # Also, these are the only ones supported by compile().
        compiler_flags = compiler_flags & FUTURE_FLAGS

        return cls(tree, globals_, closure_vals, compiler_flags)
Exemple #5
0
def prune_assignments(node, constants):
    scope = analyze_scope(node.body)
    node = remove_unused_assignments(node, ctx=dict(locals_used=scope.locals_used))
    node = remove_simple_assignments(node)
    return node, constants