PageRenderTime 1113ms CodeModel.GetById 811ms app.highlight 5ms RepoModel.GetById 165ms app.codeStats 0ms

/Lib/lib2to3/fixes/fix_renames.py

http://unladen-swallow.googlecode.com/
Python | 69 lines | 49 code | 5 blank | 15 comment | 4 complexity | 52f66737c4206d8cfa77bbb07af4a056 MD5 | raw file
 1"""Fix incompatible renames
 2
 3Fixes:
 4  * sys.maxint -> sys.maxsize
 5"""
 6# Author: Christian Heimes
 7# based on Collin Winter's fix_import
 8
 9# Local imports
10from .. import fixer_base
11from ..fixer_util import Name, attr_chain
12
13MAPPING = {"sys":  {"maxint" : "maxsize"},
14          }
15LOOKUP = {}
16
17def alternates(members):
18    return "(" + "|".join(map(repr, members)) + ")"
19
20
21def build_pattern():
22    #bare = set()
23    for module, replace in MAPPING.items():
24        for old_attr, new_attr in replace.items():
25            LOOKUP[(module, old_attr)] = new_attr
26            #bare.add(module)
27            #bare.add(old_attr)
28            #yield """
29            #      import_name< 'import' (module=%r
30            #          | dotted_as_names< any* module=%r any* >) >
31            #      """ % (module, module)
32            yield """
33                  import_from< 'from' module_name=%r 'import'
34                      ( attr_name=%r | import_as_name< attr_name=%r 'as' any >) >
35                  """ % (module, old_attr, old_attr)
36            yield """
37                  power< module_name=%r trailer< '.' attr_name=%r > any* >
38                  """ % (module, old_attr)
39    #yield """bare_name=%s""" % alternates(bare)
40
41
42class FixRenames(fixer_base.BaseFix):
43    PATTERN = "|".join(build_pattern())
44
45    order = "pre" # Pre-order tree traversal
46
47    # Don't match the node if it's within another match
48    def match(self, node):
49        match = super(FixRenames, self).match
50        results = match(node)
51        if results:
52            if any([match(obj) for obj in attr_chain(node, "parent")]):
53                return False
54            return results
55        return False
56
57    #def start_tree(self, tree, filename):
58    #    super(FixRenames, self).start_tree(tree, filename)
59    #    self.replace = {}
60
61    def transform(self, node, results):
62        mod_name = results.get("module_name")
63        attr_name = results.get("attr_name")
64        #bare_name = results.get("bare_name")
65        #import_mod = results.get("module")
66
67        if mod_name and attr_name:
68            new_attr = LOOKUP[(mod_name.value, attr_name.value)]
69            attr_name.replace(Name(new_attr, prefix=attr_name.get_prefix()))