blob: b1760561996ed1d8fada89afaacfd66eeaa2d090 [file] [log] [blame]
Martin v. Löwisef04c442008-03-19 05:04:44 +00001# Copyright 2006 Google, Inc. All Rights Reserved.
2# Licensed to PSF under a Contributor Agreement.
3
4"""Base class for fixers (optional, but recommended)."""
5
6# Python imports
7import logging
8import itertools
9
Martin v. Löwisef04c442008-03-19 05:04:44 +000010# Local imports
Benjamin Petersondf6dc8f2008-06-15 02:57:40 +000011from .patcomp import PatternCompiler
12from . import pygram
13from .fixer_util import does_tree_import
Martin v. Löwisef04c442008-03-19 05:04:44 +000014
15class BaseFix(object):
16
17 """Optional base class for fixers.
18
19 The subclass name must be FixFooBar where FooBar is the result of
20 removing underscores and capitalizing the words of the fix name.
21 For example, the class name for a fixer named 'has_key' should be
22 FixHasKey.
23 """
24
25 PATTERN = None # Most subclasses should override with a string literal
26 pattern = None # Compiled pattern, set by compile_pattern()
Benjamin Petersonf37eb3a2010-10-14 23:00:04 +000027 pattern_tree = None # Tree representation of the pattern
Martin v. Löwisef04c442008-03-19 05:04:44 +000028 options = None # Options object passed to initializer
29 filename = None # The filename (set by set_filename)
Martin v. Löwisef04c442008-03-19 05:04:44 +000030 numbers = itertools.count(1) # For new_name()
31 used_names = set() # A set of all used NAMEs
32 order = "post" # Does the fixer prefer pre- or post-order traversal
33 explicit = False # Is this ignored by refactor.py -f all?
Martin v. Löwis3faa84f2008-03-22 00:07:09 +000034 run_order = 5 # Fixers will be sorted by run order before execution
35 # Lower numbers will be run first.
Benjamin Peterson3059b002009-07-20 16:42:03 +000036 _accept_type = None # [Advanced and not public] This tells RefactoringTool
37 # which node type to accept when there's not a pattern.
Martin v. Löwisef04c442008-03-19 05:04:44 +000038
Benjamin Petersonf37eb3a2010-10-14 23:00:04 +000039 keep_line_order = False # For the bottom matcher: match with the
40 # original line order
41 BM_compatible = False # Compatibility with the bottom matching
42 # module; every fixer should set this
43 # manually
44
Martin v. Löwisef04c442008-03-19 05:04:44 +000045 # Shortcut for access to Python grammar symbols
46 syms = pygram.python_symbols
47
48 def __init__(self, options, log):
49 """Initializer. Subclass may override.
50
51 Args:
Benjamin Peterson8951b612008-09-03 02:27:16 +000052 options: an dict containing the options passed to RefactoringTool
53 that could be used to customize the fixer through the command line.
Martin v. Löwisef04c442008-03-19 05:04:44 +000054 log: a list to append warnings and other messages to.
55 """
56 self.options = options
57 self.log = log
58 self.compile_pattern()
59
60 def compile_pattern(self):
61 """Compiles self.PATTERN into self.pattern.
62
63 Subclass may override if it doesn't want to use
64 self.{pattern,PATTERN} in .match().
65 """
66 if self.PATTERN is not None:
Benjamin Petersonf37eb3a2010-10-14 23:00:04 +000067 PC = PatternCompiler()
68 self.pattern, self.pattern_tree = PC.compile_pattern(self.PATTERN,
69 with_tree=True)
Martin v. Löwisef04c442008-03-19 05:04:44 +000070
71 def set_filename(self, filename):
Vinay Sajipbf9c0212011-07-13 23:15:07 +010072 """Set the filename.
Martin v. Löwisef04c442008-03-19 05:04:44 +000073
74 The main refactoring tool should call this.
75 """
76 self.filename = filename
Martin v. Löwisef04c442008-03-19 05:04:44 +000077
78 def match(self, node):
79 """Returns match for a given parse tree node.
80
81 Should return a true or false object (not necessarily a bool).
82 It may return a non-empty dict of matching sub-nodes as
83 returned by a matching pattern.
84
85 Subclass may override.
86 """
87 results = {"node": node}
88 return self.pattern.match(node, results) and results
89
90 def transform(self, node, results):
91 """Returns the transformation for a given parse tree node.
92
93 Args:
94 node: the root of the parse tree that matched the fixer.
95 results: a dict mapping symbolic names to part of the match.
Martin v. Löwisf733c602008-03-19 05:26:18 +000096
Martin v. Löwisef04c442008-03-19 05:04:44 +000097 Returns:
98 None, or a node that is a modified copy of the
99 argument node. The node argument may also be modified in-place to
100 effect the same change.
101
102 Subclass *must* override.
103 """
104 raise NotImplementedError()
105
Martin v. Löwisef04c442008-03-19 05:04:44 +0000106 def new_name(self, template="xxx_todo_changeme"):
107 """Return a string suitable for use as an identifier
108
109 The new name is guaranteed not to conflict with other identifiers.
110 """
111 name = template
112 while name in self.used_names:
Martin v. Löwis8a5f8ca2008-03-19 05:33:36 +0000113 name = template + str(next(self.numbers))
Martin v. Löwisef04c442008-03-19 05:04:44 +0000114 self.used_names.add(name)
115 return name
116
117 def log_message(self, message):
118 if self.first_log:
119 self.first_log = False
120 self.log.append("### In file %s ###" % self.filename)
121 self.log.append(message)
122
123 def cannot_convert(self, node, reason=None):
124 """Warn the user that a given chunk of code is not valid Python 3,
125 but that it cannot be converted automatically.
126
127 First argument is the top-level node for the code in question.
128 Optional second argument is why it can't be converted.
129 """
130 lineno = node.get_lineno()
131 for_output = node.clone()
Benjamin Peterson2c3ac6b2009-06-11 23:47:38 +0000132 for_output.prefix = ""
Martin v. Löwisef04c442008-03-19 05:04:44 +0000133 msg = "Line %d: could not convert: %s"
134 self.log_message(msg % (lineno, for_output))
135 if reason:
136 self.log_message(reason)
137
138 def warning(self, node, reason):
139 """Used for warning the user about possible uncertainty in the
140 translation.
141
142 First argument is the top-level node for the code in question.
143 Optional second argument is why it can't be converted.
144 """
145 lineno = node.get_lineno()
146 self.log_message("Line %d: %s" % (lineno, reason))
147
148 def start_tree(self, tree, filename):
149 """Some fixers need to maintain tree-wide state.
150 This method is called once, at the start of tree fix-up.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000151
Martin v. Löwisef04c442008-03-19 05:04:44 +0000152 tree - the root node of the tree to be processed.
153 filename - the name of the file the tree came from.
154 """
155 self.used_names = tree.used_names
156 self.set_filename(filename)
157 self.numbers = itertools.count(1)
158 self.first_log = True
159
160 def finish_tree(self, tree, filename):
161 """Some fixers need to maintain tree-wide state.
162 This method is called once, at the conclusion of tree fix-up.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000163
Martin v. Löwisef04c442008-03-19 05:04:44 +0000164 tree - the root node of the tree to be processed.
165 filename - the name of the file the tree came from.
166 """
167 pass
Martin v. Löwis3faa84f2008-03-22 00:07:09 +0000168
169
170class ConditionalFix(BaseFix):
171 """ Base class for fixers which not execute if an import is found. """
172
173 # This is the name of the import which, if found, will cause the test to be skipped
174 skip_on = None
175
176 def start_tree(self, *args):
177 super(ConditionalFix, self).start_tree(*args)
178 self._should_skip = None
179
180 def should_skip(self, node):
181 if self._should_skip is not None:
182 return self._should_skip
183 pkg = self.skip_on.split(".")
184 name = pkg[-1]
185 pkg = ".".join(pkg[:-1])
186 self._should_skip = does_tree_import(pkg, name, node)
187 return self._should_skip