PK       ! =n  n    fix_raise.pynu [        """Fixer for 'raise E, V, T'

raise         -> raise
raise E       -> raise E
raise E, V    -> raise E(V)
raise E, V, T -> raise E(V).with_traceback(T)
raise E, None, T -> raise E.with_traceback(T)

raise (((E, E'), E''), E'''), V -> raise E(V)
raise "foo", V, T               -> warns about string exceptions


CAVEATS:
1) "raise E, V" will be incorrectly translated if V is an exception
   instance. The correct Python 3 idiom is

        raise E from V

   but since we can't detect instance-hood by syntax alone and since
   any client code would have to be changed as well, we don't automate
   this.
"""
# Author: Collin Winter

# Local imports
from .. import pytree
from ..pgen2 import token
from .. import fixer_base
from ..fixer_util import Name, Call, Attr, ArgList, is_tuple

class FixRaise(fixer_base.BaseFix):

    BM_compatible = True
    PATTERN = """
    raise_stmt< 'raise' exc=any [',' val=any [',' tb=any]] >
    """

    def transform(self, node, results):
        syms = self.syms

        exc = results["exc"].clone()
        if exc.type == token.STRING:
            msg = "Python 3 does not support string exceptions"
            self.cannot_convert(node, msg)
            return

        # Python 2 supports
        #  raise ((((E1, E2), E3), E4), E5), V
        # as a synonym for
        #  raise E1, V
        # Since Python 3 will not support this, we recurse down any tuple
        # literals, always taking the first element.
        if is_tuple(exc):
            while is_tuple(exc):
                # exc.children[1:-1] is the unparenthesized tuple
                # exc.children[1].children[0] is the first element of the tuple
                exc = exc.children[1].children[0].clone()
            exc.prefix = " "

        if "val" not in results:
            # One-argument raise
            new = pytree.Node(syms.raise_stmt, [Name("raise"), exc])
            new.prefix = node.prefix
            return new

        val = results["val"].clone()
        if is_tuple(val):
            args = [c.clone() for c in val.children[1:-1]]
        else:
            val.prefix = ""
            args = [val]

        if "tb" in results:
            tb = results["tb"].clone()
            tb.prefix = ""

            e = exc
            # If there's a traceback and None is passed as the value, then don't
            # add a call, since the user probably just wants to add a
            # traceback. See issue #9661.
            if val.type != token.NAME or val.value != "None":
                e = Call(exc, args)
            with_tb = Attr(e, Name('with_traceback')) + [ArgList([tb])]
            new = pytree.Node(syms.simple_stmt, [Name("raise")] + with_tb)
            new.prefix = node.prefix
            return new
        else:
            return pytree.Node(syms.raise_stmt,
                               [Name("raise"), Call(exc, args)],
                               prefix=node.prefix)
PK       ! 5Y
  
    fix_filter.pynu [        # Copyright 2007 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.

"""Fixer that changes filter(F, X) into list(filter(F, X)).

We avoid the transformation if the filter() call is directly contained
in iter(<>), list(<>), tuple(<>), sorted(<>), ...join(<>), or
for V in <>:.

NOTE: This is still not correct if the original code was depending on
filter(F, X) to return a string if X is a string and a tuple if X is a
tuple.  That would require type inference, which we don't do.  Let
Python 2.6 figure it out.
"""

# Local imports
from .. import fixer_base
from ..pytree import Node
from ..pygram import python_symbols as syms
from ..fixer_util import Name, ArgList, ListComp, in_special_context, parenthesize


class FixFilter(fixer_base.ConditionalFix):
    BM_compatible = True

    PATTERN = """
    filter_lambda=power<
        'filter'
        trailer<
            '('
            arglist<
                lambdef< 'lambda'
                         (fp=NAME | vfpdef< '(' fp=NAME ')'> ) ':' xp=any
                >
                ','
                it=any
            >
            ')'
        >
        [extra_trailers=trailer*]
    >
    |
    power<
        'filter'
        trailer< '(' arglist< none='None' ',' seq=any > ')' >
        [extra_trailers=trailer*]
    >
    |
    power<
        'filter'
        args=trailer< '(' [any] ')' >
        [extra_trailers=trailer*]
    >
    """

    skip_on = "future_builtins.filter"

    def transform(self, node, results):
        if self.should_skip(node):
            return

        trailers = []
        if 'extra_trailers' in results:
            for t in results['extra_trailers']:
                trailers.append(t.clone())

        if "filter_lambda" in results:
            xp = results.get("xp").clone()
            if xp.type == syms.test:
                xp.prefix = ""
                xp = parenthesize(xp)

            new = ListComp(results.get("fp").clone(),
                           results.get("fp").clone(),
                           results.get("it").clone(), xp)
            new = Node(syms.power, [new] + trailers, prefix="")

        elif "none" in results:
            new = ListComp(Name("_f"),
                           Name("_f"),
                           results["seq"].clone(),
                           Name("_f"))
            new = Node(syms.power, [new] + trailers, prefix="")

        else:
            if in_special_context(node):
                return None

            args = results['args'].clone()
            new = Node(syms.power, [Name("filter"), args], prefix="")
            new = Node(syms.power, [Name("list"), ArgList([new])] + trailers)
            new.prefix = ""
        new.prefix = node.prefix
        return new
PK       ! 誔*	  *	    fix_apply.pynu [        # Copyright 2006 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.

"""Fixer for apply().

This converts apply(func, v, k) into (func)(*v, **k)."""

# Local imports
from .. import pytree
from ..pgen2 import token
from .. import fixer_base
from ..fixer_util import Call, Comma, parenthesize

class FixApply(fixer_base.BaseFix):
    BM_compatible = True

    PATTERN = """
    power< 'apply'
        trailer<
            '('
            arglist<
                (not argument<NAME '=' any>) func=any ','
                (not argument<NAME '=' any>) args=any [','
                (not argument<NAME '=' any>) kwds=any] [',']
            >
            ')'
        >
    >
    """

    def transform(self, node, results):
        syms = self.syms
        assert results
        func = results["func"]
        args = results["args"]
        kwds = results.get("kwds")
        # I feel like we should be able to express this logic in the
        # PATTERN above but I don't know how to do it so...
        if args:
            if (args.type == self.syms.argument and
                args.children[0].value in {'**', '*'}):
                return  # Make no change.
        if kwds and (kwds.type == self.syms.argument and
                     kwds.children[0].value == '**'):
            return  # Make no change.
        prefix = node.prefix
        func = func.clone()
        if (func.type not in (token.NAME, syms.atom) and
            (func.type != syms.power or
             func.children[-2].type == token.DOUBLESTAR)):
            # Need to parenthesize
            func = parenthesize(func)
        func.prefix = ""
        args = args.clone()
        args.prefix = ""
        if kwds is not None:
            kwds = kwds.clone()
            kwds.prefix = ""
        l_newargs = [pytree.Leaf(token.STAR, "*"), args]
        if kwds is not None:
            l_newargs.extend([Comma(),
                              pytree.Leaf(token.DOUBLESTAR, "**"),
                              kwds])
            l_newargs[-2].prefix = " " # that's the ** token
        # XXX Sometimes we could be cleverer, e.g. apply(f, (x, y) + t)
        # can be translated into f(x, y, *t) instead of f(*(x, y) + t)
        #new = pytree.Node(syms.power, (func, ArgList(l_newargs)))
        return Call(func, l_newargs, prefix=prefix)
PK       ! %TW68  8  
  fix_map.pynu [        # Copyright 2007 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.

"""Fixer that changes map(F, ...) into list(map(F, ...)) unless there
exists a 'from future_builtins import map' statement in the top-level
namespace.

As a special case, map(None, X) is changed into list(X).  (This is
necessary because the semantics are changed in this case -- the new
map(None, X) is equivalent to [(x,) for x in X].)

We avoid the transformation (except for the special case mentioned
above) if the map() call is directly contained in iter(<>), list(<>),
tuple(<>), sorted(<>), ...join(<>), or for V in <>:.

NOTE: This is still not correct if the original code was depending on
map(F, X, Y, ...) to go on until the longest argument is exhausted,
substituting None for missing values -- like zip(), it now stops as
soon as the shortest argument is exhausted.
"""

# Local imports
from ..pgen2 import token
from .. import fixer_base
from ..fixer_util import Name, ArgList, Call, ListComp, in_special_context
from ..pygram import python_symbols as syms
from ..pytree import Node


class FixMap(fixer_base.ConditionalFix):
    BM_compatible = True

    PATTERN = """
    map_none=power<
        'map'
        trailer< '(' arglist< 'None' ',' arg=any [','] > ')' >
        [extra_trailers=trailer*]
    >
    |
    map_lambda=power<
        'map'
        trailer<
            '('
            arglist<
                lambdef< 'lambda'
                         (fp=NAME | vfpdef< '(' fp=NAME ')'> ) ':' xp=any
                >
                ','
                it=any
            >
            ')'
        >
        [extra_trailers=trailer*]
    >
    |
    power<
        'map' args=trailer< '(' [any] ')' >
        [extra_trailers=trailer*]
    >
    """

    skip_on = 'future_builtins.map'

    def transform(self, node, results):
        if self.should_skip(node):
            return

        trailers = []
        if 'extra_trailers' in results:
            for t in results['extra_trailers']:
                trailers.append(t.clone())

        if node.parent.type == syms.simple_stmt:
            self.warning(node, "You should use a for loop here")
            new = node.clone()
            new.prefix = ""
            new = Call(Name("list"), [new])
        elif "map_lambda" in results:
            new = ListComp(results["xp"].clone(),
                           results["fp"].clone(),
                           results["it"].clone())
            new = Node(syms.power, [new] + trailers, prefix="")

        else:
            if "map_none" in results:
                new = results["arg"].clone()
                new.prefix = ""
            else:
                if "args" in results:
                    args = results["args"]
                    if args.type == syms.trailer and \
                       args.children[1].type == syms.arglist and \
                       args.children[1].children[0].type == token.NAME and \
                       args.children[1].children[0].value == "None":
                        self.warning(node, "cannot convert map(None, ...) "
                                     "with multiple arguments because map() "
                                     "now truncates to the shortest sequence")
                        return

                    new = Node(syms.power, [Name("map"), args.clone()])
                    new.prefix = ""

                if in_special_context(node):
                    return None

            new = Node(syms.power, [Name("list"), ArgList([new])] + trailers)
            new.prefix = ""

        new.prefix = node.prefix
        return new
PK       ! iG      fix_long.pynu [        # Copyright 2006 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.

"""Fixer that turns 'long' into 'int' everywhere.
"""

# Local imports
from lib2to3 import fixer_base
from lib2to3.fixer_util import is_probably_builtin


class FixLong(fixer_base.BaseFix):
    BM_compatible = True
    PATTERN = "'long'"

    def transform(self, node, results):
        if is_probably_builtin(node):
            node.value = "int"
            node.changed()
PK       ! ʿ>1      fix_paren.pynu [        """Fixer that adds parentheses where they are required

This converts ``[x for x in 1, 2]`` to ``[x for x in (1, 2)]``."""

# By Taek Joo Kim and Benjamin Peterson

# Local imports
from .. import fixer_base
from ..fixer_util import LParen, RParen

# XXX This doesn't support nested for loops like [x for x in 1, 2 for x in 1, 2]
class FixParen(fixer_base.BaseFix):
    BM_compatible = True

    PATTERN = """
        atom< ('[' | '(')
            (listmaker< any
                comp_for<
                    'for' NAME 'in'
                    target=testlist_safe< any (',' any)+ [',']
                     >
                    [any]
                >
            >
            |
            testlist_gexp< any
                comp_for<
                    'for' NAME 'in'
                    target=testlist_safe< any (',' any)+ [',']
                     >
                    [any]
                >
            >)
        (']' | ')') >
    """

    def transform(self, node, results):
        target = results["target"]

        lparen = LParen()
        lparen.prefix = target.prefix
        target.prefix = "" # Make it hug the parentheses
        target.insert_child(0, lparen)
        target.append_child(RParen())
PK       ! Z6      fix_print.pynu [        # Copyright 2006 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.

"""Fixer for print.

Change:
    'print'          into 'print()'
    'print ...'      into 'print(...)'
    'print ... ,'    into 'print(..., end=" ")'
    'print >>x, ...' into 'print(..., file=x)'

No changes are applied if print_function is imported from __future__

"""

# Local imports
from .. import patcomp
from .. import pytree
from ..pgen2 import token
from .. import fixer_base
from ..fixer_util import Name, Call, Comma, String


parend_expr = patcomp.compile_pattern(
              """atom< '(' [atom|STRING|NAME] ')' >"""
              )


class FixPrint(fixer_base.BaseFix):

    BM_compatible = True

    PATTERN = """
              simple_stmt< any* bare='print' any* > | print_stmt
              """

    def transform(self, node, results):
        assert results

        bare_print = results.get("bare")

        if bare_print:
            # Special-case print all by itself
            bare_print.replace(Call(Name("print"), [],
                               prefix=bare_print.prefix))
            return
        assert node.children[0] == Name("print")
        args = node.children[1:]
        if len(args) == 1 and parend_expr.match(args[0]):
            # We don't want to keep sticking parens around an
            # already-parenthesised expression.
            return

        sep = end = file = None
        if args and args[-1] == Comma():
            args = args[:-1]
            end = " "
        if args and args[0] == pytree.Leaf(token.RIGHTSHIFT, ">>"):
            assert len(args) >= 2
            file = args[1].clone()
            args = args[3:] # Strip a possible comma after the file expression
        # Now synthesize a print(args, sep=..., end=..., file=...) node.
        l_args = [arg.clone() for arg in args]
        if l_args:
            l_args[0].prefix = ""
        if sep is not None or end is not None or file is not None:
            if sep is not None:
                self.add_kwarg(l_args, "sep", String(repr(sep)))
            if end is not None:
                self.add_kwarg(l_args, "end", String(repr(end)))
            if file is not None:
                self.add_kwarg(l_args, "file", file)
        n_stmt = Call(Name("print"), l_args)
        n_stmt.prefix = node.prefix
        return n_stmt

    def add_kwarg(self, l_nodes, s_kwd, n_expr):
        # XXX All this prefix-setting may lose comments (though rarely)
        n_expr.prefix = ""
        n_argument = pytree.Node(self.syms.argument,
                                 (Name(s_kwd),
                                  pytree.Leaf(token.EQUAL, "="),
                                  n_expr))
        if l_nodes:
            l_nodes.append(Comma())
            n_argument.prefix = " "
        l_nodes.append(n_argument)
PK       ! ޽      fix_standarderror.pynu [        # Copyright 2007 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.

"""Fixer for StandardError -> Exception."""

# Local imports
from .. import fixer_base
from ..fixer_util import Name


class FixStandarderror(fixer_base.BaseFix):
    BM_compatible = True
    PATTERN = """
              'StandardError'
              """

    def transform(self, node, results):
        return Name("Exception", prefix=node.prefix)
PK       ! N2E      fix_xreadlines.pynu [        """Fix "for x in f.xreadlines()" -> "for x in f".

This fixer will also convert g(f.xreadlines) into g(f.__iter__)."""
# Author: Collin Winter

# Local imports
from .. import fixer_base
from ..fixer_util import Name


class FixXreadlines(fixer_base.BaseFix):
    BM_compatible = True
    PATTERN = """
    power< call=any+ trailer< '.' 'xreadlines' > trailer< '(' ')' > >
    |
    power< any+ trailer< '.' no_call='xreadlines' > >
    """

    def transform(self, node, results):
        no_call = results.get("no_call")

        if no_call:
            no_call.replace(Name("__iter__", prefix=no_call.prefix))
        else:
            node.replace([x.clone() for x in results["call"]])
PK       ! HgH  H    fix_isinstance.pynu [        # Copyright 2008 Armin Ronacher.
# Licensed to PSF under a Contributor Agreement.

"""Fixer that cleans up a tuple argument to isinstance after the tokens
in it were fixed.  This is mainly used to remove double occurrences of
tokens as a leftover of the long -> int / unicode -> str conversion.

eg.  isinstance(x, (int, long)) -> isinstance(x, (int, int))
       -> isinstance(x, int)
"""

from .. import fixer_base
from ..fixer_util import token


class FixIsinstance(fixer_base.BaseFix):
    BM_compatible = True
    PATTERN = """
    power<
        'isinstance'
        trailer< '(' arglist< any ',' atom< '('
            args=testlist_gexp< any+ >
        ')' > > ')' >
    >
    """

    run_order = 6

    def transform(self, node, results):
        names_inserted = set()
        testlist = results["args"]
        args = testlist.children
        new_args = []
        iterator = enumerate(args)
        for idx, arg in iterator:
            if arg.type == token.NAME and arg.value in names_inserted:
                if idx < len(args) - 1 and args[idx + 1].type == token.COMMA:
                    next(iterator)
                    continue
            else:
                new_args.append(arg)
                if arg.type == token.NAME:
                    names_inserted.add(arg.value)
        if new_args and new_args[-1].type == token.COMMA:
            del new_args[-1]
        if len(new_args) == 1:
            atom = testlist.parent
            new_args[0].prefix = atom.prefix
            atom.replace(new_args[0])
        else:
            args[:] = new_args
            node.changed()
PK       ! I
  
    fix_sys_exc.pynu [        """Fixer for sys.exc_{type, value, traceback}

sys.exc_type -> sys.exc_info()[0]
sys.exc_value -> sys.exc_info()[1]
sys.exc_traceback -> sys.exc_info()[2]
"""

# By Jeff Balogh and Benjamin Peterson

# Local imports
from .. import fixer_base
from ..fixer_util import Attr, Call, Name, Number, Subscript, Node, syms

class FixSysExc(fixer_base.BaseFix):
    # This order matches the ordering of sys.exc_info().
    exc_info = ["exc_type", "exc_value", "exc_traceback"]
    BM_compatible = True
    PATTERN = """
              power< 'sys' trailer< dot='.' attribute=(%s) > >
              """ % '|'.join("'%s'" % e for e in exc_info)

    def transform(self, node, results):
        sys_attr = results["attribute"][0]
        index = Number(self.exc_info.index(sys_attr.value))

        call = Call(Name("exc_info"), prefix=sys_attr.prefix)
        attr = Attr(Name("sys"), call)
        attr[1].children[0].prefix = results["dot"].prefix
        attr.append(Subscript(index))
        return Node(syms.power, attr, prefix=node.prefix)
PK       ! ?O  O    fix_nonzero.pynu [        """Fixer for __nonzero__ -> __bool__ methods."""
# Author: Collin Winter

# Local imports
from .. import fixer_base
from ..fixer_util import Name

class FixNonzero(fixer_base.BaseFix):
    BM_compatible = True
    PATTERN = """
    classdef< 'class' any+ ':'
              suite< any*
                     funcdef< 'def' name='__nonzero__'
                              parameters< '(' NAME ')' > any+ >
                     any* > >
    """

    def transform(self, node, results):
        name = results["name"]
        new = Name("__bool__", prefix=name.prefix)
        name.replace(new)
PK       ! )x  x    fix_intern.pynu [        # Copyright 2006 Georg Brandl.
# Licensed to PSF under a Contributor Agreement.

"""Fixer for intern().

intern(s) -> sys.intern(s)"""

# Local imports
from .. import fixer_base
from ..fixer_util import ImportAndCall, touch_import


class FixIntern(fixer_base.BaseFix):
    BM_compatible = True
    order = "pre"

    PATTERN = """
    power< 'intern'
           trailer< lpar='('
                    ( not(arglist | argument<any '=' any>) obj=any
                      | obj=arglist<(not argument<any '=' any>) any ','> )
                    rpar=')' >
           after=any*
    >
    """

    def transform(self, node, results):
        if results:
            # I feel like we should be able to express this logic in the
            # PATTERN above but I don't know how to do it so...
            obj = results['obj']
            if obj:
                if (obj.type == self.syms.argument and
                    obj.children[0].value in {'**', '*'}):
                    return  # Make no change.
        names = ('sys', 'intern')
        new = ImportAndCall(node, results, names)
        touch_import(None, 'sys', node)
        return new
PK       ! ds      fix_dict.pynu [        # Copyright 2007 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.

"""Fixer for dict methods.

d.keys() -> list(d.keys())
d.items() -> list(d.items())
d.values() -> list(d.values())

d.iterkeys() -> iter(d.keys())
d.iteritems() -> iter(d.items())
d.itervalues() -> iter(d.values())

d.viewkeys() -> d.keys()
d.viewitems() -> d.items()
d.viewvalues() -> d.values()

Except in certain very specific contexts: the iter() can be dropped
when the context is list(), sorted(), iter() or for...in; the list()
can be dropped when the context is list() or sorted() (but not iter()
or for...in!). Special contexts that apply to both: list(), sorted(), tuple()
set(), any(), all(), sum().

Note: iter(d.keys()) could be written as iter(d) but since the
original d.iterkeys() was also redundant we don't fix this.  And there
are (rare) contexts where it makes a difference (e.g. when passing it
as an argument to a function that introspects the argument).
"""

# Local imports
from .. import pytree
from .. import patcomp
from .. import fixer_base
from ..fixer_util import Name, Call, Dot
from .. import fixer_util


iter_exempt = fixer_util.consuming_calls | {"iter"}


class FixDict(fixer_base.BaseFix):
    BM_compatible = True

    PATTERN = """
    power< head=any+
         trailer< '.' method=('keys'|'items'|'values'|
                              'iterkeys'|'iteritems'|'itervalues'|
                              'viewkeys'|'viewitems'|'viewvalues') >
         parens=trailer< '(' ')' >
         tail=any*
    >
    """

    def transform(self, node, results):
        head = results["head"]
        method = results["method"][0] # Extract node for method name
        tail = results["tail"]
        syms = self.syms
        method_name = method.value
        isiter = method_name.startswith("iter")
        isview = method_name.startswith("view")
        if isiter or isview:
            method_name = method_name[4:]
        assert method_name in ("keys", "items", "values"), repr(method)
        head = [n.clone() for n in head]
        tail = [n.clone() for n in tail]
        special = not tail and self.in_special_context(node, isiter)
        args = head + [pytree.Node(syms.trailer,
                                   [Dot(),
                                    Name(method_name,
                                         prefix=method.prefix)]),
                       results["parens"].clone()]
        new = pytree.Node(syms.power, args)
        if not (special or isview):
            new.prefix = ""
            new = Call(Name("iter" if isiter else "list"), [new])
        if tail:
            new = pytree.Node(syms.power, [new] + tail)
        new.prefix = node.prefix
        return new

    P1 = "power< func=NAME trailer< '(' node=any ')' > any* >"
    p1 = patcomp.compile_pattern(P1)

    P2 = """for_stmt< 'for' any 'in' node=any ':' any* >
            | comp_for< 'for' any 'in' node=any any* >
         """
    p2 = patcomp.compile_pattern(P2)

    def in_special_context(self, node, isiter):
        if node.parent is None:
            return False
        results = {}
        if (node.parent.parent is not None and
               self.p1.match(node.parent.parent, results) and
               results["node"] is node):
            if isiter:
                # iter(d.iterkeys()) -> iter(d.keys()), etc.
                return results["func"].value in iter_exempt
            else:
                # list(d.keys()) -> list(d.keys()), etc.
                return results["func"].value in fixer_util.consuming_calls
        if not isiter:
            return False
        # for ... in d.iterkeys() -> for ... in d.keys(), etc.
        return self.p2.match(node.parent, results) and results["node"] is node
PK       ! 2ۭ      fix_renames.pynu [        """Fix incompatible renames

Fixes:
  * sys.maxint -> sys.maxsize
"""
# Author: Christian Heimes
# based on Collin Winter's fix_import

# Local imports
from .. import fixer_base
from ..fixer_util import Name, attr_chain

MAPPING = {"sys":  {"maxint" : "maxsize"},
          }
LOOKUP = {}

def alternates(members):
    return "(" + "|".join(map(repr, members)) + ")"


def build_pattern():
    #bare = set()
    for module, replace in list(MAPPING.items()):
        for old_attr, new_attr in list(replace.items()):
            LOOKUP[(module, old_attr)] = new_attr
            #bare.add(module)
            #bare.add(old_attr)
            #yield """
            #      import_name< 'import' (module=%r
            #          | dotted_as_names< any* module=%r any* >) >
            #      """ % (module, module)
            yield """
                  import_from< 'from' module_name=%r 'import'
                      ( attr_name=%r | import_as_name< attr_name=%r 'as' any >) >
                  """ % (module, old_attr, old_attr)
            yield """
                  power< module_name=%r trailer< '.' attr_name=%r > any* >
                  """ % (module, old_attr)
    #yield """bare_name=%s""" % alternates(bare)


class FixRenames(fixer_base.BaseFix):
    BM_compatible = True
    PATTERN = "|".join(build_pattern())

    order = "pre" # Pre-order tree traversal

    # Don't match the node if it's within another match
    def match(self, node):
        match = super(FixRenames, self).match
        results = match(node)
        if results:
            if any(match(obj) for obj in attr_chain(node, "parent")):
                return False
            return results
        return False

    #def start_tree(self, tree, filename):
    #    super(FixRenames, self).start_tree(tree, filename)
    #    self.replace = {}

    def transform(self, node, results):
        mod_name = results.get("module_name")
        attr_name = results.get("attr_name")
        #bare_name = results.get("bare_name")
        #import_mod = results.get("module")

        if mod_name and attr_name:
            new_attr = LOOKUP[(mod_name.value, attr_name.value)]
            attr_name.replace(Name(new_attr, prefix=attr_name.prefix))
PK       ! :      fix_exec.pynu [        # Copyright 2006 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.

"""Fixer for exec.

This converts usages of the exec statement into calls to a built-in
exec() function.

exec code in ns1, ns2 -> exec(code, ns1, ns2)
"""

# Local imports
from .. import fixer_base
from ..fixer_util import Comma, Name, Call


class FixExec(fixer_base.BaseFix):
    BM_compatible = True

    PATTERN = """
    exec_stmt< 'exec' a=any 'in' b=any [',' c=any] >
    |
    exec_stmt< 'exec' (not atom<'(' [any] ')'>) a=any >
    """

    def transform(self, node, results):
        assert results
        syms = self.syms
        a = results["a"]
        b = results.get("b")
        c = results.get("c")
        args = [a.clone()]
        args[0].prefix = ""
        if b is not None:
            args.extend([Comma(), b.clone()])
        if c is not None:
            args.extend([Comma(), c.clone()])

        return Call(Name("exec"), args, prefix=node.prefix)
PK       ! )E  E    fix_reduce.pynu [        # Copyright 2008 Armin Ronacher.
# Licensed to PSF under a Contributor Agreement.

"""Fixer for reduce().

Makes sure reduce() is imported from the functools module if reduce is
used in that module.
"""

from lib2to3 import fixer_base
from lib2to3.fixer_util import touch_import



class FixReduce(fixer_base.BaseFix):

    BM_compatible = True
    order = "pre"

    PATTERN = """
    power< 'reduce'
        trailer< '('
            arglist< (
                (not(argument<any '=' any>) any ','
                 not(argument<any '=' any>) any) |
                (not(argument<any '=' any>) any ','
                 not(argument<any '=' any>) any ','
                 not(argument<any '=' any>) any)
            ) >
        ')' >
    >
    """

    def transform(self, node, results):
        touch_import('functools', 'reduce', node)
PK       ! _ \      fix_idioms.pynu [        """Adjust some old Python 2 idioms to their modern counterparts.

* Change some type comparisons to isinstance() calls:
    type(x) == T -> isinstance(x, T)
    type(x) is T -> isinstance(x, T)
    type(x) != T -> not isinstance(x, T)
    type(x) is not T -> not isinstance(x, T)

* Change "while 1:" into "while True:".

* Change both

    v = list(EXPR)
    v.sort()
    foo(v)

and the more general

    v = EXPR
    v.sort()
    foo(v)

into

    v = sorted(EXPR)
    foo(v)
"""
# Author: Jacques Frechet, Collin Winter

# Local imports
from .. import fixer_base
from ..fixer_util import Call, Comma, Name, Node, BlankLine, syms

CMP = "(n='!=' | '==' | 'is' | n=comp_op< 'is' 'not' >)"
TYPE = "power< 'type' trailer< '(' x=any ')' > >"

class FixIdioms(fixer_base.BaseFix):
    explicit = True # The user must ask for this fixer

    PATTERN = r"""
        isinstance=comparison< %s %s T=any >
        |
        isinstance=comparison< T=any %s %s >
        |
        while_stmt< 'while' while='1' ':' any+ >
        |
        sorted=any<
            any*
            simple_stmt<
              expr_stmt< id1=any '='
                         power< list='list' trailer< '(' (not arglist<any+>) any ')' > >
              >
              '\n'
            >
            sort=
            simple_stmt<
              power< id2=any
                     trailer< '.' 'sort' > trailer< '(' ')' >
              >
              '\n'
            >
            next=any*
        >
        |
        sorted=any<
            any*
            simple_stmt< expr_stmt< id1=any '=' expr=any > '\n' >
            sort=
            simple_stmt<
              power< id2=any
                     trailer< '.' 'sort' > trailer< '(' ')' >
              >
              '\n'
            >
            next=any*
        >
    """ % (TYPE, CMP, CMP, TYPE)

    def match(self, node):
        r = super(FixIdioms, self).match(node)
        # If we've matched one of the sort/sorted subpatterns above, we
        # want to reject matches where the initial assignment and the
        # subsequent .sort() call involve different identifiers.
        if r and "sorted" in r:
            if r["id1"] == r["id2"]:
                return r
            return None
        return r

    def transform(self, node, results):
        if "isinstance" in results:
            return self.transform_isinstance(node, results)
        elif "while" in results:
            return self.transform_while(node, results)
        elif "sorted" in results:
            return self.transform_sort(node, results)
        else:
            raise RuntimeError("Invalid match")

    def transform_isinstance(self, node, results):
        x = results["x"].clone() # The thing inside of type()
        T = results["T"].clone() # The type being compared against
        x.prefix = ""
        T.prefix = " "
        test = Call(Name("isinstance"), [x, Comma(), T])
        if "n" in results:
            test.prefix = " "
            test = Node(syms.not_test, [Name("not"), test])
        test.prefix = node.prefix
        return test

    def transform_while(self, node, results):
        one = results["while"]
        one.replace(Name("True", prefix=one.prefix))

    def transform_sort(self, node, results):
        sort_stmt = results["sort"]
        next_stmt = results["next"]
        list_call = results.get("list")
        simple_expr = results.get("expr")

        if list_call:
            list_call.replace(Name("sorted", prefix=list_call.prefix))
        elif simple_expr:
            new = simple_expr.clone()
            new.prefix = ""
            simple_expr.replace(Call(Name("sorted"), [new],
                                     prefix=simple_expr.prefix))
        else:
            raise RuntimeError("should not have reached here")
        sort_stmt.remove()

        btwn = sort_stmt.prefix
        # Keep any prefix lines between the sort_stmt and the list_call and
        # shove them right after the sorted() call.
        if "\n" in btwn:
            if next_stmt:
                # The new prefix should be everything from the sort_stmt's
                # prefix up to the last newline, then the old prefix after a new
                # line.
                prefix_lines = (btwn.rpartition("\n")[0], next_stmt[0].prefix)
                next_stmt[0].prefix = "\n".join(prefix_lines)
            else:
                assert list_call.parent
                assert list_call.next_sibling is None
                # Put a blank line after list_call and set its prefix.
                end_line = BlankLine()
                list_call.parent.append_child(end_line)
                assert list_call.next_sibling is end_line
                # The new prefix should be everything up to the first new line
                # of sort_stmt's prefix.
                end_line.prefix = btwn.rpartition("\n")[0]
PK       ! &      fix_unicode.pynu [        r"""Fixer for unicode.

* Changes unicode to str and unichr to chr.

* If "...\u..." is not unicode literal change it into "...\\u...".

* Change u"..." into "...".

"""

from ..pgen2 import token
from .. import fixer_base

_mapping = {"unichr" : "chr", "unicode" : "str"}

class FixUnicode(fixer_base.BaseFix):
    BM_compatible = True
    PATTERN = "STRING | 'unicode' | 'unichr'"

    def start_tree(self, tree, filename):
        super(FixUnicode, self).start_tree(tree, filename)
        self.unicode_literals = 'unicode_literals' in tree.future_features

    def transform(self, node, results):
        if node.type == token.NAME:
            new = node.clone()
            new.value = _mapping[node.value]
            return new
        elif node.type == token.STRING:
            val = node.value
            if not self.unicode_literals and val[0] in '\'"' and '\\' in val:
                val = r'\\'.join([
                    v.replace('\\u', r'\\u').replace('\\U', r'\\U')
                    for v in val.split(r'\\')
                ])
            if val[0] in 'uU':
                val = val[1:]
            if val == node.value:
                return node
            new = node.clone()
            new.value = val
            return new
PK       ! IkNf  f    fix_next.pynu [        """Fixer for it.next() -> next(it), per PEP 3114."""
# Author: Collin Winter

# Things that currently aren't covered:
#   - listcomp "next" names aren't warned
#   - "with" statement targets aren't checked

# Local imports
from ..pgen2 import token
from ..pygram import python_symbols as syms
from .. import fixer_base
from ..fixer_util import Name, Call, find_binding

bind_warning = "Calls to builtin next() possibly shadowed by global binding"


class FixNext(fixer_base.BaseFix):
    BM_compatible = True
    PATTERN = """
    power< base=any+ trailer< '.' attr='next' > trailer< '(' ')' > >
    |
    power< head=any+ trailer< '.' attr='next' > not trailer< '(' ')' > >
    |
    classdef< 'class' any+ ':'
              suite< any*
                     funcdef< 'def'
                              name='next'
                              parameters< '(' NAME ')' > any+ >
                     any* > >
    |
    global=global_stmt< 'global' any* 'next' any* >
    """

    order = "pre" # Pre-order tree traversal

    def start_tree(self, tree, filename):
        super(FixNext, self).start_tree(tree, filename)

        n = find_binding('next', tree)
        if n:
            self.warning(n, bind_warning)
            self.shadowed_next = True
        else:
            self.shadowed_next = False

    def transform(self, node, results):
        assert results

        base = results.get("base")
        attr = results.get("attr")
        name = results.get("name")

        if base:
            if self.shadowed_next:
                attr.replace(Name("__next__", prefix=attr.prefix))
            else:
                base = [n.clone() for n in base]
                base[0].prefix = ""
                node.replace(Call(Name("next", prefix=node.prefix), base))
        elif name:
            n = Name("__next__", prefix=name.prefix)
            name.replace(n)
        elif attr:
            # We don't do this transformation if we're assigning to "x.next".
            # Unfortunately, it doesn't seem possible to do this in PATTERN,
            #  so it's being done here.
            if is_assign_target(node):
                head = results["head"]
                if "".join([str(n) for n in head]).strip() == '__builtin__':
                    self.warning(node, bind_warning)
                return
            attr.replace(Name("__next__"))
        elif "global" in results:
            self.warning(node, bind_warning)
            self.shadowed_next = True


### The following functions help test if node is part of an assignment
###  target.

def is_assign_target(node):
    assign = find_assign(node)
    if assign is None:
        return False

    for child in assign.children:
        if child.type == token.EQUAL:
            return False
        elif is_subtree(child, node):
            return True
    return False

def find_assign(node):
    if node.type == syms.expr_stmt:
        return node
    if node.type == syms.simple_stmt or node.parent is None:
        return None
    return find_assign(node.parent)

def is_subtree(root, node):
    if root == node:
        return True
    return any(is_subtree(c, node) for c in root.children)
PK       ! >ӵ;&  &    fix_itertools_imports.pynu [        """ Fixer for imports of itertools.(imap|ifilter|izip|ifilterfalse) """

# Local imports
from lib2to3 import fixer_base
from lib2to3.fixer_util import BlankLine, syms, token


class FixItertoolsImports(fixer_base.BaseFix):
    BM_compatible = True
    PATTERN = """
              import_from< 'from' 'itertools' 'import' imports=any >
              """ %(locals())

    def transform(self, node, results):
        imports = results['imports']
        if imports.type == syms.import_as_name or not imports.children:
            children = [imports]
        else:
            children = imports.children
        for child in children[::2]:
            if child.type == token.NAME:
                member = child.value
                name_node = child
            elif child.type == token.STAR:
                # Just leave the import as is.
                return
            else:
                assert child.type == syms.import_as_name
                name_node = child.children[0]
            member_name = name_node.value
            if member_name in ('imap', 'izip', 'ifilter'):
                child.value = None
                child.remove()
            elif member_name in ('ifilterfalse', 'izip_longest'):
                node.changed()
                name_node.value = ('filterfalse' if member_name[1] == 'f'
                                   else 'zip_longest')

        # Make sure the import statement is still sane
        children = imports.children[:] or [imports]
        remove_comma = True
        for child in children:
            if remove_comma and child.type == token.COMMA:
                child.remove()
            else:
                remove_comma ^= True

        while children and children[-1].type == token.COMMA:
            children.pop().remove()

        # If there are no imports left, just get rid of the entire statement
        if (not (imports.children or getattr(imports, 'value', None)) or
            imports.parent is None):
            p = node.prefix
            node = BlankLine()
            node.prefix = p
            return node
PK       ! +&^  ^    fix_methodattrs.pynu [        """Fix bound method attributes (method.im_? -> method.__?__).
"""
# Author: Christian Heimes

# Local imports
from .. import fixer_base
from ..fixer_util import Name

MAP = {
    "im_func" : "__func__",
    "im_self" : "__self__",
    "im_class" : "__self__.__class__"
    }

class FixMethodattrs(fixer_base.BaseFix):
    BM_compatible = True
    PATTERN = """
    power< any+ trailer< '.' attr=('im_func' | 'im_self' | 'im_class') > any* >
    """

    def transform(self, node, results):
        attr = results["attr"][0]
        new = MAP[attr.value]
        attr.replace(Name(new, prefix=attr.prefix))
PK       ! Gg      fix_itertools.pynu [        """ Fixer for itertools.(imap|ifilter|izip) --> (map|filter|zip) and
    itertools.ifilterfalse --> itertools.filterfalse (bugs 2360-2363)

    imports from itertools are fixed in fix_itertools_import.py

    If itertools is imported as something else (ie: import itertools as it;
    it.izip(spam, eggs)) method calls will not get fixed.
    """

# Local imports
from .. import fixer_base
from ..fixer_util import Name

class FixItertools(fixer_base.BaseFix):
    BM_compatible = True
    it_funcs = "('imap'|'ifilter'|'izip'|'izip_longest'|'ifilterfalse')"
    PATTERN = """
              power< it='itertools'
                  trailer<
                     dot='.' func=%(it_funcs)s > trailer< '(' [any] ')' > >
              |
              power< func=%(it_funcs)s trailer< '(' [any] ')' > >
              """ %(locals())

    # Needs to be run after fix_(map|zip|filter)
    run_order = 6

    def transform(self, node, results):
        prefix = None
        func = results['func'][0]
        if ('it' in results and
            func.value not in ('ifilterfalse', 'izip_longest')):
            dot, it = (results['dot'], results['it'])
            # Remove the 'itertools'
            prefix = it.prefix
            it.remove()
            # Replace the node which contains ('.', 'function') with the
            # function (to be consistent with the second part of the pattern)
            dot.remove()
            func.parent.replace(func)

        prefix = prefix or func.prefix
        func.replace(Name(func.value[1:], prefix=prefix))
PK       ! 6u      fix_raw_input.pynu [        """Fixer that changes raw_input(...) into input(...)."""
# Author: Andre Roberge

# Local imports
from .. import fixer_base
from ..fixer_util import Name

class FixRawInput(fixer_base.BaseFix):

    BM_compatible = True
    PATTERN = """
              power< name='raw_input' trailer< '(' [any] ')' > any* >
              """

    def transform(self, node, results):
        name = results["name"]
        name.replace(Name("input", prefix=name.prefix))
PK       ! Y        fix_metaclass.pynu [        """Fixer for __metaclass__ = X -> (metaclass=X) methods.

   The various forms of classef (inherits nothing, inherits once, inherits
   many) don't parse the same in the CST so we look at ALL classes for
   a __metaclass__ and if we find one normalize the inherits to all be
   an arglist.

   For one-liner classes ('class X: pass') there is no indent/dedent so
   we normalize those into having a suite.

   Moving the __metaclass__ into the classdef can also cause the class
   body to be empty so there is some special casing for that as well.

   This fixer also tries very hard to keep original indenting and spacing
   in all those corner cases.

"""
# Author: Jack Diederich

# Local imports
from .. import fixer_base
from ..pygram import token
from ..fixer_util import syms, Node, Leaf


def has_metaclass(parent):
    """ we have to check the cls_node without changing it.
        There are two possibilities:
          1)  clsdef => suite => simple_stmt => expr_stmt => Leaf('__meta')
          2)  clsdef => simple_stmt => expr_stmt => Leaf('__meta')
    """
    for node in parent.children:
        if node.type == syms.suite:
            return has_metaclass(node)
        elif node.type == syms.simple_stmt and node.children:
            expr_node = node.children[0]
            if expr_node.type == syms.expr_stmt and expr_node.children:
                left_side = expr_node.children[0]
                if isinstance(left_side, Leaf) and \
                        left_side.value == '__metaclass__':
                    return True
    return False


def fixup_parse_tree(cls_node):
    """ one-line classes don't get a suite in the parse tree so we add
        one to normalize the tree
    """
    for node in cls_node.children:
        if node.type == syms.suite:
            # already in the preferred format, do nothing
            return

    # !%@#! one-liners have no suite node, we have to fake one up
    for i, node in enumerate(cls_node.children):
        if node.type == token.COLON:
            break
    else:
        raise ValueError("No class suite and no ':'!")

    # move everything into a suite node
    suite = Node(syms.suite, [])
    while cls_node.children[i+1:]:
        move_node = cls_node.children[i+1]
        suite.append_child(move_node.clone())
        move_node.remove()
    cls_node.append_child(suite)
    node = suite


def fixup_simple_stmt(parent, i, stmt_node):
    """ if there is a semi-colon all the parts count as part of the same
        simple_stmt.  We just want the __metaclass__ part so we move
        everything after the semi-colon into its own simple_stmt node
    """
    for semi_ind, node in enumerate(stmt_node.children):
        if node.type == token.SEMI: # *sigh*
            break
    else:
        return

    node.remove() # kill the semicolon
    new_expr = Node(syms.expr_stmt, [])
    new_stmt = Node(syms.simple_stmt, [new_expr])
    while stmt_node.children[semi_ind:]:
        move_node = stmt_node.children[semi_ind]
        new_expr.append_child(move_node.clone())
        move_node.remove()
    parent.insert_child(i, new_stmt)
    new_leaf1 = new_stmt.children[0].children[0]
    old_leaf1 = stmt_node.children[0].children[0]
    new_leaf1.prefix = old_leaf1.prefix


def remove_trailing_newline(node):
    if node.children and node.children[-1].type == token.NEWLINE:
        node.children[-1].remove()


def find_metas(cls_node):
    # find the suite node (Mmm, sweet nodes)
    for node in cls_node.children:
        if node.type == syms.suite:
            break
    else:
        raise ValueError("No class suite!")

    # look for simple_stmt[ expr_stmt[ Leaf('__metaclass__') ] ]
    for i, simple_node in list(enumerate(node.children)):
        if simple_node.type == syms.simple_stmt and simple_node.children:
            expr_node = simple_node.children[0]
            if expr_node.type == syms.expr_stmt and expr_node.children:
                # Check if the expr_node is a simple assignment.
                left_node = expr_node.children[0]
                if isinstance(left_node, Leaf) and \
                        left_node.value == '__metaclass__':
                    # We found an assignment to __metaclass__.
                    fixup_simple_stmt(node, i, simple_node)
                    remove_trailing_newline(simple_node)
                    yield (node, i, simple_node)


def fixup_indent(suite):
    """ If an INDENT is followed by a thing with a prefix then nuke the prefix
        Otherwise we get in trouble when removing __metaclass__ at suite start
    """
    kids = suite.children[::-1]
    # find the first indent
    while kids:
        node = kids.pop()
        if node.type == token.INDENT:
            break

    # find the first Leaf
    while kids:
        node = kids.pop()
        if isinstance(node, Leaf) and node.type != token.DEDENT:
            if node.prefix:
                node.prefix = ''
            return
        else:
            kids.extend(node.children[::-1])


class FixMetaclass(fixer_base.BaseFix):
    BM_compatible = True

    PATTERN = """
    classdef<any*>
    """

    def transform(self, node, results):
        if not has_metaclass(node):
            return

        fixup_parse_tree(node)

        # find metaclasses, keep the last one
        last_metaclass = None
        for suite, i, stmt in find_metas(node):
            last_metaclass = stmt
            stmt.remove()

        text_type = node.children[0].type # always Leaf(nnn, 'class')

        # figure out what kind of classdef we have
        if len(node.children) == 7:
            # Node(classdef, ['class', 'name', '(', arglist, ')', ':', suite])
            #                 0        1       2    3        4    5    6
            if node.children[3].type == syms.arglist:
                arglist = node.children[3]
            # Node(classdef, ['class', 'name', '(', 'Parent', ')', ':', suite])
            else:
                parent = node.children[3].clone()
                arglist = Node(syms.arglist, [parent])
                node.set_child(3, arglist)
        elif len(node.children) == 6:
            # Node(classdef, ['class', 'name', '(',  ')', ':', suite])
            #                 0        1       2     3    4    5
            arglist = Node(syms.arglist, [])
            node.insert_child(3, arglist)
        elif len(node.children) == 4:
            # Node(classdef, ['class', 'name', ':', suite])
            #                 0        1       2    3
            arglist = Node(syms.arglist, [])
            node.insert_child(2, Leaf(token.RPAR, ')'))
            node.insert_child(2, arglist)
            node.insert_child(2, Leaf(token.LPAR, '('))
        else:
            raise ValueError("Unexpected class definition")

        # now stick the metaclass in the arglist
        meta_txt = last_metaclass.children[0].children[0]
        meta_txt.value = 'metaclass'
        orig_meta_prefix = meta_txt.prefix

        if arglist.children:
            arglist.append_child(Leaf(token.COMMA, ','))
            meta_txt.prefix = ' '
        else:
            meta_txt.prefix = ''

        # compact the expression "metaclass = Meta" -> "metaclass=Meta"
        expr_stmt = last_metaclass.children[0]
        assert expr_stmt.type == syms.expr_stmt
        expr_stmt.children[1].prefix = ''
        expr_stmt.children[2].prefix = ''

        arglist.append_child(last_metaclass)

        fixup_indent(suite)

        # check for empty suite
        if not suite.children:
            # one-liner that was just __metaclass_
            suite.remove()
            pass_leaf = Leaf(text_type, 'pass')
            pass_leaf.prefix = orig_meta_prefix
            node.append_child(pass_leaf)
            node.append_child(Leaf(token.NEWLINE, '\n'))

        elif len(suite.children) > 1 and \
                 (suite.children[-2].type == token.INDENT and
                  suite.children[-1].type == token.DEDENT):
            # there was only one line in the class body and it was __metaclass__
            pass_leaf = Leaf(text_type, 'pass')
            suite.insert_child(-1, pass_leaf)
            suite.insert_child(-1, Leaf(token.NEWLINE, '\n'))
PK       ! F      fix_funcattrs.pynu [        """Fix function attribute names (f.func_x -> f.__x__)."""
# Author: Collin Winter

# Local imports
from .. import fixer_base
from ..fixer_util import Name


class FixFuncattrs(fixer_base.BaseFix):
    BM_compatible = True

    PATTERN = """
    power< any+ trailer< '.' attr=('func_closure' | 'func_doc' | 'func_globals'
                                  | 'func_name' | 'func_defaults' | 'func_code'
                                  | 'func_dict') > any* >
    """

    def transform(self, node, results):
        attr = results["attr"][0]
        attr.replace(Name(("__%s__" % attr.value[5:]),
                          prefix=attr.prefix))
PK       ! p2I      fix_except.pynu [        """Fixer for except statements with named exceptions.

The following cases will be converted:

- "except E, T:" where T is a name:

    except E as T:

- "except E, T:" where T is not a name, tuple or list:

        except E as t:
            T = t

    This is done because the target of an "except" clause must be a
    name.

- "except E, T:" where T is a tuple or list literal:

        except E as t:
            T = t.args
"""
# Author: Collin Winter

# Local imports
from .. import pytree
from ..pgen2 import token
from .. import fixer_base
from ..fixer_util import Assign, Attr, Name, is_tuple, is_list, syms

def find_excepts(nodes):
    for i, n in enumerate(nodes):
        if n.type == syms.except_clause:
            if n.children[0].value == 'except':
                yield (n, nodes[i+2])

class FixExcept(fixer_base.BaseFix):
    BM_compatible = True

    PATTERN = """
    try_stmt< 'try' ':' (simple_stmt | suite)
                  cleanup=(except_clause ':' (simple_stmt | suite))+
                  tail=(['except' ':' (simple_stmt | suite)]
                        ['else' ':' (simple_stmt | suite)]
                        ['finally' ':' (simple_stmt | suite)]) >
    """

    def transform(self, node, results):
        syms = self.syms

        tail = [n.clone() for n in results["tail"]]

        try_cleanup = [ch.clone() for ch in results["cleanup"]]
        for except_clause, e_suite in find_excepts(try_cleanup):
            if len(except_clause.children) == 4:
                (E, comma, N) = except_clause.children[1:4]
                comma.replace(Name("as", prefix=" "))

                if N.type != token.NAME:
                    # Generate a new N for the except clause
                    new_N = Name(self.new_name(), prefix=" ")
                    target = N.clone()
                    target.prefix = ""
                    N.replace(new_N)
                    new_N = new_N.clone()

                    # Insert "old_N = new_N" as the first statement in
                    #  the except body. This loop skips leading whitespace
                    #  and indents
                    #TODO(cwinter) suite-cleanup
                    suite_stmts = e_suite.children
                    for i, stmt in enumerate(suite_stmts):
                        if isinstance(stmt, pytree.Node):
                            break

                    # The assignment is different if old_N is a tuple or list
                    # In that case, the assignment is old_N = new_N.args
                    if is_tuple(N) or is_list(N):
                        assign = Assign(target, Attr(new_N, Name('args')))
                    else:
                        assign = Assign(target, new_N)

                    #TODO(cwinter) stopgap until children becomes a smart list
                    for child in reversed(suite_stmts[:i]):
                        e_suite.insert_child(0, child)
                    e_suite.insert_child(i, assign)
                elif N.prefix == "":
                    # No space after a comma is legal; no space after "as",
                    # not so much.
                    N.prefix = " "

        #TODO(cwinter) fix this when children becomes a smart list
        children = [c.clone() for c in node.children[:3]] + try_cleanup + tail
        return pytree.Node(node.type, children)
PK       ! 7h#  #    fix_future.pynu [        """Remove __future__ imports

from __future__ import foo is replaced with an empty line.
"""
# Author: Christian Heimes

# Local imports
from .. import fixer_base
from ..fixer_util import BlankLine

class FixFuture(fixer_base.BaseFix):
    BM_compatible = True

    PATTERN = """import_from< 'from' module_name="__future__" 'import' any >"""

    # This should be run last -- some things check for the import
    run_order = 10

    def transform(self, node, results):
        new = BlankLine()
        new.prefix = node.prefix
        return new
PK       ! |4  4    fix_imports.pynu [        """Fix incompatible imports and module references."""
# Authors: Collin Winter, Nick Edds

# Local imports
from .. import fixer_base
from ..fixer_util import Name, attr_chain

MAPPING = {'StringIO':  'io',
           'cStringIO': 'io',
           'cPickle': 'pickle',
           '__builtin__' : 'builtins',
           'copy_reg': 'copyreg',
           'Queue': 'queue',
           'SocketServer': 'socketserver',
           'ConfigParser': 'configparser',
           'repr': 'reprlib',
           'FileDialog': 'tkinter.filedialog',
           'tkFileDialog': 'tkinter.filedialog',
           'SimpleDialog': 'tkinter.simpledialog',
           'tkSimpleDialog': 'tkinter.simpledialog',
           'tkColorChooser': 'tkinter.colorchooser',
           'tkCommonDialog': 'tkinter.commondialog',
           'Dialog': 'tkinter.dialog',
           'Tkdnd': 'tkinter.dnd',
           'tkFont': 'tkinter.font',
           'tkMessageBox': 'tkinter.messagebox',
           'ScrolledText': 'tkinter.scrolledtext',
           'Tkconstants': 'tkinter.constants',
           'Tix': 'tkinter.tix',
           'ttk': 'tkinter.ttk',
           'Tkinter': 'tkinter',
           'markupbase': '_markupbase',
           '_winreg': 'winreg',
           'thread': '_thread',
           'dummy_thread': '_dummy_thread',
           # anydbm and whichdb are handled by fix_imports2
           'dbhash': 'dbm.bsd',
           'dumbdbm': 'dbm.dumb',
           'dbm': 'dbm.ndbm',
           'gdbm': 'dbm.gnu',
           'xmlrpclib': 'xmlrpc.client',
           'DocXMLRPCServer': 'xmlrpc.server',
           'SimpleXMLRPCServer': 'xmlrpc.server',
           'httplib': 'http.client',
           'htmlentitydefs' : 'html.entities',
           'HTMLParser' : 'html.parser',
           'Cookie': 'http.cookies',
           'cookielib': 'http.cookiejar',
           'BaseHTTPServer': 'http.server',
           'SimpleHTTPServer': 'http.server',
           'CGIHTTPServer': 'http.server',
           #'test.test_support': 'test.support',
           'commands': 'subprocess',
           'UserString' : 'collections',
           'UserList' : 'collections',
           'urlparse' : 'urllib.parse',
           'robotparser' : 'urllib.robotparser',
}


def alternates(members):
    return "(" + "|".join(map(repr, members)) + ")"


def build_pattern(mapping=MAPPING):
    mod_list = ' | '.join(["module_name='%s'" % key for key in mapping])
    bare_names = alternates(mapping.keys())

    yield """name_import=import_name< 'import' ((%s) |
               multiple_imports=dotted_as_names< any* (%s) any* >) >
          """ % (mod_list, mod_list)
    yield """import_from< 'from' (%s) 'import' ['(']
              ( any | import_as_name< any 'as' any > |
                import_as_names< any* >)  [')'] >
          """ % mod_list
    yield """import_name< 'import' (dotted_as_name< (%s) 'as' any > |
               multiple_imports=dotted_as_names<
                 any* dotted_as_name< (%s) 'as' any > any* >) >
          """ % (mod_list, mod_list)

    # Find usages of module members in code e.g. thread.foo(bar)
    yield "power< bare_with_attr=(%s) trailer<'.' any > any* >" % bare_names


class FixImports(fixer_base.BaseFix):

    BM_compatible = True
    keep_line_order = True
    # This is overridden in fix_imports2.
    mapping = MAPPING

    # We want to run this fixer late, so fix_import doesn't try to make stdlib
    # renames into relative imports.
    run_order = 6

    def build_pattern(self):
        return "|".join(build_pattern(self.mapping))

    def compile_pattern(self):
        # We override this, so MAPPING can be pragmatically altered and the
        # changes will be reflected in PATTERN.
        self.PATTERN = self.build_pattern()
        super(FixImports, self).compile_pattern()

    # Don't match the node if it's within another match.
    def match(self, node):
        match = super(FixImports, self).match
        results = match(node)
        if results:
            # Module usage could be in the trailer of an attribute lookup, so we
            # might have nested matches when "bare_with_attr" is present.
            if "bare_with_attr" not in results and \
                    any(match(obj) for obj in attr_chain(node, "parent")):
                return False
            return results
        return False

    def start_tree(self, tree, filename):
        super(FixImports, self).start_tree(tree, filename)
        self.replace = {}

    def transform(self, node, results):
        import_mod = results.get("module_name")
        if import_mod:
            mod_name = import_mod.value
            new_name = self.mapping[mod_name]
            import_mod.replace(Name(new_name, prefix=import_mod.prefix))
            if "name_import" in results:
                # If it's not a "from x import x, y" or "import x as y" import,
                # marked its usage to be replaced.
                self.replace[mod_name] = new_name
            if "multiple_imports" in results:
                # This is a nasty hack to fix multiple imports on a line (e.g.,
                # "import StringIO, urlparse"). The problem is that I can't
                # figure out an easy way to make a pattern recognize the keys of
                # MAPPING randomly sprinkled in an import statement.
                results = self.match(node)
                if results:
                    self.transform(node, results)
        else:
            # Replace usage of the module.
            bare_name = results["bare_with_attr"][0]
            new_name = self.replace.get(bare_name.value)
            if new_name:
                bare_name.replace(Name(new_name, prefix=bare_name.prefix))
PK       !  2Ϳ	  	    fix_exitfunc.pynu [        """
Convert use of sys.exitfunc to use the atexit module.
"""

# Author: Benjamin Peterson

from lib2to3 import pytree, fixer_base
from lib2to3.fixer_util import Name, Attr, Call, Comma, Newline, syms


class FixExitfunc(fixer_base.BaseFix):
    keep_line_order = True
    BM_compatible = True

    PATTERN = """
              (
                  sys_import=import_name<'import'
                      ('sys'
                      |
                      dotted_as_names< (any ',')* 'sys' (',' any)* >
                      )
                  >
              |
                  expr_stmt<
                      power< 'sys' trailer< '.' 'exitfunc' > >
                  '=' func=any >
              )
              """

    def __init__(self, *args):
        super(FixExitfunc, self).__init__(*args)

    def start_tree(self, tree, filename):
        super(FixExitfunc, self).start_tree(tree, filename)
        self.sys_import = None

    def transform(self, node, results):
        # First, find the sys import. We'll just hope it's global scope.
        if "sys_import" in results:
            if self.sys_import is None:
                self.sys_import = results["sys_import"]
            return

        func = results["func"].clone()
        func.prefix = ""
        register = pytree.Node(syms.power,
                               Attr(Name("atexit"), Name("register"))
                               )
        call = Call(register, [func], node.prefix)
        node.replace(call)

        if self.sys_import is None:
            # That's interesting.
            self.warning(node, "Can't find sys import; Please add an atexit "
                             "import at the top of your file.")
            return

        # Now add an atexit import after the sys import.
        names = self.sys_import.children[1]
        if names.type == syms.dotted_as_names:
            names.append_child(Comma())
            names.append_child(Name("atexit", " "))
        else:
            containing_stmt = self.sys_import.parent
            position = containing_stmt.children.index(self.sys_import)
            stmt_container = containing_stmt.parent
            new_import = pytree.Node(syms.import_name,
                              [Name("import"), Name("atexit", " ")]
                              )
            new = pytree.Node(syms.simple_stmt, [new_import])
            containing_stmt.insert_child(position + 1, Newline())
            containing_stmt.insert_child(position + 2, new)
PK       ! JbB  B    fix_ws_comma.pynu [        """Fixer that changes 'a ,b' into 'a, b'.

This also changes '{a :b}' into '{a: b}', but does not touch other
uses of colons.  It does not touch other uses of whitespace.

"""

from .. import pytree
from ..pgen2 import token
from .. import fixer_base

class FixWsComma(fixer_base.BaseFix):

    explicit = True # The user must ask for this fixers

    PATTERN = """
    any<(not(',') any)+ ',' ((not(',') any)+ ',')* [not(',') any]>
    """

    COMMA = pytree.Leaf(token.COMMA, ",")
    COLON = pytree.Leaf(token.COLON, ":")
    SEPS = (COMMA, COLON)

    def transform(self, node, results):
        new = node.clone()
        comma = False
        for child in new.children:
            if child in self.SEPS:
                prefix = child.prefix
                if prefix.isspace() and "\n" not in prefix:
                    child.prefix = ""
                comma = True
            else:
                if comma:
                    prefix = child.prefix
                    if not prefix:
                        child.prefix = " "
                comma = False
        return new
PK       ! M1	  	  
  fix_zip.pynu [        """
Fixer that changes zip(seq0, seq1, ...) into list(zip(seq0, seq1, ...)
unless there exists a 'from future_builtins import zip' statement in the
top-level namespace.

We avoid the transformation if the zip() call is directly contained in
iter(<>), list(<>), tuple(<>), sorted(<>), ...join(<>), or for V in <>:.
"""

# Local imports
from .. import fixer_base
from ..pytree import Node
from ..pygram import python_symbols as syms
from ..fixer_util import Name, ArgList, in_special_context


class FixZip(fixer_base.ConditionalFix):

    BM_compatible = True
    PATTERN = """
    power< 'zip' args=trailer< '(' [any] ')' > [trailers=trailer*]
    >
    """

    skip_on = "future_builtins.zip"

    def transform(self, node, results):
        if self.should_skip(node):
            return

        if in_special_context(node):
            return None

        args = results['args'].clone()
        args.prefix = ""

        trailers = []
        if 'trailers' in results:
            trailers = [n.clone() for n in results['trailers']]
            for n in trailers:
                n.prefix = ""

        new = Node(syms.power, [Name("zip"), args], prefix="")
        new = Node(syms.power, [Name("list"), ArgList([new])] + trailers)
        new.prefix = node.prefix
        return new
PK       ! E[/   /     __init__.pynu [        # Dummy file to make this directory a package.
PK       ! DIu|  |    fix_has_key.pynu [        # Copyright 2006 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.

"""Fixer for has_key().

Calls to .has_key() methods are expressed in terms of the 'in'
operator:

    d.has_key(k) -> k in d

CAVEATS:
1) While the primary target of this fixer is dict.has_key(), the
   fixer will change any has_key() method call, regardless of its
   class.

2) Cases like this will not be converted:

    m = d.has_key
    if m(k):
        ...

   Only *calls* to has_key() are converted. While it is possible to
   convert the above to something like

    m = d.__contains__
    if m(k):
        ...

   this is currently not done.
"""

# Local imports
from .. import pytree
from .. import fixer_base
from ..fixer_util import Name, parenthesize


class FixHasKey(fixer_base.BaseFix):
    BM_compatible = True

    PATTERN = """
    anchor=power<
        before=any+
        trailer< '.' 'has_key' >
        trailer<
            '('
            ( not(arglist | argument<any '=' any>) arg=any
            | arglist<(not argument<any '=' any>) arg=any ','>
            )
            ')'
        >
        after=any*
    >
    |
    negation=not_test<
        'not'
        anchor=power<
            before=any+
            trailer< '.' 'has_key' >
            trailer<
                '('
                ( not(arglist | argument<any '=' any>) arg=any
                | arglist<(not argument<any '=' any>) arg=any ','>
                )
                ')'
            >
        >
    >
    """

    def transform(self, node, results):
        assert results
        syms = self.syms
        if (node.parent.type == syms.not_test and
            self.pattern.match(node.parent)):
            # Don't transform a node matching the first alternative of the
            # pattern when its parent matches the second alternative
            return None
        negation = results.get("negation")
        anchor = results["anchor"]
        prefix = node.prefix
        before = [n.clone() for n in results["before"]]
        arg = results["arg"].clone()
        after = results.get("after")
        if after:
            after = [n.clone() for n in after]
        if arg.type in (syms.comparison, syms.not_test, syms.and_test,
                        syms.or_test, syms.test, syms.lambdef, syms.argument):
            arg = parenthesize(arg)
        if len(before) == 1:
            before = before[0]
        else:
            before = pytree.Node(syms.power, before)
        before.prefix = " "
        n_op = Name("in", prefix=" ")
        if negation:
            n_not = Name("not", prefix=" ")
            n_op = pytree.Node(syms.comp_op, (n_not, n_op))
        new = pytree.Node(syms.comparison, (arg, n_op, before))
        if after:
            new = parenthesize(new)
            new = pytree.Node(syms.power, (new,) + tuple(after))
        if node.parent.type in (syms.comparison, syms.expr, syms.xor_expr,
                                syms.and_expr, syms.shift_expr,
                                syms.arith_expr, syms.term,
                                syms.factor, syms.power):
            new = parenthesize(new)
        new.prefix = prefix
        return new
PK       ! r39  9    fix_reload.pynu [        """Fixer for reload().

reload(s) -> importlib.reload(s)"""

# Local imports
from .. import fixer_base
from ..fixer_util import ImportAndCall, touch_import


class FixReload(fixer_base.BaseFix):
    BM_compatible = True
    order = "pre"

    PATTERN = """
    power< 'reload'
           trailer< lpar='('
                    ( not(arglist | argument<any '=' any>) obj=any
                      | obj=arglist<(not argument<any '=' any>) any ','> )
                    rpar=')' >
           after=any*
    >
    """

    def transform(self, node, results):
        if results:
            # I feel like we should be able to express this logic in the
            # PATTERN above but I don't know how to do it so...
            obj = results['obj']
            if obj:
                if (obj.type == self.syms.argument and
                    obj.children[0].value in {'**', '*'}):
                    return  # Make no change.
        names = ('importlib', 'reload')
        new = ImportAndCall(node, results, names)
        touch_import(None, 'importlib', node)
        return new
PK       ! fϡ      fix_set_literal.pynu [        """
Optional fixer to transform set() calls to set literals.
"""

# Author: Benjamin Peterson

from lib2to3 import fixer_base, pytree
from lib2to3.fixer_util import token, syms



class FixSetLiteral(fixer_base.BaseFix):

    BM_compatible = True
    explicit = True

    PATTERN = """power< 'set' trailer< '('
                     (atom=atom< '[' (items=listmaker< any ((',' any)* [',']) >
                                |
                                single=any) ']' >
                     |
                     atom< '(' items=testlist_gexp< any ((',' any)* [',']) > ')' >
                     )
                     ')' > >
              """

    def transform(self, node, results):
        single = results.get("single")
        if single:
            # Make a fake listmaker
            fake = pytree.Node(syms.listmaker, [single.clone()])
            single.replace(fake)
            items = fake
        else:
            items = results["items"]

        # Build the contents of the literal
        literal = [pytree.Leaf(token.LBRACE, "{")]
        literal.extend(n.clone() for n in items.children)
        literal.append(pytree.Leaf(token.RBRACE, "}"))
        # Set the prefix of the right brace to that of the ')' or ']'
        literal[-1].prefix = items.next_sibling.prefix
        maker = pytree.Node(syms.dictsetmaker, literal)
        maker.prefix = node.prefix

        # If the original was a one tuple, we need to remove the extra comma.
        if len(maker.children) == 4:
            n = maker.children[2]
            n.remove()
            maker.children[-1].prefix = n.prefix

        # Finally, replace the set call with our shiny new literal.
        return maker
PK       ! S      fix_types.pynu [        # Copyright 2007 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.

"""Fixer for removing uses of the types module.

These work for only the known names in the types module.  The forms above
can include types. or not.  ie, It is assumed the module is imported either as:

    import types
    from types import ... # either * or specific types

The import statements are not modified.

There should be another fixer that handles at least the following constants:

   type([]) -> list
   type(()) -> tuple
   type('') -> str

"""

# Local imports
from .. import fixer_base
from ..fixer_util import Name

_TYPE_MAPPING = {
        'BooleanType' : 'bool',
        'BufferType' : 'memoryview',
        'ClassType' : 'type',
        'ComplexType' : 'complex',
        'DictType': 'dict',
        'DictionaryType' : 'dict',
        'EllipsisType' : 'type(Ellipsis)',
        #'FileType' : 'io.IOBase',
        'FloatType': 'float',
        'IntType': 'int',
        'ListType': 'list',
        'LongType': 'int',
        'ObjectType' : 'object',
        'NoneType': 'type(None)',
        'NotImplementedType' : 'type(NotImplemented)',
        'SliceType' : 'slice',
        'StringType': 'bytes', # XXX ?
        'StringTypes' : '(str,)', # XXX ?
        'TupleType': 'tuple',
        'TypeType' : 'type',
        'UnicodeType': 'str',
        'XRangeType' : 'range',
    }

_pats = ["power< 'types' trailer< '.' name='%s' > >" % t for t in _TYPE_MAPPING]

class FixTypes(fixer_base.BaseFix):
    BM_compatible = True
    PATTERN = '|'.join(_pats)

    def transform(self, node, results):
        new_value = _TYPE_MAPPING.get(results["name"].value)
        if new_value:
            return Name(new_value, prefix=node.prefix)
        return None
PK       ! ?k      fix_getcwdu.pynu [        """
Fixer that changes os.getcwdu() to os.getcwd().
"""
# Author: Victor Stinner

# Local imports
from .. import fixer_base
from ..fixer_util import Name

class FixGetcwdu(fixer_base.BaseFix):
    BM_compatible = True

    PATTERN = """
              power< 'os' trailer< dot='.' name='getcwdu' > any* >
              """

    def transform(self, node, results):
        name = results["name"]
        name.replace(Name("getcwd", prefix=name.prefix))
PK       ! lH        fix_numliterals.pynu [        """Fixer that turns 1L into 1, 0755 into 0o755.
"""
# Copyright 2007 Georg Brandl.
# Licensed to PSF under a Contributor Agreement.

# Local imports
from ..pgen2 import token
from .. import fixer_base
from ..fixer_util import Number


class FixNumliterals(fixer_base.BaseFix):
    # This is so simple that we don't need the pattern compiler.

    _accept_type = token.NUMBER

    def match(self, node):
        # Override
        return (node.value.startswith("0") or node.value[-1] in "Ll")

    def transform(self, node, results):
        val = node.value
        if val[-1] in 'Ll':
            val = val[:-1]
        elif val.startswith('0') and val.isdigit() and len(set(val)) > 1:
            val = "0o" + val[1:]

        return Number(val, prefix=node.prefix)
PK       ! {Wk        fix_execfile.pynu [        # Copyright 2006 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.

"""Fixer for execfile.

This converts usages of the execfile function into calls to the built-in
exec() function.
"""

from .. import fixer_base
from ..fixer_util import (Comma, Name, Call, LParen, RParen, Dot, Node,
                          ArgList, String, syms)


class FixExecfile(fixer_base.BaseFix):
    BM_compatible = True

    PATTERN = """
    power< 'execfile' trailer< '(' arglist< filename=any [',' globals=any [',' locals=any ] ] > ')' > >
    |
    power< 'execfile' trailer< '(' filename=any ')' > >
    """

    def transform(self, node, results):
        assert results
        filename = results["filename"]
        globals = results.get("globals")
        locals = results.get("locals")

        # Copy over the prefix from the right parentheses end of the execfile
        # call.
        execfile_paren = node.children[-1].children[-1].clone()
        # Construct open().read().
        open_args = ArgList([filename.clone(), Comma(), String('"rb"', ' ')],
                            rparen=execfile_paren)
        open_call = Node(syms.power, [Name("open"), open_args])
        read = [Node(syms.trailer, [Dot(), Name('read')]),
                Node(syms.trailer, [LParen(), RParen()])]
        open_expr = [open_call] + read
        # Wrap the open call in a compile call. This is so the filename will be
        # preserved in the execed code.
        filename_arg = filename.clone()
        filename_arg.prefix = " "
        exec_str = String("'exec'", " ")
        compile_args = open_expr + [Comma(), filename_arg, Comma(), exec_str]
        compile_call = Call(Name("compile"), compile_args, "")
        # Finally, replace the execfile call with an exec call.
        args = [compile_call]
        if globals is not None:
            args.extend([Comma(), globals.clone()])
        if locals is not None:
            args.extend([Comma(), locals.clone()])
        return Call(Name("exec"), args, prefix=node.prefix)
PK       ! N  N    fix_buffer.pynu [        # Copyright 2007 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.

"""Fixer that changes buffer(...) into memoryview(...)."""

# Local imports
from .. import fixer_base
from ..fixer_util import Name


class FixBuffer(fixer_base.BaseFix):
    BM_compatible = True

    explicit = True # The user must ask for this fixer

    PATTERN = """
              power< name='buffer' trailer< '(' [any] ')' > any* >
              """

    def transform(self, node, results):
        name = results["name"]
        name.replace(Name("memoryview", prefix=name.prefix))
PK       ! a.e  e    fix_repr.pynu [        # Copyright 2006 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.

"""Fixer that transforms `xyzzy` into repr(xyzzy)."""

# Local imports
from .. import fixer_base
from ..fixer_util import Call, Name, parenthesize


class FixRepr(fixer_base.BaseFix):

    BM_compatible = True
    PATTERN = """
              atom < '`' expr=any '`' >
              """

    def transform(self, node, results):
        expr = results["expr"].clone()

        if expr.type == self.syms.testlist1:
            expr = parenthesize(expr)
        return Call(Name("repr"), [expr], prefix=node.prefix)
PK       ! M@  @    fix_basestring.pynu [        """Fixer for basestring -> str."""
# Author: Christian Heimes

# Local imports
from .. import fixer_base
from ..fixer_util import Name

class FixBasestring(fixer_base.BaseFix):
    BM_compatible = True

    PATTERN = "'basestring'"

    def transform(self, node, results):
        return Name("str", prefix=node.prefix)
PK       ! =      fix_asserts.pynu [        """Fixer that replaces deprecated unittest method names."""

# Author: Ezio Melotti

from ..fixer_base import BaseFix
from ..fixer_util import Name

NAMES = dict(
    assert_="assertTrue",
    assertEquals="assertEqual",
    assertNotEquals="assertNotEqual",
    assertAlmostEquals="assertAlmostEqual",
    assertNotAlmostEquals="assertNotAlmostEqual",
    assertRegexpMatches="assertRegex",
    assertRaisesRegexp="assertRaisesRegex",
    failUnlessEqual="assertEqual",
    failIfEqual="assertNotEqual",
    failUnlessAlmostEqual="assertAlmostEqual",
    failIfAlmostEqual="assertNotAlmostEqual",
    failUnless="assertTrue",
    failUnlessRaises="assertRaises",
    failIf="assertFalse",
)


class FixAsserts(BaseFix):

    PATTERN = """
              power< any+ trailer< '.' meth=(%s)> any* >
              """ % '|'.join(map(repr, NAMES))

    def transform(self, node, results):
        name = results["meth"][0]
        name.replace(Name(NAMES[str(name)], prefix=name.prefix))
PK       ! 6ng      fix_import.pynu [        """Fixer for import statements.
If spam is being imported from the local directory, this import:
    from spam import eggs
Becomes:
    from .spam import eggs

And this import:
    import spam
Becomes:
    from . import spam
"""

# Local imports
from .. import fixer_base
from os.path import dirname, join, exists, sep
from ..fixer_util import FromImport, syms, token


def traverse_imports(names):
    """
    Walks over all the names imported in a dotted_as_names node.
    """
    pending = [names]
    while pending:
        node = pending.pop()
        if node.type == token.NAME:
            yield node.value
        elif node.type == syms.dotted_name:
            yield "".join([ch.value for ch in node.children])
        elif node.type == syms.dotted_as_name:
            pending.append(node.children[0])
        elif node.type == syms.dotted_as_names:
            pending.extend(node.children[::-2])
        else:
            raise AssertionError("unknown node type")


class FixImport(fixer_base.BaseFix):
    BM_compatible = True

    PATTERN = """
    import_from< 'from' imp=any 'import' ['('] any [')'] >
    |
    import_name< 'import' imp=any >
    """

    def start_tree(self, tree, name):
        super(FixImport, self).start_tree(tree, name)
        self.skip = "absolute_import" in tree.future_features

    def transform(self, node, results):
        if self.skip:
            return
        imp = results['imp']

        if node.type == syms.import_from:
            # Some imps are top-level (eg: 'import ham')
            # some are first level (eg: 'import ham.eggs')
            # some are third level (eg: 'import ham.eggs as spam')
            # Hence, the loop
            while not hasattr(imp, 'value'):
                imp = imp.children[0]
            if self.probably_a_local_import(imp.value):
                imp.value = "." + imp.value
                imp.changed()
        else:
            have_local = False
            have_absolute = False
            for mod_name in traverse_imports(imp):
                if self.probably_a_local_import(mod_name):
                    have_local = True
                else:
                    have_absolute = True
            if have_absolute:
                if have_local:
                    # We won't handle both sibling and absolute imports in the
                    # same statement at the moment.
                    self.warning(node, "absolute and local imports together")
                return

            new = FromImport(".", [imp])
            new.prefix = node.prefix
            return new

    def probably_a_local_import(self, imp_name):
        if imp_name.startswith("."):
            # Relative imports are certainly not local imports.
            return False
        imp_name = imp_name.split(".", 1)[0]
        base_path = dirname(self.filename)
        base_path = join(base_path, imp_name)
        # If there is no __init__.py next to the file its not in a package
        # so can't be a relative import.
        if not exists(join(dirname(base_path), "__init__.py")):
            return False
        for ext in [".py", sep, ".pyc", ".so", ".sl", ".pyd"]:
            if exists(base_path + ext):
                return True
        return False
PK       !         fix_urllib.pynu [        """Fix changes imports of urllib which are now incompatible.
   This is rather similar to fix_imports, but because of the more
   complex nature of the fixing for urllib, it has its own fixer.
"""
# Author: Nick Edds

# Local imports
from lib2to3.fixes.fix_imports import alternates, FixImports
from lib2to3.fixer_util import (Name, Comma, FromImport, Newline,
                                find_indentation, Node, syms)

MAPPING = {"urllib":  [
                ("urllib.request",
                    ["URLopener", "FancyURLopener", "urlretrieve",
                     "_urlopener", "urlopen", "urlcleanup",
                     "pathname2url", "url2pathname", "getproxies"]),
                ("urllib.parse",
                    ["quote", "quote_plus", "unquote", "unquote_plus",
                     "urlencode", "splitattr", "splithost", "splitnport",
                     "splitpasswd", "splitport", "splitquery", "splittag",
                     "splittype", "splituser", "splitvalue", ]),
                ("urllib.error",
                    ["ContentTooShortError"])],
           "urllib2" : [
                ("urllib.request",
                    ["urlopen", "install_opener", "build_opener",
                     "Request", "OpenerDirector", "BaseHandler",
                     "HTTPDefaultErrorHandler", "HTTPRedirectHandler",
                     "HTTPCookieProcessor", "ProxyHandler",
                     "HTTPPasswordMgr",
                     "HTTPPasswordMgrWithDefaultRealm",
                     "AbstractBasicAuthHandler",
                     "HTTPBasicAuthHandler", "ProxyBasicAuthHandler",
                     "AbstractDigestAuthHandler",
                     "HTTPDigestAuthHandler", "ProxyDigestAuthHandler",
                     "HTTPHandler", "HTTPSHandler", "FileHandler",
                     "FTPHandler", "CacheFTPHandler",
                     "UnknownHandler"]),
                ("urllib.error",
                    ["URLError", "HTTPError"]),
           ]
}

# Duplicate the url parsing functions for urllib2.
MAPPING["urllib2"].append(MAPPING["urllib"][1])


def build_pattern():
    bare = set()
    for old_module, changes in MAPPING.items():
        for change in changes:
            new_module, members = change
            members = alternates(members)
            yield """import_name< 'import' (module=%r
                                  | dotted_as_names< any* module=%r any* >) >
                  """ % (old_module, old_module)
            yield """import_from< 'from' mod_member=%r 'import'
                       ( member=%s | import_as_name< member=%s 'as' any > |
                         import_as_names< members=any*  >) >
                  """ % (old_module, members, members)
            yield """import_from< 'from' module_star=%r 'import' star='*' >
                  """ % old_module
            yield """import_name< 'import'
                                  dotted_as_name< module_as=%r 'as' any > >
                  """ % old_module
            # bare_with_attr has a special significance for FixImports.match().
            yield """power< bare_with_attr=%r trailer< '.' member=%s > any* >
                  """ % (old_module, members)


class FixUrllib(FixImports):

    def build_pattern(self):
        return "|".join(build_pattern())

    def transform_import(self, node, results):
        """Transform for the basic import case. Replaces the old
           import name with a comma separated list of its
           replacements.
        """
        import_mod = results.get("module")
        pref = import_mod.prefix

        names = []

        # create a Node list of the replacement modules
        for name in MAPPING[import_mod.value][:-1]:
            names.extend([Name(name[0], prefix=pref), Comma()])
        names.append(Name(MAPPING[import_mod.value][-1][0], prefix=pref))
        import_mod.replace(names)

    def transform_member(self, node, results):
        """Transform for imports of specific module elements. Replaces
           the module to be imported from with the appropriate new
           module.
        """
        mod_member = results.get("mod_member")
        pref = mod_member.prefix
        member = results.get("member")

        # Simple case with only a single member being imported
        if member:
            # this may be a list of length one, or just a node
            if isinstance(member, list):
                member = member[0]
            new_name = None
            for change in MAPPING[mod_member.value]:
                if member.value in change[1]:
                    new_name = change[0]
                    break
            if new_name:
                mod_member.replace(Name(new_name, prefix=pref))
            else:
                self.cannot_convert(node, "This is an invalid module element")

        # Multiple members being imported
        else:
            # a dictionary for replacements, order matters
            modules = []
            mod_dict = {}
            members = results["members"]
            for member in members:
                # we only care about the actual members
                if member.type == syms.import_as_name:
                    as_name = member.children[2].value
                    member_name = member.children[0].value
                else:
                    member_name = member.value
                    as_name = None
                if member_name != ",":
                    for change in MAPPING[mod_member.value]:
                        if member_name in change[1]:
                            if change[0] not in mod_dict:
                                modules.append(change[0])
                            mod_dict.setdefault(change[0], []).append(member)

            new_nodes = []
            indentation = find_indentation(node)
            first = True
            def handle_name(name, prefix):
                if name.type == syms.import_as_name:
                    kids = [Name(name.children[0].value, prefix=prefix),
                            name.children[1].clone(),
                            name.children[2].clone()]
                    return [Node(syms.import_as_name, kids)]
                return [Name(name.value, prefix=prefix)]
            for module in modules:
                elts = mod_dict[module]
                names = []
                for elt in elts[:-1]:
                    names.extend(handle_name(elt, pref))
                    names.append(Comma())
                names.extend(handle_name(elts[-1], pref))
                new = FromImport(module, names)
                if not first or node.parent.prefix.endswith(indentation):
                    new.prefix = indentation
                new_nodes.append(new)
                first = False
            if new_nodes:
                nodes = []
                for new_node in new_nodes[:-1]:
                    nodes.extend([new_node, Newline()])
                nodes.append(new_nodes[-1])
                node.replace(nodes)
            else:
                self.cannot_convert(node, "All module elements are invalid")

    def transform_dot(self, node, results):
        """Transform for calls to module members in code."""
        module_dot = results.get("bare_with_attr")
        member = results.get("member")
        new_name = None
        if isinstance(member, list):
            member = member[0]
        for change in MAPPING[module_dot.value]:
            if member.value in change[1]:
                new_name = change[0]
                break
        if new_name:
            module_dot.replace(Name(new_name,
                                    prefix=module_dot.prefix))
        else:
            self.cannot_convert(node, "This is an invalid module element")

    def transform(self, node, results):
        if results.get("module"):
            self.transform_import(node, results)
        elif results.get("mod_member"):
            self.transform_member(node, results)
        elif results.get("bare_with_attr"):
            self.transform_dot(node, results)
        # Renaming and star imports are not supported for these modules.
        elif results.get("module_star"):
            self.cannot_convert(node, "Cannot handle star imports.")
        elif results.get("module_as"):
            self.cannot_convert(node, "This module is now multiple modules")
PK       ! C
  
    fix_xrange.pynu [        # Copyright 2007 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.

"""Fixer that changes xrange(...) into range(...)."""

# Local imports
from .. import fixer_base
from ..fixer_util import Name, Call, consuming_calls
from .. import patcomp


class FixXrange(fixer_base.BaseFix):
    BM_compatible = True
    PATTERN = """
              power<
                 (name='range'|name='xrange') trailer< '(' args=any ')' >
              rest=any* >
              """

    def start_tree(self, tree, filename):
        super(FixXrange, self).start_tree(tree, filename)
        self.transformed_xranges = set()

    def finish_tree(self, tree, filename):
        self.transformed_xranges = None

    def transform(self, node, results):
        name = results["name"]
        if name.value == "xrange":
            return self.transform_xrange(node, results)
        elif name.value == "range":
            return self.transform_range(node, results)
        else:
            raise ValueError(repr(name))

    def transform_xrange(self, node, results):
        name = results["name"]
        name.replace(Name("range", prefix=name.prefix))
        # This prevents the new range call from being wrapped in a list later.
        self.transformed_xranges.add(id(node))

    def transform_range(self, node, results):
        if (id(node) not in self.transformed_xranges and
            not self.in_special_context(node)):
            range_call = Call(Name("range"), [results["args"].clone()])
            # Encase the range call in list().
            list_call = Call(Name("list"), [range_call],
                             prefix=node.prefix)
            # Put things that were after the range() call after the list call.
            for n in results["rest"]:
                list_call.append_child(n)
            return list_call

    P1 = "power< func=NAME trailer< '(' node=any ')' > any* >"
    p1 = patcomp.compile_pattern(P1)

    P2 = """for_stmt< 'for' any 'in' node=any ':' any* >
            | comp_for< 'for' any 'in' node=any any* >
            | comparison< any 'in' node=any any*>
         """
    p2 = patcomp.compile_pattern(P2)

    def in_special_context(self, node):
        if node.parent is None:
            return False
        results = {}
        if (node.parent.parent is not None and
               self.p1.match(node.parent.parent, results) and
               results["node"] is node):
            # list(d.keys()) -> list(d.keys()), etc.
            return results["func"].value in consuming_calls
        # for ... in d.iterkeys() -> for ... in d.keys(), etc.
        return self.p2.match(node.parent, results) and results["node"] is node
PK       ! xu.  .    fix_throw.pynu [        """Fixer for generator.throw(E, V, T).

g.throw(E)       -> g.throw(E)
g.throw(E, V)    -> g.throw(E(V))
g.throw(E, V, T) -> g.throw(E(V).with_traceback(T))

g.throw("foo"[, V[, T]]) will warn about string exceptions."""
# Author: Collin Winter

# Local imports
from .. import pytree
from ..pgen2 import token
from .. import fixer_base
from ..fixer_util import Name, Call, ArgList, Attr, is_tuple

class FixThrow(fixer_base.BaseFix):
    BM_compatible = True
    PATTERN = """
    power< any trailer< '.' 'throw' >
           trailer< '(' args=arglist< exc=any ',' val=any [',' tb=any] > ')' >
    >
    |
    power< any trailer< '.' 'throw' > trailer< '(' exc=any ')' > >
    """

    def transform(self, node, results):
        syms = self.syms

        exc = results["exc"].clone()
        if exc.type is token.STRING:
            self.cannot_convert(node, "Python 3 does not support string exceptions")
            return

        # Leave "g.throw(E)" alone
        val = results.get("val")
        if val is None:
            return

        val = val.clone()
        if is_tuple(val):
            args = [c.clone() for c in val.children[1:-1]]
        else:
            val.prefix = ""
            args = [val]

        throw_args = results["args"]

        if "tb" in results:
            tb = results["tb"].clone()
            tb.prefix = ""

            e = Call(exc, args)
            with_tb = Attr(e, Name('with_traceback')) + [ArgList([tb])]
            throw_args.replace(pytree.Node(syms.power, with_tb))
        else:
            throw_args.replace(Call(exc, args))
PK       ! ܬ'!  !    fix_imports2.pynu [        """Fix incompatible imports and module references that must be fixed after
fix_imports."""
from . import fix_imports


MAPPING = {
            'whichdb': 'dbm',
            'anydbm': 'dbm',
          }


class FixImports2(fix_imports.FixImports):

    run_order = 7

    mapping = MAPPING
PK       ! q|      fix_input.pynu [        """Fixer that changes input(...) into eval(input(...))."""
# Author: Andre Roberge

# Local imports
from .. import fixer_base
from ..fixer_util import Call, Name
from .. import patcomp


context = patcomp.compile_pattern("power< 'eval' trailer< '(' any ')' > >")


class FixInput(fixer_base.BaseFix):
    BM_compatible = True
    PATTERN = """
              power< 'input' args=trailer< '(' [any] ')' > >
              """

    def transform(self, node, results):
        # If we're already wrapped in an eval() call, we're done.
        if context.match(node.parent.parent):
            return

        new = node.clone()
        new.prefix = ""
        return Call(Name("eval"), [new], prefix=node.prefix)
PK       ! |b  b    fix_operator.pynu [        """Fixer for operator functions.

operator.isCallable(obj)       -> callable(obj)
operator.sequenceIncludes(obj) -> operator.contains(obj)
operator.isSequenceType(obj)   -> isinstance(obj, collections.abc.Sequence)
operator.isMappingType(obj)    -> isinstance(obj, collections.abc.Mapping)
operator.isNumberType(obj)     -> isinstance(obj, numbers.Number)
operator.repeat(obj, n)        -> operator.mul(obj, n)
operator.irepeat(obj, n)       -> operator.imul(obj, n)
"""

import collections.abc

# Local imports
from lib2to3 import fixer_base
from lib2to3.fixer_util import Call, Name, String, touch_import


def invocation(s):
    def dec(f):
        f.invocation = s
        return f
    return dec


class FixOperator(fixer_base.BaseFix):
    BM_compatible = True
    order = "pre"

    methods = """
              method=('isCallable'|'sequenceIncludes'
                     |'isSequenceType'|'isMappingType'|'isNumberType'
                     |'repeat'|'irepeat')
              """
    obj = "'(' obj=any ')'"
    PATTERN = """
              power< module='operator'
                trailer< '.' %(methods)s > trailer< %(obj)s > >
              |
              power< %(methods)s trailer< %(obj)s > >
              """ % dict(methods=methods, obj=obj)

    def transform(self, node, results):
        method = self._check_method(node, results)
        if method is not None:
            return method(node, results)

    @invocation("operator.contains(%s)")
    def _sequenceIncludes(self, node, results):
        return self._handle_rename(node, results, "contains")

    @invocation("callable(%s)")
    def _isCallable(self, node, results):
        obj = results["obj"]
        return Call(Name("callable"), [obj.clone()], prefix=node.prefix)

    @invocation("operator.mul(%s)")
    def _repeat(self, node, results):
        return self._handle_rename(node, results, "mul")

    @invocation("operator.imul(%s)")
    def _irepeat(self, node, results):
        return self._handle_rename(node, results, "imul")

    @invocation("isinstance(%s, collections.abc.Sequence)")
    def _isSequenceType(self, node, results):
        return self._handle_type2abc(node, results, "collections.abc", "Sequence")

    @invocation("isinstance(%s, collections.abc.Mapping)")
    def _isMappingType(self, node, results):
        return self._handle_type2abc(node, results, "collections.abc", "Mapping")

    @invocation("isinstance(%s, numbers.Number)")
    def _isNumberType(self, node, results):
        return self._handle_type2abc(node, results, "numbers", "Number")

    def _handle_rename(self, node, results, name):
        method = results["method"][0]
        method.value = name
        method.changed()

    def _handle_type2abc(self, node, results, module, abc):
        touch_import(None, module, node)
        obj = results["obj"]
        args = [obj.clone(), String(", " + ".".join([module, abc]))]
        return Call(Name("isinstance"), args, prefix=node.prefix)

    def _check_method(self, node, results):
        method = getattr(self, "_" + results["method"][0].value)
        if isinstance(method, collections.abc.Callable):
            if "module" in results:
                return method
            else:
                sub = (str(results["obj"]),)
                invocation_str = method.invocation % sub
                self.warning(node, "You should use '%s' here." % invocation_str)
        return None
PK       ! O+      fix_tuple_params.pynu [        """Fixer for function definitions with tuple parameters.

def func(((a, b), c), d):
    ...

    ->

def func(x, d):
    ((a, b), c) = x
    ...

It will also support lambdas:

    lambda (x, y): x + y -> lambda t: t[0] + t[1]

    # The parens are a syntax error in Python 3
    lambda (x): x + y -> lambda x: x + y
"""
# Author: Collin Winter

# Local imports
from .. import pytree
from ..pgen2 import token
from .. import fixer_base
from ..fixer_util import Assign, Name, Newline, Number, Subscript, syms

def is_docstring(stmt):
    return isinstance(stmt, pytree.Node) and \
           stmt.children[0].type == token.STRING

class FixTupleParams(fixer_base.BaseFix):
    run_order = 4 #use a lower order since lambda is part of other
                  #patterns
    BM_compatible = True

    PATTERN = """
              funcdef< 'def' any parameters< '(' args=any ')' >
                       ['->' any] ':' suite=any+ >
              |
              lambda=
              lambdef< 'lambda' args=vfpdef< '(' inner=any ')' >
                       ':' body=any
              >
              """

    def transform(self, node, results):
        if "lambda" in results:
            return self.transform_lambda(node, results)

        new_lines = []
        suite = results["suite"]
        args = results["args"]
        # This crap is so "def foo(...): x = 5; y = 7" is handled correctly.
        # TODO(cwinter): suite-cleanup
        if suite[0].children[1].type == token.INDENT:
            start = 2
            indent = suite[0].children[1].value
            end = Newline()
        else:
            start = 0
            indent = "; "
            end = pytree.Leaf(token.INDENT, "")

        # We need access to self for new_name(), and making this a method
        #  doesn't feel right. Closing over self and new_lines makes the
        #  code below cleaner.
        def handle_tuple(tuple_arg, add_prefix=False):
            n = Name(self.new_name())
            arg = tuple_arg.clone()
            arg.prefix = ""
            stmt = Assign(arg, n.clone())
            if add_prefix:
                n.prefix = " "
            tuple_arg.replace(n)
            new_lines.append(pytree.Node(syms.simple_stmt,
                                         [stmt, end.clone()]))

        if args.type == syms.tfpdef:
            handle_tuple(args)
        elif args.type == syms.typedargslist:
            for i, arg in enumerate(args.children):
                if arg.type == syms.tfpdef:
                    # Without add_prefix, the emitted code is correct,
                    #  just ugly.
                    handle_tuple(arg, add_prefix=(i > 0))

        if not new_lines:
            return

        # This isn't strictly necessary, but it plays nicely with other fixers.
        # TODO(cwinter) get rid of this when children becomes a smart list
        for line in new_lines:
            line.parent = suite[0]

        # TODO(cwinter) suite-cleanup
        after = start
        if start == 0:
            new_lines[0].prefix = " "
        elif is_docstring(suite[0].children[start]):
            new_lines[0].prefix = indent
            after = start + 1

        for line in new_lines:
            line.parent = suite[0]
        suite[0].children[after:after] = new_lines
        for i in range(after+1, after+len(new_lines)+1):
            suite[0].children[i].prefix = indent
        suite[0].changed()

    def transform_lambda(self, node, results):
        args = results["args"]
        body = results["body"]
        inner = simplify_args(results["inner"])

        # Replace lambda ((((x)))): x  with lambda x: x
        if inner.type == token.NAME:
            inner = inner.clone()
            inner.prefix = " "
            args.replace(inner)
            return

        params = find_params(args)
        to_index = map_to_index(params)
        tup_name = self.new_name(tuple_name(params))

        new_param = Name(tup_name, prefix=" ")
        args.replace(new_param.clone())
        for n in body.post_order():
            if n.type == token.NAME and n.value in to_index:
                subscripts = [c.clone() for c in to_index[n.value]]
                new = pytree.Node(syms.power,
                                  [new_param.clone()] + subscripts)
                new.prefix = n.prefix
                n.replace(new)


### Helper functions for transform_lambda()

def simplify_args(node):
    if node.type in (syms.vfplist, token.NAME):
        return node
    elif node.type == syms.vfpdef:
        # These look like vfpdef< '(' x ')' > where x is NAME
        # or another vfpdef instance (leading to recursion).
        while node.type == syms.vfpdef:
            node = node.children[1]
        return node
    raise RuntimeError("Received unexpected node %s" % node)

def find_params(node):
    if node.type == syms.vfpdef:
        return find_params(node.children[1])
    elif node.type == token.NAME:
        return node.value
    return [find_params(c) for c in node.children if c.type != token.COMMA]

def map_to_index(param_list, prefix=[], d=None):
    if d is None:
        d = {}
    for i, obj in enumerate(param_list):
        trailer = [Subscript(Number(str(i)))]
        if isinstance(obj, list):
            map_to_index(obj, trailer, d=d)
        else:
            d[obj] = prefix + trailer
    return d

def tuple_name(param_list):
    l = []
    for obj in param_list:
        if isinstance(obj, list):
            l.append(tuple_name(obj))
        else:
            l.append(obj)
    return "_".join(l)
PK       ! <;  ;  	  fix_ne.pynu [        # Copyright 2006 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.

"""Fixer that turns <> into !=."""

# Local imports
from .. import pytree
from ..pgen2 import token
from .. import fixer_base


class FixNe(fixer_base.BaseFix):
    # This is so simple that we don't need the pattern compiler.

    _accept_type = token.NOTEQUAL

    def match(self, node):
        # Override
        return node.value == "<>"

    def transform(self, node, results):
        new = pytree.Leaf(token.NOTEQUAL, "!=", prefix=node.prefix)
        return new
PK       ! &  &  &  __pycache__/fix_buffer.cpython-310.pycnu [        o
    bcN                     @   s2   d Z ddlmZ ddlmZ G dd dejZdS )z4Fixer that changes buffer(...) into memoryview(...).   )
fixer_base)Namec                   @   s    e Zd ZdZdZdZdd ZdS )	FixBufferTzR
              power< name='buffer' trailer< '(' [any] ')' > any* >
              c                 C   s    |d }| td|jd d S )Nname
memoryview)prefix)replacer   r   )selfnoderesultsr    r   //usr/lib/python3.10/lib2to3/fixes/fix_buffer.py	transform   s   zFixBuffer.transformN)__name__
__module____qualname__BM_compatibleexplicitPATTERNr   r   r   r   r   r      s
    r   N)__doc__ r   
fixer_utilr   BaseFixr   r   r   r   r   <module>   s   PK       ! Κ    '  __pycache__/fix_nonzero.cpython-310.pycnu [        o
    bcO                     @   s2   d Z ddlmZ ddlmZ G dd dejZdS )z*Fixer for __nonzero__ -> __bool__ methods.   )
fixer_base)Namec                   @   s   e Zd ZdZdZdd ZdS )
FixNonzeroTz
    classdef< 'class' any+ ':'
              suite< any*
                     funcdef< 'def' name='__nonzero__'
                              parameters< '(' NAME ')' > any+ >
                     any* > >
    c                 C   s$   |d }t d|jd}|| d S )Nname__bool__)prefix)r   r   replace)selfnoderesultsr   new r   0/usr/lib/python3.10/lib2to3/fixes/fix_nonzero.py	transform   s   zFixNonzero.transformN)__name__
__module____qualname__BM_compatiblePATTERNr   r   r   r   r   r      s    r   N)__doc__ r   
fixer_utilr   BaseFixr   r   r   r   r   <module>   s    PK       ! #    '  __pycache__/fix_unicode.cpython-310.pycnu [        o
    bc                     @   s<   d Z ddlmZ ddlmZ dddZG dd dejZd	S )
zFixer for unicode.

* Changes unicode to str and unichr to chr.

* If "...\u..." is not unicode literal change it into "...\\u...".

* Change u"..." into "...".

   )token)
fixer_basechrstr)unichrunicodec                       s,   e Zd ZdZdZ fddZdd Z  ZS )
FixUnicodeTzSTRING | 'unicode' | 'unichr'c                    s"   t t| || d|jv | _d S )Nunicode_literals)superr   
start_treefuture_featuresr	   )selftreefilename	__class__ 0/usr/lib/python3.10/lib2to3/fixes/fix_unicode.pyr      s   zFixUnicode.start_treec                 C   s   |j tjkr| }t|j |_|S |j tjkrQ|j}| js5|d dv r5d|v r5ddd |	dD }|d dv rA|dd  }||jkrH|S | }||_|S d S )	N    z'"\z\\c                 S   s    g | ]}| d d ddqS )z\uz\\uz\Uz\\U)replace).0vr   r   r   
<listcomp>    s    z(FixUnicode.transform.<locals>.<listcomp>uU   )
typer   NAMEclone_mappingvalueSTRINGr	   joinsplit)r   noderesultsnewvalr   r   r   	transform   s$   

zFixUnicode.transform)__name__
__module____qualname__BM_compatiblePATTERNr   r(   __classcell__r   r   r   r   r      s
    r   N)__doc__pgen2r    r   r   BaseFixr   r   r   r   r   <module>   s
    

PK       ! 4ǹl	  	  &  __pycache__/fix_filter.cpython-310.pycnu [        o
    bc
                     @   sZ   d Z ddlmZ ddlmZ ddlmZ ddlm	Z	m
Z
mZmZmZ G dd dejZdS )	a  Fixer that changes filter(F, X) into list(filter(F, X)).

We avoid the transformation if the filter() call is directly contained
in iter(<>), list(<>), tuple(<>), sorted(<>), ...join(<>), or
for V in <>:.

NOTE: This is still not correct if the original code was depending on
filter(F, X) to return a string if X is a string and a tuple if X is a
tuple.  That would require type inference, which we don't do.  Let
Python 2.6 figure it out.
   )
fixer_base)Node)python_symbols)NameArgListListCompin_special_contextparenthesizec                   @   s    e Zd ZdZdZdZdd ZdS )	FixFilterTaV  
    filter_lambda=power<
        'filter'
        trailer<
            '('
            arglist<
                lambdef< 'lambda'
                         (fp=NAME | vfpdef< '(' fp=NAME ')'> ) ':' xp=any
                >
                ','
                it=any
            >
            ')'
        >
        [extra_trailers=trailer*]
    >
    |
    power<
        'filter'
        trailer< '(' arglist< none='None' ',' seq=any > ')' >
        [extra_trailers=trailer*]
    >
    |
    power<
        'filter'
        args=trailer< '(' [any] ')' >
        [extra_trailers=trailer*]
    >
    zfuture_builtins.filterc                 C   sL  |  |rd S g }d|v r|d D ]	}||  qd|v rU|d }|jtjkr3d|_t|}t	|d |d |d |}t
tj|g| dd}nKd|v rvt	td	td	|d
  td	}t
tj|g| dd}n*t|r|d S |d  }t
tjtd|gdd}t
tjtdt|gg| }d|_|j|_|S )Nextra_trailersfilter_lambdaxp fpit)prefixnone_fseqargsfilterlist)should_skipappendclonegettypesymstestr   r	   r   r   powerr   r   r   )selfnoderesultstrailerstr   newr    r&   //usr/lib/python3.10/lib2to3/fixes/fix_filter.py	transform:   s>   

zFixFilter.transformN)__name__
__module____qualname__BM_compatiblePATTERNskip_onr(   r&   r&   r&   r'   r
      s
    r
   N)__doc__r   r   pytreer   pygramr   r   
fixer_utilr   r   r   r   r	   ConditionalFixr
   r&   r&   r&   r'   <module>   s   PK       ! Bk    '  __pycache__/fix_asserts.cpython-310.pycnu [        o
    bc                     @   sT   d Z ddlmZ ddlmZ edddddd	d
ddddddddZG dd deZdS )z5Fixer that replaces deprecated unittest method names.   )BaseFix)Name
assertTrueassertEqualassertNotEqualassertAlmostEqualassertNotAlmostEqualassertRegexassertRaisesRegexassertRaisesassertFalse)assert_assertEqualsassertNotEqualsassertAlmostEqualsassertNotAlmostEqualsassertRegexpMatchesassertRaisesRegexpfailUnlessEqualfailIfEqualfailUnlessAlmostEqualfailIfAlmostEqual
failUnlessfailUnlessRaisesfailIfc                   @   s(   e Zd Zddeee Zdd ZdS )
FixAssertszH
              power< any+ trailer< '.' meth=(%s)> any* >
              |c                 C   s,   |d d }| ttt| |jd d S )Nmeth    )prefix)replacer   NAMESstrr   )selfnoderesultsname r'   0/usr/lib/python3.10/lib2to3/fixes/fix_asserts.py	transform    s    zFixAsserts.transformN)	__name__
__module____qualname__joinmapreprr!   PATTERNr)   r'   r'   r'   r(   r      s
    r   N)__doc__
fixer_baser   
fixer_utilr   dictr!   r   r'   r'   r'   r(   <module>   s(    PK       ! 0p    $  __pycache__/fix_next.cpython-310.pycnu [        o
    bcf                     @   sn   d Z ddlmZ ddlmZ ddlmZ ddlm	Z	m
Z
mZ dZG dd dejZd	d
 Zdd Zdd ZdS )z.Fixer for it.next() -> next(it), per PEP 3114.   )token)python_symbols)
fixer_base)NameCallfind_bindingz;Calls to builtin next() possibly shadowed by global bindingc                       s0   e Zd ZdZdZdZ fddZdd Z  ZS )FixNextTa  
    power< base=any+ trailer< '.' attr='next' > trailer< '(' ')' > >
    |
    power< head=any+ trailer< '.' attr='next' > not trailer< '(' ')' > >
    |
    classdef< 'class' any+ ':'
              suite< any*
                     funcdef< 'def'
                              name='next'
                              parameters< '(' NAME ')' > any+ >
                     any* > >
    |
    global=global_stmt< 'global' any* 'next' any* >
    prec                    s@   t t| || td|}|r| |t d| _d S d| _d S )NnextTF)superr   
start_treer   warningbind_warningshadowed_next)selftreefilenamen	__class__ -/usr/lib/python3.10/lib2to3/fixes/fix_next.pyr   $   s   


zFixNext.start_treec                 C   s  |sJ | d}| d}| d}|r?| jr$|td|jd d S dd |D }d|d	 _|ttd
|jd| d S |rOtd|jd}|| d S |rxt|ro|d }ddd |D  dkrm| 	|t
 d S |td d S d|v r| 	|t
 d| _d S d S )Nbaseattrname__next__)prefixc                 S   s   g | ]}|  qS r   )clone.0r   r   r   r   
<listcomp>9       z%FixNext.transform.<locals>.<listcomp>     r
   headc                 S   s   g | ]}t |qS r   )strr   r   r   r   r    E   r!   __builtin__globalT)getr   replacer   r   r   is_assign_targetjoinstripr   r   )r   noderesultsr   r   r   r   r$   r   r   r   	transform.   s0   




zFixNext.transform)	__name__
__module____qualname__BM_compatiblePATTERNorderr   r/   __classcell__r   r   r   r   r      s    
r   c                 C   sF   t | }|d u r
dS |jD ]}|jtjkr dS t|| r  dS qdS )NFT)find_assignchildrentyper   EQUAL
is_subtree)r-   assignchildr   r   r   r*   Q   s   

r*   c                 C   s4   | j tjkr| S | j tjks| jd u rd S t| jS N)r9   syms	expr_stmtsimple_stmtparentr7   r-   r   r   r   r7   ]   s
   
r7   c                    s$   |  krdS t  fdd| jD S )NTc                 3   s    | ]}t | V  qd S r>   )r;   )r   crC   r   r   	<genexpr>g   s    zis_subtree.<locals>.<genexpr>)anyr8   )rootr-   r   rC   r   r;   d   s   r;   N)__doc__pgen2r   pygramr   r?   r"   r   
fixer_utilr   r   r   r   BaseFixr   r*   r7   r;   r   r   r   r   <module>   s    @PK       ! ُr&8  8  (  __pycache__/fix_operator.cpython-310.pycnu [        o
    bcb                     @   sN   d Z ddlZddlmZ ddlmZmZmZm	Z	 dd Z
G dd dejZdS )	a  Fixer for operator functions.

operator.isCallable(obj)       -> callable(obj)
operator.sequenceIncludes(obj) -> operator.contains(obj)
operator.isSequenceType(obj)   -> isinstance(obj, collections.abc.Sequence)
operator.isMappingType(obj)    -> isinstance(obj, collections.abc.Mapping)
operator.isNumberType(obj)     -> isinstance(obj, numbers.Number)
operator.repeat(obj, n)        -> operator.mul(obj, n)
operator.irepeat(obj, n)       -> operator.imul(obj, n)
    N)
fixer_base)CallNameStringtouch_importc                    s    fdd}|S )Nc                    s
    | _ | S N)
invocation)fs 1/usr/lib/python3.10/lib2to3/fixes/fix_operator.pydec   s   zinvocation.<locals>.decr   )r   r   r   r
   r   r      s   r   c                   @   s   e Zd ZdZdZdZdZdeeed Zdd Z	e
d	d
d Ze
ddd Ze
ddd Ze
ddd Ze
ddd Ze
ddd Ze
ddd Zdd Zd d! Zd"d# Zd$S )%FixOperatorTprez
              method=('isCallable'|'sequenceIncludes'
                     |'isSequenceType'|'isMappingType'|'isNumberType'
                     |'repeat'|'irepeat')
              z'(' obj=any ')'z
              power< module='operator'
                trailer< '.' %(methods)s > trailer< %(obj)s > >
              |
              power< %(methods)s trailer< %(obj)s > >
              )methodsobjc                 C   s"   |  ||}|d ur|||S d S r   )_check_method)selfnoderesultsmethodr   r   r   	transform+   s   
zFixOperator.transformzoperator.contains(%s)c                 C      |  ||dS )Ncontains_handle_renamer   r   r   r   r   r   _sequenceIncludes0      zFixOperator._sequenceIncludeszcallable(%s)c                 C   s"   |d }t td| g|jdS )Nr   callableprefix)r   r   cloner"   )r   r   r   r   r   r   r   _isCallable4   s   zFixOperator._isCallablezoperator.mul(%s)c                 C   r   )Nmulr   r   r   r   r   _repeat9   r   zFixOperator._repeatzoperator.imul(%s)c                 C   r   )Nimulr   r   r   r   r   _irepeat=   r   zFixOperator._irepeatz(isinstance(%s, collections.abc.Sequence)c                 C      |  ||ddS )Ncollections.abcSequence_handle_type2abcr   r   r   r   _isSequenceTypeA      zFixOperator._isSequenceTypez'isinstance(%s, collections.abc.Mapping)c                 C   r)   )Nr*   Mappingr,   r   r   r   r   _isMappingTypeE   r/   zFixOperator._isMappingTypezisinstance(%s, numbers.Number)c                 C   r)   )NnumbersNumberr,   r   r   r   r   _isNumberTypeI   r/   zFixOperator._isNumberTypec                 C   s   |d d }||_ |  d S )Nr   r   )valuechanged)r   r   r   namer   r   r   r   r   M   s   zFixOperator._handle_renamec                 C   sF   t d || |d }| tdd||g g}ttd||jdS )Nr   z, .
isinstancer!   )r   r#   r   joinr   r   r"   )r   r   r   moduleabcr   argsr   r   r   r-   R   s   zFixOperator._handle_type2abcc                 C   s^   t | d|d d j }t|tjjr-d|v r|S t|d f}|j| }| |d|  d S )N_r   r   r;   r   zYou should use '%s' here.)	getattrr5   r9   collectionsr<   Callablestrr   warning)r   r   r   r   subinvocation_strr   r   r   r   X   s   
zFixOperator._check_methodN)__name__
__module____qualname__BM_compatibleorderr   r   dictPATTERNr   r   r   r$   r&   r(   r.   r1   r4   r   r-   r   r   r   r   r   r      s4    







r   )__doc__collections.abcr@   lib2to3r   lib2to3.fixer_utilr   r   r   r   r   BaseFixr   r   r   r   r   <module>   s    PK       ! 1    '  __pycache__/fix_imports.cpython-310.pycnu [        o
    bc4                     @   s@  d Z ddlmZ ddlmZmZ i ddddddd	d
dddddddddddddddddddddddd d!d"i d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdDdEdFdGdHdIdJdJdJdKdLdLdMdNdOZdPdQ ZefdRdSZG dTdU dUej	Z
dVS )Wz/Fix incompatible imports and module references.   )
fixer_base)Name
attr_chainStringIOio	cStringIOcPicklepickle__builtin__builtinscopy_regcopyregQueuequeueSocketServersocketserverConfigParserconfigparserreprreprlib
FileDialogztkinter.filedialogtkFileDialogSimpleDialogztkinter.simpledialogtkSimpleDialogtkColorChooserztkinter.colorchoosertkCommonDialogztkinter.commondialogDialogztkinter.dialogTkdndztkinter.dndtkFontztkinter.fonttkMessageBoxztkinter.messageboxScrolledTextztkinter.scrolledtextTkconstantsztkinter.constantsTixztkinter.tixttkztkinter.ttkTkintertkinter
markupbase_markupbase_winregwinregthread_threaddummy_thread_dummy_threaddbhashzdbm.bsddumbdbmzdbm.dumbdbmzdbm.ndbmgdbmzdbm.gnu	xmlrpclibzxmlrpc.clientDocXMLRPCServerzxmlrpc.serverzhttp.clientzhtml.entitieszhtml.parserzhttp.cookieszhttp.cookiejarzhttp.server
subprocesscollectionszurllib.parsezurllib.robotparser)SimpleXMLRPCServerhttplibhtmlentitydefs
HTMLParserCookie	cookielibBaseHTTPServerSimpleHTTPServerCGIHTTPServercommands
UserStringUserListurlparserobotparserc                 C   s   dd tt|  d S )N(|))joinmapr   )members rJ   0/usr/lib/python3.10/lib2to3/fixes/fix_imports.py
alternates=   s   rL   c                 c   sV    d dd | D }t|  }d||f V  d| V  d||f V  d| V  d S )Nz | c                 S   s   g | ]}d | qS )zmodule_name='%s'rJ   ).0keyrJ   rJ   rK   
<listcomp>B   s    z!build_pattern.<locals>.<listcomp>zyname_import=import_name< 'import' ((%s) |
               multiple_imports=dotted_as_names< any* (%s) any* >) >
          zimport_from< 'from' (%s) 'import' ['(']
              ( any | import_as_name< any 'as' any > |
                import_as_names< any* >)  [')'] >
          zimport_name< 'import' (dotted_as_name< (%s) 'as' any > |
               multiple_imports=dotted_as_names<
                 any* dotted_as_name< (%s) 'as' any > any* >) >
          z3power< bare_with_attr=(%s) trailer<'.' any > any* >)rG   rL   keys)mappingmod_list
bare_namesrJ   rJ   rK   build_patternA   s   rT   c                       sT   e Zd ZdZdZeZdZdd Z fddZ	 fddZ
 fd	d
Zdd Z  ZS )
FixImportsT   c                 C   s   d t| jS )NrE   )rG   rT   rQ   selfrJ   rJ   rK   rT   `   s   zFixImports.build_patternc                    s   |   | _tt|   d S N)rT   PATTERNsuperrU   compile_patternrW   	__class__rJ   rK   r\   c   s   
zFixImports.compile_patternc                    sH   t t| j  |}|r"d|vr t fddt|dD r dS |S dS )Nbare_with_attrc                 3   s    | ]} |V  qd S rY   rJ   )rM   objmatchrJ   rK   	<genexpr>q   s    z#FixImports.match.<locals>.<genexpr>parentF)r[   rU   rb   anyr   )rX   noderesultsr]   ra   rK   rb   j   s   zFixImports.matchc                    s   t t| || i | _d S rY   )r[   rU   
start_treereplace)rX   treefilenamer]   rJ   rK   rh   v   s   
zFixImports.start_treec                 C   s   | d}|r9|j}| j| }|t||jd d|v r"|| j|< d|v r5| |}|r7| || d S d S d S |d d }| j |j}|rT|t||jd d S d S )Nmodule_name)prefixname_importmultiple_importsr_       )getvaluerQ   ri   r   rm   rb   	transform)rX   rf   rg   
import_modmod_namenew_name	bare_namerJ   rJ   rK   rs   z   s$   



zFixImports.transform)__name__
__module____qualname__BM_compatiblekeep_line_orderMAPPINGrQ   	run_orderrT   r\   rb   rh   rs   __classcell__rJ   rJ   r]   rK   rU   U   s    rU   N)__doc__ r   
fixer_utilr   r   r}   rL   rT   BaseFixrU   rJ   rJ   rJ   rK   <module>   s    	
 !"#5PK       ! "#	  	  %  __pycache__/fix_print.cpython-310.pycnu [        o
    bc                     @   sl   d Z ddlmZ ddlmZ ddlmZ ddlmZ ddlmZm	Z	m
Z
mZ edZG dd	 d	ejZd
S )a  Fixer for print.

Change:
    'print'          into 'print()'
    'print ...'      into 'print(...)'
    'print ... ,'    into 'print(..., end=" ")'
    'print >>x, ...' into 'print(..., file=x)'

No changes are applied if print_function is imported from __future__

   )patcomp)pytree)token)
fixer_base)NameCallCommaStringz"atom< '(' [atom|STRING|NAME] ')' >c                   @   s$   e Zd ZdZdZdd Zdd ZdS )FixPrintTzP
              simple_stmt< any* bare='print' any* > | print_stmt
              c           
      C   s  |sJ | d}|r|ttdg |jd d S |jd tdks%J |jdd  }t|dkr;t|d r;d S d  } }}|rR|d t	 krR|d d }d}|rs|d t
tjdkrst|d	ksgJ |d  }|d
d  }dd |D }|rd|d _|d us|d us|d ur|d ur| |dtt| |d ur| |dtt| |d ur| |d| ttd|}	|j|	_|	S )Nbareprint)prefix        z>>r      c                 S   s   g | ]}|  qS  )clone).0argr   r   ./usr/lib/python3.10/lib2to3/fixes/fix_print.py
<listcomp>?   s    z&FixPrint.transform.<locals>.<listcomp> sependfile)getreplacer   r   r   childrenlenparend_exprmatchr   r   Leafr   
RIGHTSHIFTr   	add_kwargr	   repr)
selfnoderesults
bare_printargsr   r   r   l_argsn_stmtr   r   r   	transform%   s@   

zFixPrint.transformc                 C   sN   d|_ t| jjt|ttjd|f}|r |	t
  d|_ |	| d S )Nr   =r   )r   r   Nodesymsargumentr   r#   r   EQUALappendr   )r'   l_nodess_kwdn_expr
n_argumentr   r   r   r%   M   s   
zFixPrint.add_kwargN)__name__
__module____qualname__BM_compatiblePATTERNr.   r%   r   r   r   r   r
      s
    (r
   N)__doc__r   r   r   pgen2r   r   
fixer_utilr   r   r   r	   compile_patternr!   BaseFixr
   r   r   r   r   <module>   s   PK       ! 4*t  t  %  __pycache__/fix_apply.cpython-310.pycnu [        o
    bc*	                     @   sR   d Z ddlmZ ddlmZ ddlmZ ddlmZmZm	Z	 G dd dej
ZdS )	zIFixer for apply().

This converts apply(func, v, k) into (func)(*v, **k).   )pytree)token)
fixer_base)CallCommaparenthesizec                   @   s   e Zd ZdZdZdd ZdS )FixApplyTa.  
    power< 'apply'
        trailer<
            '('
            arglist<
                (not argument<NAME '=' any>) func=any ','
                (not argument<NAME '=' any>) args=any [','
                (not argument<NAME '=' any>) kwds=any] [',']
            >
            ')'
        >
    >
    c           	      C   s2  | j }|sJ |d }|d }|d}|r'|j| j jkr'|jd jdv r'd S |r:|j| j jkr:|jd jdkr:d S |j}| }|jtj	|j
fvr]|j|jksY|jd jtjkr]t|}d|_| }d|_|d urr| }d|_ttjd	|g}|d ur|t ttjd|g d
|d _t|||dS )Nfuncargskwds    >   ***r    r    )prefix)symsgettypeargumentchildrenvaluer   cloner   NAMEatompower
DOUBLESTARr   r   LeafSTARextendr   r   )	selfnoderesultsr   r	   r
   r   r   	l_newargs r%   ./usr/lib/python3.10/lib2to3/fixes/fix_apply.py	transform   s@   

zFixApply.transformN)__name__
__module____qualname__BM_compatiblePATTERNr'   r%   r%   r%   r&   r      s    r   N)__doc__r   r   pgen2r   r   
fixer_utilr   r   r   BaseFixr   r%   r%   r%   r&   <module>   s   PK       ! _    %  __pycache__/fix_raise.cpython-310.pycnu [        o
    bcn                     @   sZ   d Z ddlmZ ddlmZ ddlmZ ddlmZmZm	Z	m
Z
mZ G dd dejZdS )	a[  Fixer for 'raise E, V, T'

raise         -> raise
raise E       -> raise E
raise E, V    -> raise E(V)
raise E, V, T -> raise E(V).with_traceback(T)
raise E, None, T -> raise E.with_traceback(T)

raise (((E, E'), E''), E'''), V -> raise E(V)
raise "foo", V, T               -> warns about string exceptions


CAVEATS:
1) "raise E, V" will be incorrectly translated if V is an exception
   instance. The correct Python 3 idiom is

        raise E from V

   but since we can't detect instance-hood by syntax alone and since
   any client code would have to be changed as well, we don't automate
   this.
   )pytree)token)
fixer_base)NameCallAttrArgListis_tuplec                   @   s   e Zd ZdZdZdd ZdS )FixRaiseTzB
    raise_stmt< 'raise' exc=any [',' val=any [',' tb=any]] >
    c                 C   sf  | j }|d  }|jtjkrd}| || d S t|r2t|r/|jd jd  }t|s!d|_d|vrGt	
|jtd|g}|j|_|S |d  }t|r^dd	 |jdd
 D }nd|_|g}d|v r|d  }	d|	_|}
|jtjks~|jdkrt||}
t|
tdt|	gg }t	
|jtdg| }|j|_|S t	j
|jtdt||g|jdS )Nexcz+Python 3 does not support string exceptions        valraisec                 S   s   g | ]}|  qS  )clone).0cr   r   ./usr/lib/python3.10/lib2to3/fixes/fix_raise.py
<listcomp>D   s    z&FixRaise.transform.<locals>.<listcomp> tbNonewith_traceback)prefix)symsr   typer   STRINGcannot_convertr	   childrenr   r   Node
raise_stmtr   NAMEvaluer   r   r   simple_stmt)selfnoderesultsr   r   msgnewr   argsr   ewith_tbr   r   r   	transform&   sD   
zFixRaise.transformN)__name__
__module____qualname__BM_compatiblePATTERNr/   r   r   r   r   r
      s    r
   N)__doc__r   r   pgen2r   r   
fixer_utilr   r   r   r   r	   BaseFixr
   r   r   r   r   <module>   s    PK       ! a  a  *  __pycache__/fix_xreadlines.cpython-310.pycnu [        o
    bc                     @   s2   d Z ddlmZ ddlmZ G dd dejZdS )zpFix "for x in f.xreadlines()" -> "for x in f".

This fixer will also convert g(f.xreadlines) into g(f.__iter__).   )
fixer_base)Namec                   @   s   e Zd ZdZdZdd ZdS )FixXreadlinesTz
    power< call=any+ trailer< '.' 'xreadlines' > trailer< '(' ')' > >
    |
    power< any+ trailer< '.' no_call='xreadlines' > >
    c                 C   sB   | d}|r|td|jd d S |dd |d D  d S )Nno_call__iter__)prefixc                 S   s   g | ]}|  qS  )clone).0xr   r   3/usr/lib/python3.10/lib2to3/fixes/fix_xreadlines.py
<listcomp>   s    z+FixXreadlines.transform.<locals>.<listcomp>call)getreplacer   r   )selfnoderesultsr   r   r   r   	transform   s   
zFixXreadlines.transformN)__name__
__module____qualname__BM_compatiblePATTERNr   r   r   r   r   r      s    r   N)__doc__ r   
fixer_utilr   BaseFixr   r   r   r   r   <module>   s    PK       ! Ɂ	  	  (  __pycache__/fix_exitfunc.cpython-310.pycnu [        o
    bc	                     @   sJ   d Z ddlmZmZ ddlmZmZmZmZm	Z	m
Z
 G dd dejZdS )z7
Convert use of sys.exitfunc to use the atexit module.
    )pytree
fixer_base)NameAttrCallCommaNewlinesymsc                       s<   e Zd ZdZdZdZ fddZ fddZdd Z  Z	S )	FixExitfuncTa  
              (
                  sys_import=import_name<'import'
                      ('sys'
                      |
                      dotted_as_names< (any ',')* 'sys' (',' any)* >
                      )
                  >
              |
                  expr_stmt<
                      power< 'sys' trailer< '.' 'exitfunc' > >
                  '=' func=any >
              )
              c                    s   t t| j|  d S N)superr
   __init__)selfargs	__class__ 1/usr/lib/python3.10/lib2to3/fixes/fix_exitfunc.pyr      s   zFixExitfunc.__init__c                    s   t t| || d | _d S r   )r   r
   
start_tree
sys_import)r   treefilenamer   r   r   r   !   s   
zFixExitfunc.start_treec                 C   s(  d|v r| j d u r|d | _ d S |d  }d|_ttjttdtd}t	||g|j}|
| | j d u rA| |d d S | j jd }|jtjkr]|t  |tdd d S | j j}|j| j }|j}	ttjtd	tddg}
ttj|
g}||d t  ||d
 | d S )Nr   func atexitregisterzKCan't find sys import; Please add an atexit import at the top of your file.    import   )r   cloneprefixr   Noder	   powerr   r   r   replacewarningchildrentypedotted_as_namesappend_childr   parentindeximport_namesimple_stmtinsert_childr   )r   noderesultsr   r   callnamescontaining_stmtpositionstmt_container
new_importnewr   r   r   	transform%   s6   



zFixExitfunc.transform)
__name__
__module____qualname__keep_line_orderBM_compatiblePATTERNr   r   r8   __classcell__r   r   r   r   r
      s    r
   N)__doc__lib2to3r   r   lib2to3.fixer_utilr   r   r   r   r   r	   BaseFixr
   r   r   r   r   <module>   s     PK       ! \    &  __pycache__/fix_future.cpython-310.pycnu [        o
    bc#                     @   s2   d Z ddlmZ ddlmZ G dd dejZdS )zVRemove __future__ imports

from __future__ import foo is replaced with an empty line.
   )
fixer_base)	BlankLinec                   @   s    e Zd ZdZdZdZdd ZdS )	FixFutureTz;import_from< 'from' module_name="__future__" 'import' any >
   c                 C   s   t  }|j|_|S )N)r   prefix)selfnoderesultsnew r   //usr/lib/python3.10/lib2to3/fixes/fix_future.py	transform   s   zFixFuture.transformN)__name__
__module____qualname__BM_compatiblePATTERN	run_orderr   r   r   r   r   r      s
    r   N)__doc__ r   
fixer_utilr   BaseFixr   r   r   r   r   <module>   s    PK       ! #b    1  __pycache__/fix_itertools_imports.cpython-310.pycnu [        o
    bc&                     @   s:   d Z ddlmZ ddlmZmZmZ G dd dejZdS )zA Fixer for imports of itertools.(imap|ifilter|izip|ifilterfalse)     )
fixer_base)	BlankLinesymstokenc                   @   s"   e Zd ZdZde  Zdd ZdS )FixItertoolsImportsTzT
              import_from< 'from' 'itertools' 'import' imports=any >
              c                 C   sr  |d }|j tjks|js|g}n|j}|d d d D ]F}|j tjkr)|j}|}n|j tjkr2 d S |j tjks:J |jd }|j}|dv rNd |_|  q|dv ra|	  |d dkr^dnd	|_q|jd d  pk|g}d
}	|D ]}|	r|j tj
kr|  qp|	d
N }	qp|r|d j tj
kr|   |r|d j tj
ks|jst|dd r|jd u r|j}
t }|
|_|S d S )Nimports   r   )imapizipifilter)ifilterfalseizip_longest   ffilterfalsezip_longestTvalue)typer   import_as_namechildrenr   NAMEr   STARremovechangedCOMMApopgetattrparentprefixr   )selfnoderesultsr   r   childmember	name_nodemember_nameremove_commap r)   :/usr/lib/python3.10/lib2to3/fixes/fix_itertools_imports.py	transform   sL   




zFixItertoolsImports.transformN)__name__
__module____qualname__BM_compatiblelocalsPATTERNr+   r)   r)   r)   r*   r      s    r   N)	__doc__lib2to3r   lib2to3.fixer_utilr   r   r   BaseFixr   r)   r)   r)   r*   <module>   s    PK       ! dk  k  $  __pycache__/fix_exec.cpython-310.pycnu [        o
    bc                     @   s:   d Z ddlmZ ddlmZmZmZ G dd dejZdS )zFixer for exec.

This converts usages of the exec statement into calls to a built-in
exec() function.

exec code in ns1, ns2 -> exec(code, ns1, ns2)
   )
fixer_base)CommaNameCallc                   @   s   e Zd ZdZdZdd ZdS )FixExecTzx
    exec_stmt< 'exec' a=any 'in' b=any [',' c=any] >
    |
    exec_stmt< 'exec' (not atom<'(' [any] ')'>) a=any >
    c                 C   s   |sJ | j }|d }|d}|d}| g}d|d _|d ur-|t | g |d ur;|t | g ttd||jdS )Nabc     exec)prefix)symsgetcloner   extendr   r   r   )selfnoderesultsr   r   r   r	   args r   -/usr/lib/python3.10/lib2to3/fixes/fix_exec.py	transform   s   



zFixExec.transformN)__name__
__module____qualname__BM_compatiblePATTERNr   r   r   r   r   r      s    r   N)	__doc__r
   r   
fixer_utilr   r   r   BaseFixr   r   r   r   r   <module>   s   	PK       ! gWM    $  __pycache__/fix_long.cpython-310.pycnu [        o
    bc                     @   s2   d Z ddlmZ ddlmZ G dd dejZdS )z/Fixer that turns 'long' into 'int' everywhere.
    )
fixer_base)is_probably_builtinc                   @   s   e Zd ZdZdZdd ZdS )FixLongTz'long'c                 C   s   t |rd|_|  d S d S )Nint)r   valuechanged)selfnoderesults r   -/usr/lib/python3.10/lib2to3/fixes/fix_long.py	transform   s   zFixLong.transformN)__name__
__module____qualname__BM_compatiblePATTERNr   r   r   r   r   r      s    r   N)__doc__lib2to3r   lib2to3.fixer_utilr   BaseFixr   r   r   r   r   <module>   s   PK       ! ͗<	  	  &  __pycache__/fix_xrange.cpython-310.pycnu [        o
    bc
                     @   sF   d Z ddlmZ ddlmZmZmZ ddlmZ G dd dejZ	dS )z/Fixer that changes xrange(...) into range(...).   )
fixer_base)NameCallconsuming_calls)patcompc                       sh   e Zd ZdZdZ fddZdd Zdd Zd	d
 Zdd Z	dZ
ee
ZdZeeZdd Z  ZS )	FixXrangeTz
              power<
                 (name='range'|name='xrange') trailer< '(' args=any ')' >
              rest=any* >
              c                    s   t t| || t | _d S N)superr   
start_treesettransformed_xrangesselftreefilename	__class__ //usr/lib/python3.10/lib2to3/fixes/fix_xrange.pyr
      s   zFixXrange.start_treec                 C   s
   d | _ d S r   )r   r   r   r   r   finish_tree   s   
zFixXrange.finish_treec                 C   s@   |d }|j dkr| ||S |j dkr| ||S tt|)Nnamexrangerange)valuetransform_xrangetransform_range
ValueErrorreprr   noderesultsr   r   r   r   	transform   s   

zFixXrange.transformc                 C   s0   |d }| td|jd | jt| d S )Nr   r   prefix)replacer   r#   r   addidr   r   r   r   r   $   s   zFixXrange.transform_xrangec                 C   sj   t || jvr1| |s3ttd|d  g}ttd|g|jd}|d D ]}|| q'|S d S d S )Nr   argslistr"   rest)r&   r   in_special_contextr   r   cloner#   append_child)r   r   r    
range_call	list_callnr   r   r   r   *   s   zFixXrange.transform_rangez3power< func=NAME trailer< '(' node=any ')' > any* >zfor_stmt< 'for' any 'in' node=any ':' any* >
            | comp_for< 'for' any 'in' node=any any* >
            | comparison< any 'in' node=any any*>
         c                 C   sf   |j d u rdS i }|j j d ur%| j|j j |r%|d |u r%|d jtv S | j|j |o2|d |u S )NFr   func)parentp1matchr   r   p2)r   r   r    r   r   r   r*   ?   s   
zFixXrange.in_special_context)__name__
__module____qualname__BM_compatiblePATTERNr
   r   r!   r   r   P1r   compile_patternr2   P2r4   r*   __classcell__r   r   r   r   r      s    	

r   N)
__doc__ r   
fixer_utilr   r   r   r   BaseFixr   r   r   r   r   <module>   s
   PK       ! V)  )  "  __pycache__/fix_ne.cpython-310.pycnu [        o
    bc;                     @   s>   d Z ddlmZ ddlmZ ddlmZ G dd dejZdS )zFixer that turns <> into !=.   )pytree)token)
fixer_basec                   @   s"   e Zd ZejZdd Zdd ZdS )FixNec                 C   s
   |j dkS )Nz<>)value)selfnode r	   +/usr/lib/python3.10/lib2to3/fixes/fix_ne.pymatch   s   
zFixNe.matchc                 C   s   t jtjd|jd}|S )Nz!=)prefix)r   Leafr   NOTEQUALr   )r   r   resultsnewr	   r	   r
   	transform   s   zFixNe.transformN)__name__
__module____qualname__r   r   _accept_typer   r   r	   r	   r	   r
   r      s    r   N)__doc__ r   pgen2r   r   BaseFixr   r	   r	   r	   r
   <module>   s
   PK       ! hMm      $  __pycache__/__init__.cpython-310.pycnu [        o
    bc/                      @   s   d S )N r   r   r   -/usr/lib/python3.10/lib2to3/fixes/__init__.py<module>   s    PK       ! ^    (  __pycache__/fix_execfile.cpython-310.pycnu [        o
    bc                      @   sV   d Z ddlmZ ddlmZmZmZmZmZm	Z	m
Z
mZmZmZ G dd dejZdS )zoFixer for execfile.

This converts usages of the execfile function into calls to the built-in
exec() function.
   )
fixer_base)
CommaNameCallLParenRParenDotNodeArgListStringsymsc                   @   s   e Zd ZdZdZdd ZdS )FixExecfileTz
    power< 'execfile' trailer< '(' arglist< filename=any [',' globals=any [',' locals=any ] ] > ')' > >
    |
    power< 'execfile' trailer< '(' filename=any ')' > >
    c                 C   s,  |sJ |d }| d}| d}|jd jd  }t| t tddg|d}ttjt	d|g}ttj
t t	d	gttj
t t gg}	|g|	 }
| }d|_td
d}|
t |t |g }tt	d|d}|g}|d ur~|t | g |d ur|t | g tt	d||jdS )Nfilenameglobalslocalsz"rb" )rparenopenreadz'exec'compile exec)prefix)getchildrencloner
   r   r   r	   r   powerr   trailerr   r   r   r   r   extend)selfnoderesultsr   r   r   execfile_paren	open_args	open_callr   	open_exprfilename_argexec_strcompile_argscompile_callargs r,   1/usr/lib/python3.10/lib2to3/fixes/fix_execfile.py	transform   s0   



zFixExecfile.transformN)__name__
__module____qualname__BM_compatiblePATTERNr.   r,   r,   r,   r-   r      s    r   N)__doc__r   r   
fixer_utilr   r   r   r   r   r   r	   r
   r   r   BaseFixr   r,   r,   r,   r-   <module>   s   0PK       ! Vj  j  &  __pycache__/fix_intern.cpython-310.pycnu [        o
    bcx                     @   s6   d Z ddlmZ ddlmZmZ G dd dejZdS )z/Fixer for intern().

intern(s) -> sys.intern(s)   )
fixer_base)ImportAndCalltouch_importc                   @   s    e Zd ZdZdZdZdd ZdS )	FixInternTprez
    power< 'intern'
           trailer< lpar='('
                    ( not(arglist | argument<any '=' any>) obj=any
                      | obj=arglist<(not argument<any '=' any>) any ','> )
                    rpar=')' >
           after=any*
    >
    c                 C   sR   |r|d }|r|j | jjkr|jd jdv rd S d}t|||}td d| |S )Nobj    >   ***)sysinternr   )typesymsargumentchildrenvaluer   r   )selfnoderesultsr   namesnew r   //usr/lib/python3.10/lib2to3/fixes/fix_intern.py	transform   s   zFixIntern.transformN)__name__
__module____qualname__BM_compatibleorderPATTERNr   r   r   r   r   r      s
    
r   N)__doc__ r   
fixer_utilr   r   BaseFixr   r   r   r   r   <module>   s   PK       ! 0    -  __pycache__/fix_standarderror.cpython-310.pycnu [        o
    bc                     @   s2   d Z ddlmZ ddlmZ G dd dejZdS )z%Fixer for StandardError -> Exception.   )
fixer_base)Namec                   @   s   e Zd ZdZdZdd ZdS )FixStandarderrorTz-
              'StandardError'
              c                 C   s   t d|jdS )N	Exception)prefix)r   r   )selfnoderesults r
   6/usr/lib/python3.10/lib2to3/fixes/fix_standarderror.py	transform   s   zFixStandarderror.transformN)__name__
__module____qualname__BM_compatiblePATTERNr   r
   r
   r
   r   r      s    r   N)__doc__ r   
fixer_utilr   BaseFixr   r
   r
   r
   r   <module>   s   PK       ! tk  k  %  __pycache__/fix_paren.cpython-310.pycnu [        o
    bc                     @   s6   d Z ddlmZ ddlmZmZ G dd dejZdS )ztFixer that adds parentheses where they are required

This converts ``[x for x in 1, 2]`` to ``[x for x in (1, 2)]``.   )
fixer_base)LParenRParenc                   @   s   e Zd ZdZdZdd ZdS )FixParenTa  
        atom< ('[' | '(')
            (listmaker< any
                comp_for<
                    'for' NAME 'in'
                    target=testlist_safe< any (',' any)+ [',']
                     >
                    [any]
                >
            >
            |
            testlist_gexp< any
                comp_for<
                    'for' NAME 'in'
                    target=testlist_safe< any (',' any)+ [',']
                     >
                    [any]
                >
            >)
        (']' | ')') >
    c                 C   s8   |d }t  }|j|_d|_|d| |t  d S )Ntarget     )r   prefixinsert_childappend_childr   )selfnoderesultsr   lparen r   ./usr/lib/python3.10/lib2to3/fixes/fix_paren.py	transform%   s   zFixParen.transformN)__name__
__module____qualname__BM_compatiblePATTERNr   r   r   r   r   r      s    r   N)__doc__r   r   
fixer_utilr   r   BaseFixr   r   r   r   r   <module>   s    PK       !     )  __pycache__/fix_funcattrs.cpython-310.pycnu [        o
    bc                     @   s2   d Z ddlmZ ddlmZ G dd dejZdS )z3Fix function attribute names (f.func_x -> f.__x__).   )
fixer_base)Namec                   @   s   e Zd ZdZdZdd ZdS )FixFuncattrsTz
    power< any+ trailer< '.' attr=('func_closure' | 'func_doc' | 'func_globals'
                                  | 'func_name' | 'func_defaults' | 'func_code'
                                  | 'func_dict') > any* >
    c                 C   s2   |d d }| td|jdd   |jd d S )Nattr    z__%s__   )prefix)replacer   valuer   )selfnoderesultsr    r   2/usr/lib/python3.10/lib2to3/fixes/fix_funcattrs.py	transform   s   zFixFuncattrs.transformN)__name__
__module____qualname__BM_compatiblePATTERNr   r   r   r   r   r   	   s    r   N)__doc__ r   
fixer_utilr   BaseFixr   r   r   r   r   <module>   s    PK       ! f%    ,  __pycache__/fix_tuple_params.cpython-310.pycnu [        o
    bc                     @   s   d Z ddlmZ ddlmZ ddlmZ ddlmZmZm	Z	m
Z
mZmZ dd ZG dd	 d	ejZd
d Zdd Zg dfddZdd ZdS )a:  Fixer for function definitions with tuple parameters.

def func(((a, b), c), d):
    ...

    ->

def func(x, d):
    ((a, b), c) = x
    ...

It will also support lambdas:

    lambda (x, y): x + y -> lambda t: t[0] + t[1]

    # The parens are a syntax error in Python 3
    lambda (x): x + y -> lambda x: x + y
   )pytree)token)
fixer_base)AssignNameNewlineNumber	Subscriptsymsc                 C   s   t | tjo| jd jtjkS )N    )
isinstancer   Nodechildrentyper   STRING)stmt r   5/usr/lib/python3.10/lib2to3/fixes/fix_tuple_params.pyis_docstring   s   r   c                   @   s(   e Zd ZdZdZdZdd Zdd ZdS )	FixTupleParams   Ta  
              funcdef< 'def' any parameters< '(' args=any ')' >
                       ['->' any] ':' suite=any+ >
              |
              lambda=
              lambdef< 'lambda' args=vfpdef< '(' inner=any ')' >
                       ':' body=any
              >
              c                    s  d|v r
 ||S g |d }|d }|d jd jtjkr-d}|d jd j}t  nd}d}ttjd d fd
d	}|jt	j
krL|| n|jt	jkrjt|jD ]\}}	|	jt	j
kri||	|dkd qWsnd S D ]}
|d |
_qp|}|dkrdd _nt|d j| r|d _|d }D ]}
|d |
_q|d j||< t|d |t d D ]
}||d j| _q|d   d S )Nlambdasuiteargsr      r   z;  Fc                    s\   t  }|  }d|_t|| }|rd|_| | tt	j
|  g d S )Nr    )r   new_namecloneprefixr   replaceappendr   r   r
   simple_stmt)	tuple_arg
add_prefixnargr   end	new_linesselfr   r   handle_tupleC   s   


z.FixTupleParams.transform.<locals>.handle_tuple)r$   r   )F)transform_lambdar   r   r   INDENTvaluer   r   Leafr
   tfpdeftypedargslist	enumerateparentr   r   rangelenchanged)r*   noderesultsr   r   startindentr+   ir&   lineafterr   r'   r   	transform.   sH   

zFixTupleParams.transformc                 C   s   |d }|d }t |d }|jtjkr"| }d|_|| d S t|}t|}| 	t
|}t|dd}	||	  | D ],}
|
jtjkrn|
j|v rndd ||
j D }ttj|	 g| }|
j|_|
| qBd S )Nr   bodyinnerr   )r   c                 S   s   g | ]}|  qS r   )r   .0cr   r   r   
<listcomp>   s    z3FixTupleParams.transform_lambda.<locals>.<listcomp>)simplify_argsr   r   NAMEr   r   r    find_paramsmap_to_indexr   
tuple_namer   
post_orderr.   r   r   r
   power)r*   r7   r8   r   r?   r@   paramsto_indextup_name	new_paramr%   
subscriptsnewr   r   r   r,   n   s.   

zFixTupleParams.transform_lambdaN)__name__
__module____qualname__	run_orderBM_compatiblePATTERNr>   r,   r   r   r   r   r      s    
@r   c                 C   sT   | j tjtjfv r| S | j tjkr$| j tjkr"| jd } | j tjks| S td|  )Nr   zReceived unexpected node %s)r   r
   vfplistr   rF   vfpdefr   RuntimeErrorr7   r   r   r   rE      s   
rE   c                 C   s<   | j tjkrt| jd S | j tjkr| jS dd | jD S )Nr   c                 S   s    g | ]}|j tjkrt|qS r   )r   r   COMMArG   rA   r   r   r   rD      s     zfind_params.<locals>.<listcomp>)r   r
   rY   rG   r   r   rF   r.   r[   r   r   r   rG      s
   rG   Nc                 C   sZ   |d u ri }t | D ] \}}ttt|g}t|tr$t|||d q
|| ||< q
|S )N)d)r2   r	   r   strr   listrH   )
param_listr   r]   r;   objtrailerr   r   r   rH      s   
rH   c                 C   s<   g }| D ]}t |tr|t| q|| qd|S )N_)r   r_   r!   rI   join)r`   lra   r   r   r   rI      s   

rI   )__doc__r   r   pgen2r   r   
fixer_utilr   r   r   r   r	   r
   r   BaseFixr   rE   rG   rH   rI   r   r   r   r   <module>   s     lPK       ! /m=  =  '  __pycache__/fix_has_key.cpython-310.pycnu [        o
    bc|                     @   sB   d Z ddlmZ ddlmZ ddlmZmZ G dd dejZdS )a&  Fixer for has_key().

Calls to .has_key() methods are expressed in terms of the 'in'
operator:

    d.has_key(k) -> k in d

CAVEATS:
1) While the primary target of this fixer is dict.has_key(), the
   fixer will change any has_key() method call, regardless of its
   class.

2) Cases like this will not be converted:

    m = d.has_key
    if m(k):
        ...

   Only *calls* to has_key() are converted. While it is possible to
   convert the above to something like

    m = d.__contains__
    if m(k):
        ...

   this is currently not done.
   )pytree)
fixer_base)Nameparenthesizec                   @   s   e Zd ZdZdZdd ZdS )	FixHasKeyTa  
    anchor=power<
        before=any+
        trailer< '.' 'has_key' >
        trailer<
            '('
            ( not(arglist | argument<any '=' any>) arg=any
            | arglist<(not argument<any '=' any>) arg=any ','>
            )
            ')'
        >
        after=any*
    >
    |
    negation=not_test<
        'not'
        anchor=power<
            before=any+
            trailer< '.' 'has_key' >
            trailer<
                '('
                ( not(arglist | argument<any '=' any>) arg=any
                | arglist<(not argument<any '=' any>) arg=any ','>
                )
                ')'
            >
        >
    >
    c              
   C   s  |sJ | j }|jj|jkr| j|jrd S |d}|d }|j}dd |d D }|d  }|d}	|	r@dd |	D }	|j|j	|j|j
|j|j|j|jfv rWt|}t|d	krb|d
 }nt|j|}d|_tddd}
|rtddd}t|j||
f}
t|j	||
|f}|	rt|}t|j|ft|	 }|jj|j	|j|j|j|j|j|j|j|jf	v rt|}||_|S )Nnegationanchorc                 S      g | ]}|  qS  clone.0nr
   r
   0/usr/lib/python3.10/lib2to3/fixes/fix_has_key.py
<listcomp>R       z'FixHasKey.transform.<locals>.<listcomp>beforeargafterc                 S   r	   r
   r   r   r
   r
   r   r   V   r           in)prefixnot)symsparenttypenot_testpatternmatchgetr   r   
comparisonand_testor_testtestlambdefargumentr   lenr   Nodepowerr   comp_optupleexprxor_exprand_expr
shift_expr
arith_exprtermfactor)selfnoderesultsr   r   r   r   r   r   r   n_opn_notnewr
   r
   r   	transformG   sL   


zFixHasKey.transformN)__name__
__module____qualname__BM_compatiblePATTERNr;   r
   r
   r
   r   r   &   s    r   N)	__doc__ r   r   
fixer_utilr   r   BaseFixr   r
   r
   r
   r   <module>   s
   PK       ! .    %  __pycache__/fix_throw.cpython-310.pycnu [        o
    bc.                     @   sZ   d Z ddlmZ ddlmZ ddlmZ ddlmZmZm	Z	m
Z
mZ G dd dejZdS )	zFixer for generator.throw(E, V, T).

g.throw(E)       -> g.throw(E)
g.throw(E, V)    -> g.throw(E(V))
g.throw(E, V, T) -> g.throw(E(V).with_traceback(T))

g.throw("foo"[, V[, T]]) will warn about string exceptions.   )pytree)token)
fixer_base)NameCallArgListAttris_tuplec                   @   s   e Zd ZdZdZdd ZdS )FixThrowTz
    power< any trailer< '.' 'throw' >
           trailer< '(' args=arglist< exc=any ',' val=any [',' tb=any] > ')' >
    >
    |
    power< any trailer< '.' 'throw' > trailer< '(' exc=any ')' > >
    c                 C   s   | j }|d  }|jtju r| |d d S |d}|d u r"d S | }t|r7dd |jdd D }nd|_	|g}|d	 }d
|v rl|d
  }d|_	t
||}	t|	tdt|gg }
|t|j|
 d S |t
|| d S )Nexcz+Python 3 does not support string exceptionsvalc                 S   s   g | ]}|  qS  )clone).0cr   r   ./usr/lib/python3.10/lib2to3/fixes/fix_throw.py
<listcomp>)   s    z&FixThrow.transform.<locals>.<listcomp>    argstbwith_traceback)symsr   typer   STRINGcannot_convertgetr	   childrenprefixr   r   r   r   replacer   Nodepower)selfnoderesultsr   r   r   r   
throw_argsr   ewith_tbr   r   r   	transform   s*   

zFixThrow.transformN)__name__
__module____qualname__BM_compatiblePATTERNr)   r   r   r   r   r
      s    r
   N)__doc__r   r   pgen2r   r   
fixer_utilr   r   r   r   r	   BaseFixr
   r   r   r   r   <module>   s    
PK       ! 9?J+  +  #  __pycache__/fix_zip.cpython-310.pycnu [        o
    bc	                     @   sR   d Z ddlmZ ddlmZ ddlmZ ddlm	Z	m
Z
mZ G dd dejZdS )	a7  
Fixer that changes zip(seq0, seq1, ...) into list(zip(seq0, seq1, ...)
unless there exists a 'from future_builtins import zip' statement in the
top-level namespace.

We avoid the transformation if the zip() call is directly contained in
iter(<>), list(<>), tuple(<>), sorted(<>), ...join(<>), or for V in <>:.
   )
fixer_base)Node)python_symbols)NameArgListin_special_contextc                   @   s    e Zd ZdZdZdZdd ZdS )FixZipTzN
    power< 'zip' args=trailer< '(' [any] ')' > [trailers=trailer*]
    >
    zfuture_builtins.zipc                 C   s   |  |rd S t|rd S |d  }d|_g }d|v r-dd |d D }|D ]}d|_q'ttjtd|gdd}ttjtdt|gg| }|j|_|S )	Nargs trailersc                 S   s   g | ]}|  qS  )clone).0nr   r   ,/usr/lib/python3.10/lib2to3/fixes/fix_zip.py
<listcomp>'   s    z$FixZip.transform.<locals>.<listcomp>zip)prefixlist)	should_skipr   r   r   r   symspowerr   r   )selfnoderesultsr	   r   r   newr   r   r   	transform   s   
zFixZip.transformN)__name__
__module____qualname__BM_compatiblePATTERNskip_onr   r   r   r   r   r      s
    r   N)__doc__r
   r   pytreer   pygramr   r   
fixer_utilr   r   r   ConditionalFixr   r   r   r   r   <module>   s    
PK       ! dZ    &  __pycache__/fix_urllib.cpython-310.pycnu [        o
    bc                      @   s   d Z ddlmZmZ ddlmZmZmZmZm	Z	m
Z
mZ dg dfdg dfdd	gfgdg d
fdddgfgdZed ed d  dd ZG dd deZdS )zFix changes imports of urllib which are now incompatible.
   This is rather similar to fix_imports, but because of the more
   complex nature of the fixing for urllib, it has its own fixer.
    )
alternates
FixImports)NameComma
FromImportNewlinefind_indentationNodesymszurllib.request)		URLopenerFancyURLopenerurlretrieve
_urlopenerurlopen
urlcleanuppathname2urlurl2pathname
getproxieszurllib.parse)quote
quote_plusunquoteunquote_plus	urlencode	splitattr	splithost
splitnportsplitpasswd	splitport
splitquerysplittag	splittype	splituser
splitvaluezurllib.errorContentTooShortError)r   install_openerbuild_openerRequestOpenerDirectorBaseHandlerHTTPDefaultErrorHandlerHTTPRedirectHandlerHTTPCookieProcessorProxyHandlerHTTPPasswordMgrHTTPPasswordMgrWithDefaultRealmAbstractBasicAuthHandlerHTTPBasicAuthHandlerProxyBasicAuthHandlerAbstractDigestAuthHandlerHTTPDigestAuthHandlerProxyDigestAuthHandlerHTTPHandlerHTTPSHandlerFileHandler
FTPHandlerCacheFTPHandlerUnknownHandlerURLError	HTTPError)urlliburllib2r>   r=      c                  c   sx    t  } t D ]1\}}|D ]*}|\}}t|}d||f V  d|||f V  d| V  d| V  d||f V  qqd S )Nzimport_name< 'import' (module=%r
                                  | dotted_as_names< any* module=%r any* >) >
                  zimport_from< 'from' mod_member=%r 'import'
                       ( member=%s | import_as_name< member=%s 'as' any > |
                         import_as_names< members=any*  >) >
                  zIimport_from< 'from' module_star=%r 'import' star='*' >
                  ztimport_name< 'import'
                                  dotted_as_name< module_as=%r 'as' any > >
                  zKpower< bare_with_attr=%r trailer< '.' member=%s > any* >
                  )setMAPPINGitemsr   )bare
old_modulechangeschange
new_modulemembers rI   //usr/lib/python3.10/lib2to3/fixes/fix_urllib.pybuild_pattern0   s.   rK   c                   @   s4   e Zd Zdd Zdd Zdd Zdd Zd	d
 ZdS )	FixUrllibc                 C   s   d t S )N|)joinrK   )selfrI   rI   rJ   rK   I   s   zFixUrllib.build_patternc                 C   sv   | d}|j}g }t|j dd D ]}|t|d |dt g q|tt|j d d |d || dS )zTransform for the basic import case. Replaces the old
           import name with a comma separated list of its
           replacements.
        moduleNr   prefix)	getrS   rA   valueextendr   r   appendreplace)rO   noderesults
import_modprefnamesnamerI   rI   rJ   transform_importL   s   
 zFixUrllib.transform_importc                 C   s  | d}|j}| d}|rDt|tr|d }d}t|j D ]}|j|d v r.|d } nq|r<|t||d dS | |d dS g }i }	|d }
|
D ]D}|j	t
jkrc|jd	 j}|jd j}n|j}d}|d
krt|j D ] }||d v r|d |	vr||d  |	|d g | qqqNg }t|}d}dd }|D ]A}|	| }g }|dd D ]}|||| |t  q|||d | t||}|r|jj|r||_|| d}q|rg }|dd D ]
}||t g q||d  || dS | |d dS )zTransform for imports of specific module elements. Replaces
           the module to be imported from with the appropriate new
           module.
        
mod_membermemberr   Nr?   rR   !This is an invalid module elementrH      ,Tc                 S   sX   | j tjkr$t| jd j|d| jd  | jd  g}ttj|gS t| j|dgS )Nr   rR   r?   rc   )typer
   import_as_namer   childrenrU   cloner	   )r^   rS   kidsrI   rI   rJ   handle_name   s   z/FixUrllib.transform_member.<locals>.handle_namerQ   FzAll module elements are invalid)rT   rS   
isinstancelistrA   rU   rX   r   cannot_convertre   r
   rf   rg   rW   
setdefaultr   rV   r   r   parentendswithr   )rO   rY   rZ   r`   r\   ra   new_namerF   modulesmod_dictrH   as_namemember_name	new_nodesindentationfirstrj   rP   eltsr]   eltnewnodesnew_noderI   rI   rJ   transform_member\   sl   




zFixUrllib.transform_memberc                 C   s   | d}| d}d}t|tr|d }t|j D ]}|j|d v r)|d } nq|r8|t||jd dS | |d dS )z.Transform for calls to module members in code.bare_with_attrra   Nr   r?   rR   rb   )	rT   rk   rl   rA   rU   rX   r   rS   rm   )rO   rY   rZ   
module_dotra   rq   rF   rI   rI   rJ   transform_dot   s   


zFixUrllib.transform_dotc                 C   s   | dr| || d S | dr| || d S | dr'| || d S | dr4| |d d S | drA| |d d S d S )NrP   r`   r   module_starzCannot handle star imports.	module_asz#This module is now multiple modules)rT   r_   r~   r   rm   )rO   rY   rZ   rI   rI   rJ   	transform   s   




zFixUrllib.transformN)__name__
__module____qualname__rK   r_   r~   r   r   rI   rI   rI   rJ   rL   G   s    LrL   N)__doc__lib2to3.fixes.fix_importsr   r   lib2to3.fixer_utilr   r   r   r   r   r	   r
   rA   rW   rK   rL   rI   rI   rI   rJ   <module>   s0    $!PK       ! Z    %  __pycache__/fix_types.cpython-310.pycnu [        o
    bc                     @   s   d Z ddlmZ ddlmZ i dddddd	d
dddddddddddddddddddddddd d!d"d#d$d	d%d&d'Zd(d) eD ZG d*d+ d+ejZd,S )-a  Fixer for removing uses of the types module.

These work for only the known names in the types module.  The forms above
can include types. or not.  ie, It is assumed the module is imported either as:

    import types
    from types import ... # either * or specific types

The import statements are not modified.

There should be another fixer that handles at least the following constants:

   type([]) -> list
   type(()) -> tuple
   type('') -> str

   )
fixer_base)NameBooleanTypebool
BufferType
memoryview	ClassTypetypeComplexTypecomplexDictTypedictDictionaryTypeEllipsisTypeztype(Ellipsis)	FloatTypefloatIntTypeintListTypelistLongType
ObjectTypeobjectNoneTypez
type(None)NotImplementedTypeztype(NotImplemented)	SliceTypeslice
StringTypebytesStringTypesz(str,)tuplestrrange)	TupleTypeTypeTypeUnicodeType
XRangeTypec                 C   s   g | ]}d | qS )z)power< 'types' trailer< '.' name='%s' > > ).0tr'   r'   ./usr/lib/python3.10/lib2to3/fixes/fix_types.py
<listcomp>3   s    r+   c                   @   s"   e Zd ZdZdeZdd ZdS )FixTypesT|c                 C   s&   t |d j}|rt||jdS d S )Nname)prefix)_TYPE_MAPPINGgetvaluer   r/   )selfnoderesults	new_valuer'   r'   r*   	transform9   s   zFixTypes.transformN)__name__
__module____qualname__BM_compatiblejoin_patsPATTERNr7   r'   r'   r'   r*   r,   5   s    
r,   N)	__doc__ r   
fixer_utilr   r0   r=   BaseFixr,   r'   r'   r'   r*   <module>   sZ   	
PK       !       (  __pycache__/fix_imports2.cpython-310.pycnu [        o
    bc!                     @   s0   d Z ddlmZ dddZG dd dejZdS )zTFix incompatible imports and module references that must be fixed after
fix_imports.   )fix_importsdbm)whichdbanydbmc                   @   s   e Zd ZdZeZdS )FixImports2   N)__name__
__module____qualname__	run_orderMAPPINGmapping r   r   1/usr/lib/python3.10/lib2to3/fixes/fix_imports2.pyr      s    r   N)__doc__ r   r   
FixImportsr   r   r   r   r   <module>   s    PK       ! MA  A  &  __pycache__/fix_idioms.cpython-310.pycnu [        o
    bc                     @   sN   d Z ddlmZ ddlmZmZmZmZmZm	Z	 dZ
dZG dd dejZdS )	a  Adjust some old Python 2 idioms to their modern counterparts.

* Change some type comparisons to isinstance() calls:
    type(x) == T -> isinstance(x, T)
    type(x) is T -> isinstance(x, T)
    type(x) != T -> not isinstance(x, T)
    type(x) is not T -> not isinstance(x, T)

* Change "while 1:" into "while True:".

* Change both

    v = list(EXPR)
    v.sort()
    foo(v)

and the more general

    v = EXPR
    v.sort()
    foo(v)

into

    v = sorted(EXPR)
    foo(v)
   )
fixer_base)CallCommaNameNode	BlankLinesymsz0(n='!=' | '==' | 'is' | n=comp_op< 'is' 'not' >)z(power< 'type' trailer< '(' x=any ')' > >c                       sP   e Zd ZdZdeeeef Z fddZdd Zdd Z	d	d
 Z
dd Z  ZS )	FixIdiomsTa  
        isinstance=comparison< %s %s T=any >
        |
        isinstance=comparison< T=any %s %s >
        |
        while_stmt< 'while' while='1' ':' any+ >
        |
        sorted=any<
            any*
            simple_stmt<
              expr_stmt< id1=any '='
                         power< list='list' trailer< '(' (not arglist<any+>) any ')' > >
              >
              '\n'
            >
            sort=
            simple_stmt<
              power< id2=any
                     trailer< '.' 'sort' > trailer< '(' ')' >
              >
              '\n'
            >
            next=any*
        >
        |
        sorted=any<
            any*
            simple_stmt< expr_stmt< id1=any '=' expr=any > '\n' >
            sort=
            simple_stmt<
              power< id2=any
                     trailer< '.' 'sort' > trailer< '(' ')' >
              >
              '\n'
            >
            next=any*
        >
    c                    s8   t t| |}|rd|v r|d |d kr|S d S |S )Nsortedid1id2)superr	   match)selfnoder	__class__ //usr/lib/python3.10/lib2to3/fixes/fix_idioms.pyr   O   s   zFixIdioms.matchc                 C   sD   d|v r
|  ||S d|v r| ||S d|v r| ||S td)N
isinstancewhiler
   zInvalid match)transform_isinstancetransform_whiletransform_sortRuntimeError)r   r   resultsr   r   r   	transformZ   s   zFixIdioms.transformc                 C   sh   |d   }|d   }d|_d|_ttd|t |g}d|v r.d|_ttjtd|g}|j|_|S )NxT  r   nnot)cloneprefixr   r   r   r   r   not_test)r   r   r   r   r   testr   r   r   r   d   s   zFixIdioms.transform_isinstancec                 C   s    |d }| td|jd d S )Nr   Truer%   )replacer   r%   )r   r   r   oner   r   r   r   p   s   zFixIdioms.transform_whilec                 C   s  |d }|d }| d}| d}|r|td|jd n|r7| }d|_|ttd|g|jd ntd|  |j}d	|v r|r^|d	d
 |d
 jf}	d		|	|d
 _d S |j
scJ |jd u sjJ t }
|j
|
 |j|
u szJ |d	d
 |
_d S d S )Nsortnextlistexprr
   r)   r    zshould not have reached here
    )getr*   r   r%   r$   r   r   remove
rpartitionjoinparentnext_siblingr   append_child)r   r   r   	sort_stmt	next_stmt	list_callsimple_exprnewbtwnprefix_linesend_liner   r   r   r   t   s4   



zFixIdioms.transform_sort)__name__
__module____qualname__explicitTYPECMPPATTERNr   r   r   r   r   __classcell__r   r   r   r   r	   %   s    
%'
r	   N)__doc__r    r   
fixer_utilr   r   r   r   r   r   rF   rE   BaseFixr	   r   r   r   r   <module>   s     PK       !     )  __pycache__/fix_raw_input.cpython-310.pycnu [        o
    bc                     @   s2   d Z ddlmZ ddlmZ G dd dejZdS )z2Fixer that changes raw_input(...) into input(...).   )
fixer_base)Namec                   @   s   e Zd ZdZdZdd ZdS )FixRawInputTzU
              power< name='raw_input' trailer< '(' [any] ')' > any* >
              c                 C   s    |d }| td|jd d S )Nnameinput)prefix)replacer   r   )selfnoderesultsr    r   2/usr/lib/python3.10/lib2to3/fixes/fix_raw_input.py	transform   s   zFixRawInput.transformN)__name__
__module____qualname__BM_compatiblePATTERNr   r   r   r   r   r      s    r   N)__doc__ r   
fixer_utilr   BaseFixr   r   r   r   r   <module>   s    PK       ! خ
  
  &  __pycache__/fix_except.cpython-310.pycnu [        o
    bc                     @   sf   d Z ddlmZ ddlmZ ddlmZ ddlmZmZm	Z	m
Z
mZmZ dd ZG dd	 d	ejZd
S )a  Fixer for except statements with named exceptions.

The following cases will be converted:

- "except E, T:" where T is a name:

    except E as T:

- "except E, T:" where T is not a name, tuple or list:

        except E as t:
            T = t

    This is done because the target of an "except" clause must be a
    name.

- "except E, T:" where T is a tuple or list literal:

        except E as t:
            T = t.args
   )pytree)token)
fixer_base)AssignAttrNameis_tupleis_listsymsc                 c   sF    t | D ]\}}|jtjkr |jd jdkr || |d  fV  qd S )N    exceptr   )	enumeratetyper
   except_clausechildrenvalue)nodesin r   //usr/lib/python3.10/lib2to3/fixes/fix_except.pyfind_excepts   s   r   c                   @   s   e Zd ZdZdZdd ZdS )	FixExceptTa1  
    try_stmt< 'try' ':' (simple_stmt | suite)
                  cleanup=(except_clause ':' (simple_stmt | suite))+
                  tail=(['except' ':' (simple_stmt | suite)]
                        ['else' ':' (simple_stmt | suite)]
                        ['finally' ':' (simple_stmt | suite)]) >
    c                 C   sr  | j }dd |d D }dd |d D }t|D ]\}}t|jdkr|jdd \}}	}
|	tdd	d
 |
jtjkrt| 	 d	d
}|

 }d|_|
| |
 }|j}t|D ]\}}t|tjrh nq\t|
sqt|
r|t|t|td}nt||}t|d | D ]}|d| q||| q|
jdkrd	|
_qdd |jd d D | | }t|j|S )Nc                 S      g | ]}|  qS r   clone).0r   r   r   r   
<listcomp>2       z'FixExcept.transform.<locals>.<listcomp>tailc                 S   r   r   r   )r   chr   r   r   r   4   r   cleanup      as )prefix argsr   c                 S   r   r   r   )r   cr   r   r   r   \   r      )r
   r   lenr   replacer   r   r   NAMEnew_namer   r&   r   
isinstancer   Noder   r	   r   r   reversedinsert_child)selfnoderesultsr
   r   try_cleanupr   e_suiteEcommaNnew_Ntargetsuite_stmtsr   stmtassignchildr   r   r   r   	transform/   s:   


 zFixExcept.transformN)__name__
__module____qualname__BM_compatiblePATTERNrA   r   r   r   r   r   $   s    r   N)__doc__r'   r   pgen2r   r   
fixer_utilr   r   r   r   r	   r
   r   BaseFixr   r   r   r   r   <module>   s     PK       ! !YAK  K  $  __pycache__/fix_repr.cpython-310.pycnu [        o
    bce                     @   s:   d Z ddlmZ ddlmZmZmZ G dd dejZdS )z/Fixer that transforms `xyzzy` into repr(xyzzy).   )
fixer_base)CallNameparenthesizec                   @   s   e Zd ZdZdZdd ZdS )FixReprTz7
              atom < '`' expr=any '`' >
              c                 C   s8   |d   }|j| jjkrt|}ttd|g|jdS )Nexprrepr)prefix)clonetypesyms	testlist1r   r   r   r	   )selfnoderesultsr    r   -/usr/lib/python3.10/lib2to3/fixes/fix_repr.py	transform   s   zFixRepr.transformN)__name__
__module____qualname__BM_compatiblePATTERNr   r   r   r   r   r      s    r   N)	__doc__ r   
fixer_utilr   r   r   BaseFixr   r   r   r   r   <module>   s   PK       ! .O    +  __pycache__/fix_methodattrs.cpython-310.pycnu [        o
    bc^                     @   s>   d Z ddlmZ ddlmZ ddddZG dd	 d	ejZd
S )z;Fix bound method attributes (method.im_? -> method.__?__).
   )
fixer_base)Name__func____self__z__self__.__class__)im_funcim_selfim_classc                   @   s   e Zd ZdZdZdd ZdS )FixMethodattrsTzU
    power< any+ trailer< '.' attr=('im_func' | 'im_self' | 'im_class') > any* >
    c                 C   s.   |d d }t |j }|t||jd d S )Nattr    )prefix)MAPvaluereplacer   r   )selfnoderesultsr
   new r   4/usr/lib/python3.10/lib2to3/fixes/fix_methodattrs.py	transform   s   
zFixMethodattrs.transformN)__name__
__module____qualname__BM_compatiblePATTERNr   r   r   r   r   r	      s    r	   N)__doc__ r   
fixer_utilr   r   BaseFixr	   r   r   r   r   <module>   s    PK       !     '  __pycache__/fix_sys_exc.cpython-310.pycnu [        o
    bc
                     @   sJ   d Z ddlmZ ddlmZmZmZmZmZm	Z	m
Z
 G dd dejZdS )zFixer for sys.exc_{type, value, traceback}

sys.exc_type -> sys.exc_info()[0]
sys.exc_value -> sys.exc_info()[1]
sys.exc_traceback -> sys.exc_info()[2]
   )
fixer_base)AttrCallNameNumber	SubscriptNodesymsc                   @   s8   e Zd Zg dZdZdddd eD  Zdd Zd	S )
	FixSysExc)exc_type	exc_valueexc_tracebackTzN
              power< 'sys' trailer< dot='.' attribute=(%s) > >
              |c                 c   s    | ]}d | V  qdS )z'%s'N ).0er   r   0/usr/lib/python3.10/lib2to3/fixes/fix_sys_exc.py	<genexpr>   s    zFixSysExc.<genexpr>c                 C   st   |d d }t | j|j}ttd|jd}ttd|}|d j|d jd _|	t
| ttj||jdS )N	attribute    exc_info)prefixsysdot   )r   r   indexvaluer   r   r   r   childrenappendr   r   r	   power)selfnoderesultssys_attrr   callattrr   r   r   	transform   s   zFixSysExc.transformN)__name__
__module____qualname__r   BM_compatiblejoinPATTERNr&   r   r   r   r   r
      s    r
   N)__doc__ r   
fixer_utilr   r   r   r   r   r   r	   BaseFixr
   r   r   r   r   <module>   s    
$PK       ! /G    )  __pycache__/fix_metaclass.cpython-310.pycnu [        o
    bc                      @   sv   d Z ddlmZ ddlmZ ddlmZmZmZ dd Z	dd Z
d	d
 Zdd Zdd Zdd ZG dd dejZdS )a  Fixer for __metaclass__ = X -> (metaclass=X) methods.

   The various forms of classef (inherits nothing, inherits once, inherits
   many) don't parse the same in the CST so we look at ALL classes for
   a __metaclass__ and if we find one normalize the inherits to all be
   an arglist.

   For one-liner classes ('class X: pass') there is no indent/dedent so
   we normalize those into having a suite.

   Moving the __metaclass__ into the classdef can also cause the class
   body to be empty so there is some special casing for that as well.

   This fixer also tries very hard to keep original indenting and spacing
   in all those corner cases.

   )
fixer_base)token)symsNodeLeafc                 C   sz   | j D ]7}|jtjkrt|  S |jtjkr:|j r:|j d }|jtjkr:|j r:|j d }t|tr:|j	dkr: dS qdS )z we have to check the cls_node without changing it.
        There are two possibilities:
          1)  clsdef => suite => simple_stmt => expr_stmt => Leaf('__meta')
          2)  clsdef => simple_stmt => expr_stmt => Leaf('__meta')
        __metaclass__TF)
childrentyper   suitehas_metaclasssimple_stmt	expr_stmt
isinstancer   value)parentnode	expr_node	left_side r   2/usr/lib/python3.10/lib2to3/fixes/fix_metaclass.pyr      s   




r   c                 C   s   | j D ]}|jtjkr dS qt| j D ]\}}|jtjkr  nqtdttjg }| j |d d rO| j |d  }|	|
  |  | j |d d s4| 	| |}dS )zf one-line classes don't get a suite in the parse tree so we add
        one to normalize the tree
    NzNo class suite and no ':'!   )r	   r
   r   r   	enumerater   COLON
ValueErrorr   append_childcloneremove)cls_noder   ir   	move_noder   r   r   fixup_parse_tree-   s"   

r!   c           
      C   s   t |jD ]\}}|jtjkr nqdS |  ttjg }ttj	|g}|j|d rC|j| }|
|  |  |j|d s,| || |jd jd }|jd jd }	|	j|_dS )z if there is a semi-colon all the parts count as part of the same
        simple_stmt.  We just want the __metaclass__ part so we move
        everything after the semi-colon into its own simple_stmt node
    Nr   )r   r	   r
   r   SEMIr   r   r   r   r   r   r   insert_childprefix)
r   r   	stmt_nodesemi_indr   new_exprnew_stmtr    	new_leaf1	old_leaf1r   r   r   fixup_simple_stmtG   s"   
r+   c                 C   s2   | j r| j d jtjkr| j d   d S d S d S )N)r	   r
   r   NEWLINEr   )r   r   r   r   remove_trailing_newline_   s   r.   c                 c   s    | j D ]
}|jtjkr nqtdtt|j D ]:\}}|jtjkrT|j rT|j d }|jtjkrT|j rT|j d }t	|t
rT|jdkrTt||| t| |||fV  qd S )NzNo class suite!r   r   )r	   r
   r   r   r   listr   r   r   r   r   r   r+   r.   )r   r   r   simple_noder   	left_noder   r   r   
find_metasd   s$   




r2   c                 C   s   | j ddd }|r| }|jtjkrn|s
|r?| }t|tr0|jtjkr0|jr.d|_dS |	|j ddd  |sdS dS )z If an INDENT is followed by a thing with a prefix then nuke the prefix
        Otherwise we get in trouble when removing __metaclass__ at suite start
    Nr,    )
r	   popr
   r   INDENTr   r   DEDENTr$   extend)r   kidsr   r   r   r   fixup_indent{   s   r9   c                   @   s   e Zd ZdZdZdd ZdS )FixMetaclassTz
    classdef<any*>
    c                 C   sP  t |sd S t| d }t|D ]\}}}|}|  q|jd j}t|jdkrM|jd jtjkr8|jd }nU|jd 	 }	t
tj|	g}|d| n@t|jdkrat
tjg }|d| n,t|jdkrt
tjg }|dttjd |d| |dttjd ntd	|jd jd }
d
|
_|
j}|jr|ttjd d|
_nd|
_|jd }|jtjksJ d|jd _d|jd _|| t| |js|  t|d}||_|| |ttjd d S t|jdkr"|jd jtjkr$|jd jtjkr&t|d}|d| |dttjd d S d S d S d S )Nr               r   )(zUnexpected class definition	metaclass, r3   r   pass
r,   )r   r!   r2   r   r	   r
   lenr   arglistr   r   	set_childr#   r   r   RPARLPARr   r   r$   r   COMMAr   r9   r-   r5   r6   )selfr   resultslast_metaclassr   r   stmt	text_typerH   r   meta_txtorig_meta_prefixr   	pass_leafr   r   r   	transform   sf   





zFixMetaclass.transformN)__name__
__module____qualname__BM_compatiblePATTERNrU   r   r   r   r   r:      s    r:   N)__doc__r3   r   pygramr   
fixer_utilr   r   r   r   r!   r+   r.   r2   r9   BaseFixr:   r   r   r   r   <module>   s    PK       ! 3f  f  &  __pycache__/fix_reduce.cpython-310.pycnu [        o
    bcE                     @   s2   d Z ddlmZ ddlmZ G dd dejZdS )zqFixer for reduce().

Makes sure reduce() is imported from the functools module if reduce is
used in that module.
    )
fixer_basetouch_importc                   @   s    e Zd ZdZdZdZdd ZdS )	FixReduceTpreai  
    power< 'reduce'
        trailer< '('
            arglist< (
                (not(argument<any '=' any>) any ','
                 not(argument<any '=' any>) any) |
                (not(argument<any '=' any>) any ','
                 not(argument<any '=' any>) any ','
                 not(argument<any '=' any>) any)
            ) >
        ')' >
    >
    c                 C   s   t dd| d S )N	functoolsreducer   )selfnoderesults r   //usr/lib/python3.10/lib2to3/fixes/fix_reduce.py	transform"   s   zFixReduce.transformN)__name__
__module____qualname__BM_compatibleorderPATTERNr   r   r   r   r   r      s
    r   N)__doc__lib2to3r   lib2to3.fixer_utilr   BaseFixr   r   r   r   r   <module>   s   PK       ! 
  
  )  __pycache__/fix_itertools.cpython-310.pycnu [        o
    bc                     @   s2   d Z ddlmZ ddlmZ G dd dejZdS )aT   Fixer for itertools.(imap|ifilter|izip) --> (map|filter|zip) and
    itertools.ifilterfalse --> itertools.filterfalse (bugs 2360-2363)

    imports from itertools are fixed in fix_itertools_import.py

    If itertools is imported as something else (ie: import itertools as it;
    it.izip(spam, eggs)) method calls will not get fixed.
       )
fixer_base)Namec                   @   s*   e Zd ZdZdZde  ZdZdd ZdS )FixItertoolsTz7('imap'|'ifilter'|'izip'|'izip_longest'|'ifilterfalse')z
              power< it='itertools'
                  trailer<
                     dot='.' func=%(it_funcs)s > trailer< '(' [any] ')' > >
              |
              power< func=%(it_funcs)s trailer< '(' [any] ')' > >
                 c                 C   s   d }|d d }d|v r+|j dvr+|d |d }}|j}|  |  |j| |p/|j}|t|j dd  |d d S )Nfunc    it)ifilterfalseizip_longestdot   )prefix)valuer   removeparentreplacer   )selfnoderesultsr   r   r   r    r   2/usr/lib/python3.10/lib2to3/fixes/fix_itertools.py	transform   s   

 zFixItertools.transformN)	__name__
__module____qualname__BM_compatibleit_funcslocalsPATTERN	run_orderr   r   r   r   r   r      s    	r   N)__doc__ r   
fixer_utilr   BaseFixr   r   r   r   r   <module>   s    
PK       ! #
  
  &  __pycache__/fix_import.cpython-310.pycnu [        o
    bc                     @   sZ   d Z ddlmZ ddlmZmZmZmZ ddlm	Z	m
Z
mZ dd ZG dd	 d	ejZd
S )zFixer for import statements.
If spam is being imported from the local directory, this import:
    from spam import eggs
Becomes:
    from .spam import eggs

And this import:
    import spam
Becomes:
    from . import spam
   )
fixer_base    )dirnamejoinexistssep)
FromImportsymstokenc                 c   s    | g}|rQ|  }|jtjkr|jV  n8|jtjkr(ddd |jD V  n%|jtj	kr7|
|jd  n|jtjkrI||jddd  ntd|sdS dS )zF
    Walks over all the names imported in a dotted_as_names node.
     c                 S   s   g | ]}|j qS  )value).0chr   r   //usr/lib/python3.10/lib2to3/fixes/fix_import.py
<listcomp>   s    z$traverse_imports.<locals>.<listcomp>r   Nzunknown node type)poptyper
   NAMEr   r	   dotted_namer   childrendotted_as_nameappenddotted_as_namesextendAssertionError)namespendingnoder   r   r   traverse_imports   s   
r    c                       s4   e Zd ZdZdZ fddZdd Zdd Z  ZS )		FixImportTzj
    import_from< 'from' imp=any 'import' ['('] any [')'] >
    |
    import_name< 'import' imp=any >
    c                    s"   t t| || d|jv | _d S )Nabsolute_import)superr!   
start_treefuture_featuresskip)selftreename	__class__r   r   r$   /   s   zFixImport.start_treec                 C   s   | j rd S |d }|jtjkr2t|ds|jd }t|dr| |jr0d|j |_|  d S d S d}d}t	|D ]}| |rDd}q:d}q:|rS|rQ| 
|d d S td|g}|j|_|S )Nimpr   r   .FTz#absolute and local imports together)r&   r   r	   import_fromhasattrr   probably_a_local_importr   changedr    warningr   prefix)r'   r   resultsr,   
have_localhave_absolutemod_namenewr   r   r   	transform3   s0   



zFixImport.transformc                 C   st   | drdS |ddd }t| j}t||}ttt|ds$dS dtddd	d
fD ]}t|| r7 dS q,dS )Nr-   F   r   z__init__.pyz.pyz.pycz.soz.slz.pydT)
startswithsplitr   filenamer   r   r   )r'   imp_name	base_pathextr   r   r   r0   U   s   


z!FixImport.probably_a_local_import)	__name__
__module____qualname__BM_compatiblePATTERNr$   r9   r0   __classcell__r   r   r*   r   r!   &   s    "r!   N)__doc__r   r   os.pathr   r   r   r   
fixer_utilr   r	   r
   r    BaseFixr!   r   r   r   r   <module>   s    PK       ! c]  ]  (  __pycache__/fix_ws_comma.cpython-310.pycnu [        o
    bcB                     @   s>   d Z ddlmZ ddlmZ ddlmZ G dd dejZdS )zFixer that changes 'a ,b' into 'a, b'.

This also changes '{a :b}' into '{a: b}', but does not touch other
uses of colons.  It does not touch other uses of whitespace.

   )pytree)token)
fixer_basec                   @   s@   e Zd ZdZdZeejdZeej	dZ	ee	fZ
dd ZdS )
FixWsCommaTzH
    any<(not(',') any)+ ',' ((not(',') any)+ ',')* [not(',') any]>
    ,:c                 C   s`   |  }d}|jD ]$}|| jv r!|j}| rd|vrd|_d}q	|r+|j}|s+d|_d}q	|S )NF
 T )clonechildrenSEPSprefixisspace)selfnoderesultsnewcommachildr    r   1/usr/lib/python3.10/lib2to3/fixes/fix_ws_comma.py	transform   s   

zFixWsComma.transformN)__name__
__module____qualname__explicitPATTERNr   Leafr   COMMACOLONr   r   r   r   r   r   r      s    r   N)__doc__r	   r   pgen2r   r   BaseFixr   r   r   r   r   <module>   s
    PK       ! .    +  __pycache__/fix_numliterals.cpython-310.pycnu [        o
    bc                      @   s>   d Z ddlmZ ddlmZ ddlmZ G dd dejZdS )z-Fixer that turns 1L into 1, 0755 into 0o755.
   )token)
fixer_base)Numberc                   @   s"   e Zd ZejZdd Zdd ZdS )FixNumliteralsc                 C   s   |j dp|j d dv S )N0Ll)value
startswith)selfnode r   4/usr/lib/python3.10/lib2to3/fixes/fix_numliterals.pymatch   s   zFixNumliterals.matchc                 C   s`   |j }|d dv r|d d }n|dr)| r)tt|dkr)d|dd   }t||jdS )Nr   r   r      0o)prefix)r	   r
   isdigitlensetr   r   )r   r   resultsvalr   r   r   	transform   s   "zFixNumliterals.transformN)__name__
__module____qualname__r   NUMBER_accept_typer   r   r   r   r   r   r      s    r   N)	__doc__pgen2r    r   
fixer_utilr   BaseFixr   r   r   r   r   <module>   s
    PK       ! 1    '  __pycache__/fix_renames.cpython-310.pycnu [        o
    bc                     @   sV   d Z ddlmZ ddlmZmZ dddiiZi Zdd Zd	d
 Z	G dd dej
ZdS )z?Fix incompatible renames

Fixes:
  * sys.maxint -> sys.maxsize
   )
fixer_base)Name
attr_chainsysmaxintmaxsizec                 C   s   dd tt|  d S )N(|))joinmaprepr)members r   0/usr/lib/python3.10/lib2to3/fixes/fix_renames.py
alternates   s   r   c                  c   s\    t t D ]$\} }t | D ]\}}|t| |f< d| ||f V  d| |f V  qqd S )Nz
                  import_from< 'from' module_name=%r 'import'
                      ( attr_name=%r | import_as_name< attr_name=%r 'as' any >) >
                  z^
                  power< module_name=%r trailer< '.' attr_name=%r > any* >
                  )listMAPPINGitemsLOOKUP)modulereplaceold_attrnew_attrr   r   r   build_pattern   s   r   c                       s8   e Zd ZdZde ZdZ fddZdd Z	  Z
S )
FixRenamesTr	   prec                    s@   t t| j  |}|rt fddt|dD rdS |S dS )Nc                 3   s    | ]} |V  qd S )Nr   ).0objmatchr   r   	<genexpr>5   s    z#FixRenames.match.<locals>.<genexpr>parentF)superr   r    anyr   )selfnoderesults	__class__r   r   r    1   s   zFixRenames.matchc                 C   sL   | d}| d}|r"|r$t|j|jf }|t||jd d S d S d S )Nmodule_name	attr_name)prefix)getr   valuer   r   r,   )r%   r&   r'   mod_namer+   r   r   r   r   	transform>   s   

zFixRenames.transform)__name__
__module____qualname__BM_compatibler   r   PATTERNorderr    r0   __classcell__r   r   r(   r   r   *   s    r   N)__doc__ r   
fixer_utilr   r   r   r   r   r   BaseFixr   r   r   r   r   <module>   s    	PK       ! #msv  v  &  __pycache__/fix_reload.cpython-310.pycnu [        o
    bc9                     @   s6   d Z ddlmZ ddlmZmZ G dd dejZdS )z5Fixer for reload().

reload(s) -> importlib.reload(s)   )
fixer_base)ImportAndCalltouch_importc                   @   s    e Zd ZdZdZdZdd ZdS )	FixReloadTprez
    power< 'reload'
           trailer< lpar='('
                    ( not(arglist | argument<any '=' any>) obj=any
                      | obj=arglist<(not argument<any '=' any>) any ','> )
                    rpar=')' >
           after=any*
    >
    c                 C   sR   |r|d }|r|j | jjkr|jd jdv rd S d}t|||}td d| |S )Nobj    >   ***)	importlibreloadr   )typesymsargumentchildrenvaluer   r   )selfnoderesultsr   namesnew r   //usr/lib/python3.10/lib2to3/fixes/fix_reload.py	transform   s   zFixReload.transformN)__name__
__module____qualname__BM_compatibleorderPATTERNr   r   r   r   r   r   
   s
    
r   N)__doc__ r   
fixer_utilr   r   BaseFixr   r   r   r   r   <module>   s    PK       ! fYJ    *  __pycache__/fix_isinstance.cpython-310.pycnu [        o
    bcH                     @   s2   d Z ddlmZ ddlmZ G dd dejZdS )a,  Fixer that cleans up a tuple argument to isinstance after the tokens
in it were fixed.  This is mainly used to remove double occurrences of
tokens as a leftover of the long -> int / unicode -> str conversion.

eg.  isinstance(x, (int, long)) -> isinstance(x, (int, int))
       -> isinstance(x, int)
   )
fixer_base)tokenc                   @   s    e Zd ZdZdZdZdd ZdS )FixIsinstanceTz
    power<
        'isinstance'
        trailer< '(' arglist< any ',' atom< '('
            args=testlist_gexp< any+ >
        ')' > > ')' >
    >
       c                 C   s   t  }|d }|j}g }t|}|D ]8\}}	|	jtjkr9|	j|v r9|t|d k r8||d  jtjkr8t	| qq|
|	 |	jtjkrJ||	j q|rX|d jtjkrX|d= t|dkrp|j}
|
j|d _|
|d  d S ||d d < |  d S )Nargs       )setchildren	enumeratetyper   NAMEvaluelenCOMMAnextappendaddparentprefixreplacechanged)selfnoderesultsnames_insertedtestlistr   new_argsiteratoridxargatom r#   3/usr/lib/python3.10/lib2to3/fixes/fix_isinstance.py	transform   s.   $
zFixIsinstance.transformN)__name__
__module____qualname__BM_compatiblePATTERN	run_orderr%   r#   r#   r#   r$   r      s
    	r   N)__doc__ r   
fixer_utilr   BaseFixr   r#   r#   r#   r$   <module>   s   PK       ! Xx    +  __pycache__/fix_set_literal.cpython-310.pycnu [        o
    bc                     @   s:   d Z ddlmZmZ ddlmZmZ G dd dejZdS )z:
Optional fixer to transform set() calls to set literals.
    )
fixer_basepytree)tokensymsc                   @   s    e Zd ZdZdZdZdd ZdS )FixSetLiteralTaj  power< 'set' trailer< '('
                     (atom=atom< '[' (items=listmaker< any ((',' any)* [',']) >
                                |
                                single=any) ']' >
                     |
                     atom< '(' items=testlist_gexp< any ((',' any)* [',']) > ')' >
                     )
                     ')' > >
              c           	      C   s   | d}|rttj| g}|| |}n|d }ttj	dg}|
dd |jD  |ttjd |jj|d _ttj|}|j|_t|jdkrc|jd	 }|  |j|jd _|S )
Nsingleitems{c                 s   s    | ]}|  V  qd S )N)clone).0n r   4/usr/lib/python3.10/lib2to3/fixes/fix_set_literal.py	<genexpr>'   s    z*FixSetLiteral.transform.<locals>.<genexpr>}      )getr   Noder   	listmakerr
   replaceLeafr   LBRACEextendchildrenappendRBRACEnext_siblingprefixdictsetmakerlenremove)	selfnoderesultsr   faker   literalmakerr   r   r   r   	transform   s"   


zFixSetLiteral.transformN)__name__
__module____qualname__BM_compatibleexplicitPATTERNr)   r   r   r   r   r      s
    
r   N)	__doc__lib2to3r   r   lib2to3.fixer_utilr   r   BaseFixr   r   r   r   r   <module>   s    PK       ! % ٕ    *  __pycache__/fix_basestring.cpython-310.pycnu [        o
    bc@                     @   s2   d Z ddlmZ ddlmZ G dd dejZdS )zFixer for basestring -> str.   )
fixer_base)Namec                   @   s   e Zd ZdZdZdd ZdS )FixBasestringTz'basestring'c                 C   s   t d|jdS )Nstr)prefix)r   r   )selfnoderesults r
   3/usr/lib/python3.10/lib2to3/fixes/fix_basestring.py	transform   s   zFixBasestring.transformN)__name__
__module____qualname__BM_compatiblePATTERNr   r
   r
   r
   r   r      s    r   N)__doc__ r   
fixer_utilr   BaseFixr   r
   r
   r
   r   <module>   s    PK       ! DJT    #  __pycache__/fix_map.cpython-310.pycnu [        o
    bc8                     @   sf   d Z ddlmZ ddlmZ ddlmZmZmZm	Z	m
Z
 ddlmZ ddlmZ G dd dejZd	S )
a  Fixer that changes map(F, ...) into list(map(F, ...)) unless there
exists a 'from future_builtins import map' statement in the top-level
namespace.

As a special case, map(None, X) is changed into list(X).  (This is
necessary because the semantics are changed in this case -- the new
map(None, X) is equivalent to [(x,) for x in X].)

We avoid the transformation (except for the special case mentioned
above) if the map() call is directly contained in iter(<>), list(<>),
tuple(<>), sorted(<>), ...join(<>), or for V in <>:.

NOTE: This is still not correct if the original code was depending on
map(F, X, Y, ...) to go on until the longest argument is exhausted,
substituting None for missing values -- like zip(), it now stops as
soon as the shortest argument is exhausted.
   )token)
fixer_base)NameArgListCallListCompin_special_context)python_symbols)Nodec                   @   s    e Zd ZdZdZdZdd ZdS )FixMapTaL  
    map_none=power<
        'map'
        trailer< '(' arglist< 'None' ',' arg=any [','] > ')' >
        [extra_trailers=trailer*]
    >
    |
    map_lambda=power<
        'map'
        trailer<
            '('
            arglist<
                lambdef< 'lambda'
                         (fp=NAME | vfpdef< '(' fp=NAME ')'> ) ':' xp=any
                >
                ','
                it=any
            >
            ')'
        >
        [extra_trailers=trailer*]
    >
    |
    power<
        'map' args=trailer< '(' [any] ')' >
        [extra_trailers=trailer*]
    >
    zfuture_builtins.mapc                 C   s  |  |rd S g }d|v r|d D ]	}||  q|jjtjkr8| |d | }d|_t	t
d|g}nd|v rZt|d  |d  |d  }ttj|g| dd	}nkd
|v rh|d  }d|_nKd|v r|d }|jtjkr|jd jtjkr|jd jd jtjkr|jd jd jdkr| |d d S ttjt
d| g}d|_t|rd S ttjt
dt|gg| }d|_|j|_|S )Nextra_trailerszYou should use a for loop here list
map_lambdaxpfpit)prefixmap_noneargargs       Nonezjcannot convert map(None, ...) with multiple arguments because map() now truncates to the shortest sequencemap)should_skipappendcloneparenttypesymssimple_stmtwarningr   r   r   r   r
   powertrailerchildrenarglistr   NAMEvaluer   r   )selfnoderesultstrailerstnewr    r/   ,/usr/lib/python3.10/lib2to3/fixes/fix_map.py	transform@   sH   


zFixMap.transformN)__name__
__module____qualname__BM_compatiblePATTERNskip_onr1   r/   r/   r/   r0   r      s
    r   N)__doc__pgen2r   r   r   
fixer_utilr   r   r   r   r   pygramr	   r    pytreer
   ConditionalFixr   r/   r/   r/   r0   <module>   s   PK       ! ?    '  __pycache__/fix_getcwdu.cpython-310.pycnu [        o
    bc                     @   s2   d Z ddlmZ ddlmZ G dd dejZdS )z1
Fixer that changes os.getcwdu() to os.getcwd().
   )
fixer_base)Namec                   @   s   e Zd ZdZdZdd ZdS )
FixGetcwduTzR
              power< 'os' trailer< dot='.' name='getcwdu' > any* >
              c                 C   s    |d }| td|jd d S )Nnamegetcwd)prefix)replacer   r   )selfnoderesultsr    r   0/usr/lib/python3.10/lib2to3/fixes/fix_getcwdu.py	transform   s   zFixGetcwdu.transformN)__name__
__module____qualname__BM_compatiblePATTERNr   r   r   r   r   r   
   s    r   N)__doc__ r   
fixer_utilr   BaseFixr   r   r   r   r   <module>   s    PK       ! E1    %  __pycache__/fix_input.cpython-310.pycnu [        o
    bc                     @   sL   d Z ddlmZ ddlmZmZ ddlmZ edZG dd dej	Z
dS )	z4Fixer that changes input(...) into eval(input(...)).   )
fixer_base)CallName)patcompz&power< 'eval' trailer< '(' any ')' > >c                   @   s   e Zd ZdZdZdd ZdS )FixInputTzL
              power< 'input' args=trailer< '(' [any] ')' > >
              c                 C   s6   t |jjr	d S | }d|_ttd|g|jdS )N eval)prefix)contextmatchparentcloner	   r   r   )selfnoderesultsnew r   ./usr/lib/python3.10/lib2to3/fixes/fix_input.py	transform   s
   zFixInput.transformN)__name__
__module____qualname__BM_compatiblePATTERNr   r   r   r   r   r      s    r   N)__doc__r   r   
fixer_utilr   r   r   compile_patternr
   BaseFixr   r   r   r   r   <module>   s    
PK       ! gy    $  __pycache__/fix_dict.cpython-310.pycnu [        o
    bc                     @   sj   d Z ddlmZ ddlmZ ddlmZ ddlmZmZmZ ddlmZ ej	dhB Z
G dd	 d	ejZd
S )aj  Fixer for dict methods.

d.keys() -> list(d.keys())
d.items() -> list(d.items())
d.values() -> list(d.values())

d.iterkeys() -> iter(d.keys())
d.iteritems() -> iter(d.items())
d.itervalues() -> iter(d.values())

d.viewkeys() -> d.keys()
d.viewitems() -> d.items()
d.viewvalues() -> d.values()

Except in certain very specific contexts: the iter() can be dropped
when the context is list(), sorted(), iter() or for...in; the list()
can be dropped when the context is list() or sorted() (but not iter()
or for...in!). Special contexts that apply to both: list(), sorted(), tuple()
set(), any(), all(), sum().

Note: iter(d.keys()) could be written as iter(d) but since the
original d.iterkeys() was also redundant we don't fix this.  And there
are (rare) contexts where it makes a difference (e.g. when passing it
as an argument to a function that introspects the argument).
   )pytree)patcomp)
fixer_base)NameCallDot)
fixer_utiliterc                   @   s@   e Zd ZdZdZdd ZdZeeZ	dZ
ee
Zdd Zd	S )
FixDictTa  
    power< head=any+
         trailer< '.' method=('keys'|'items'|'values'|
                              'iterkeys'|'iteritems'|'itervalues'|
                              'viewkeys'|'viewitems'|'viewvalues') >
         parens=trailer< '(' ')' >
         tail=any*
    >
    c              	   C   s  |d }|d d }|d }| j }|j}|d}|d}	|s"|	r(|dd  }|dv s2J t|d	d
 |D }dd
 |D }| oH| ||}
|t|jt t	||j
dg|d  g }t|j|}|
sz|	szd|_
tt	|rtdnd|g}|rt|j|g| }|j
|_
|S )Nheadmethod    tailr	   view   )keysitemsvaluesc                 S      g | ]}|  qS  clone.0nr   r   -/usr/lib/python3.10/lib2to3/fixes/fix_dict.py
<listcomp>A       z%FixDict.transform.<locals>.<listcomp>c                 S   r   r   r   r   r   r   r   r   B   r   )prefixparens list)symsvalue
startswithreprin_special_contextr   Nodetrailerr   r   r   r   powerr   )selfnoderesultsr   r   r   r"   method_nameisiterisviewspecialargsnewr   r   r   	transform6   s<   



zFixDict.transformz3power< func=NAME trailer< '(' node=any ')' > any* >zmfor_stmt< 'for' any 'in' node=any ':' any* >
            | comp_for< 'for' any 'in' node=any any* >
         c                 C   s   |j d u rdS i }|j j d ur/| j|j j |r/|d |u r/|r'|d jtv S |d jtjv S |s3dS | j|j |o@|d |u S )NFr+   func)parentp1matchr#   iter_exemptr   consuming_callsp2)r*   r+   r.   r,   r   r   r   r&   Z   s   
zFixDict.in_special_contextN)__name__
__module____qualname__BM_compatiblePATTERNr3   P1r   compile_patternr6   P2r:   r&   r   r   r   r   r
   )   s    


r
   N)__doc__r    r   r   r   r   r   r   r   r9   r8   BaseFixr
   r   r   r   r   <module>   s   PK         ! =n  n                  fix_raise.pynu [        PK         ! 5Y
  
                fix_filter.pynu [        PK         ! 誔*	  *	                fix_apply.pynu [        PK         ! %TW68  8  
               fix_map.pynu [        PK         ! iG                .  fix_long.pynu [        PK         ! ʿ>1                0  fix_paren.pynu [        PK         ! Z6                5  fix_print.pynu [        PK         ! ޽                A  fix_standarderror.pynu [        PK         ! N2E                C  fix_xreadlines.pynu [        PK         ! HgH  H              E  fix_isinstance.pynu [        PK         ! I
  
              L  fix_sys_exc.pynu [        PK         ! ?O  O              P  fix_nonzero.pynu [        PK         ! )x  x              VS  fix_intern.pynu [        PK         ! ds                X  fix_dict.pynu [        PK         ! 2ۭ                f  fix_renames.pynu [        PK         ! :                o  fix_exec.pynu [        PK         ! )E  E              s  fix_reduce.pynu [        PK         ! _ \                qw  fix_idioms.pynu [        PK         ! &                  fix_unicode.pynu [        PK         ! IkNf  f                fix_next.pynu [        PK         ! >ӵ;&  &                fix_itertools_imports.pynu [        PK         ! +&^  ^                fix_methodattrs.pynu [        PK         ! Gg                  fix_itertools.pynu [        PK         ! 6u                ۭ  fix_raw_input.pynu [        PK         ! Y                    fix_metaclass.pynu [        PK         ! F                &  fix_funcattrs.pynu [        PK         ! p2I                  fix_except.pynu [        PK         ! 7h#  #              7  fix_future.pynu [        PK         ! |4  4                fix_imports.pynu [        PK         !  2Ϳ	  	              	  fix_exitfunc.pynu [        PK         ! JbB  B               fix_ws_comma.pynu [        PK         ! M1	  	  
             fix_zip.pynu [        PK         ! E[/   /                __init__.pynu [        PK         ! DIu|  |              5 fix_has_key.pynu [        PK         ! r39  9               fix_reload.pynu [        PK         ! fϡ                e fix_set_literal.pynu [        PK         ! S                H% fix_types.pynu [        PK         ! ?k                r, fix_getcwdu.pynu [        PK         ! lH                  s. fix_numliterals.pynu [        PK         ! {Wk                  1 fix_execfile.pynu [        PK         ! N  N              9 fix_buffer.pynu [        PK         ! a.e  e              < fix_repr.pynu [        PK         ! M@  @              ? fix_basestring.pynu [        PK         ! =                @ fix_asserts.pynu [        PK         ! 6ng                D fix_import.pynu [        PK         !                   Q fix_urllib.pynu [        PK         ! C
  
              r fix_xrange.pynu [        PK         ! xu.  .              Z} fix_throw.pynu [        PK         ! ܬ'!  !              ă fix_imports2.pynu [        PK         ! q|                $ fix_input.pynu [        PK         ! |b  b              $ fix_operator.pynu [        PK         ! O+                ŕ fix_tuple_params.pynu [        PK         ! <;  ;  	            ū fix_ne.pynu [        PK         ! &  &  &            9 __pycache__/fix_buffer.cpython-310.pycnu [        PK         ! Κ    '             __pycache__/fix_nonzero.cpython-310.pycnu [        PK         ! #    '             __pycache__/fix_unicode.cpython-310.pycnu [        PK         ! 4ǹl	  	  &             __pycache__/fix_filter.cpython-310.pycnu [        PK         ! Bk    '             __pycache__/fix_asserts.cpython-310.pycnu [        PK         ! 0p    $            ? __pycache__/fix_next.cpython-310.pycnu [        PK         ! ُr&8  8  (             __pycache__/fix_operator.cpython-310.pycnu [        PK         ! 1    '            ( __pycache__/fix_imports.cpython-310.pycnu [        PK         ! "#	  	  %             __pycache__/fix_print.cpython-310.pycnu [        PK         ! 4*t  t  %             __pycache__/fix_apply.cpython-310.pycnu [        PK         ! _    %            
 __pycache__/fix_raise.cpython-310.pycnu [        PK         ! a  a  *             __pycache__/fix_xreadlines.cpython-310.pycnu [        PK         ! Ɂ	  	  (             __pycache__/fix_exitfunc.cpython-310.pycnu [        PK         ! \    &            ! __pycache__/fix_future.cpython-310.pycnu [        PK         ! #b    1            L% __pycache__/fix_itertools_imports.cpython-310.pycnu [        PK         ! dk  k  $            + __pycache__/fix_exec.cpython-310.pycnu [        PK         ! gWM    $            0 __pycache__/fix_long.cpython-310.pycnu [        PK         ! ͗<	  	  &            3 __pycache__/fix_xrange.cpython-310.pycnu [        PK         ! V)  )  "            = __pycache__/fix_ne.cpython-310.pycnu [        PK         ! hMm      $            SA __pycache__/__init__.cpython-310.pycnu [        PK         ! ^    (            1B __pycache__/fix_execfile.cpython-310.pycnu [        PK         ! Vj  j  &            I __pycache__/fix_intern.cpython-310.pycnu [        PK         ! 0    -            M __pycache__/fix_standarderror.cpython-310.pycnu [        PK         ! tk  k  %            Q __pycache__/fix_paren.cpython-310.pycnu [        PK         !     )            V __pycache__/fix_funcattrs.cpython-310.pycnu [        PK         ! f%    ,            Z __pycache__/fix_tuple_params.cpython-310.pycnu [        PK         ! /m=  =  '            1m __pycache__/fix_has_key.cpython-310.pycnu [        PK         ! .    %            x __pycache__/fix_throw.cpython-310.pycnu [        PK         ! 9?J+  +  #            ( __pycache__/fix_zip.cpython-310.pycnu [        PK         ! dZ    &             __pycache__/fix_urllib.cpython-310.pycnu [        PK         ! Z    %             __pycache__/fix_types.cpython-310.pycnu [        PK         !       (            ޥ __pycache__/fix_imports2.cpython-310.pycnu [        PK         ! MA  A  &            V __pycache__/fix_idioms.cpython-310.pycnu [        PK         !     )             __pycache__/fix_raw_input.cpython-310.pycnu [        PK         ! خ
  
  &            _ __pycache__/fix_except.cpython-310.pycnu [        PK         ! !YAK  K  $             __pycache__/fix_repr.cpython-310.pycnu [        PK         ! .O    +            ( __pycache__/fix_methodattrs.cpython-310.pycnu [        PK         !     '            + __pycache__/fix_sys_exc.cpython-310.pycnu [        PK         ! /G    )             __pycache__/fix_metaclass.cpython-310.pycnu [        PK         ! 3f  f  &            { __pycache__/fix_reduce.cpython-310.pycnu [        PK         ! 
  
  )            7 __pycache__/fix_itertools.cpython-310.pycnu [        PK         ! #
  
  &             __pycache__/fix_import.cpython-310.pycnu [        PK         ! c]  ]  (             __pycache__/fix_ws_comma.cpython-310.pycnu [        PK         ! .    +             __pycache__/fix_numliterals.cpython-310.pycnu [        PK         ! 1    '             __pycache__/fix_renames.cpython-310.pycnu [        PK         ! #msv  v  &            8 __pycache__/fix_reload.cpython-310.pycnu [        PK         ! fYJ    *             __pycache__/fix_isinstance.cpython-310.pycnu [        PK         ! Xx    +            q __pycache__/fix_set_literal.cpython-310.pycnu [        PK         ! % ٕ    *            _# __pycache__/fix_basestring.cpython-310.pycnu [        PK         ! DJT    #            N& __pycache__/fix_map.cpython-310.pycnu [        PK         ! ?    '            2 __pycache__/fix_getcwdu.cpython-310.pycnu [        PK         ! E1    %            6 __pycache__/fix_input.cpython-310.pycnu [        PK         ! gy    $            : __pycache__/fix_dict.cpython-310.pycnu [        PK    j j w%  AG