blob: c361e6139345a05cc5207073201d867b30746007 [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()
27 options = None # Options object passed to initializer
28 filename = None # The filename (set by set_filename)
29 logger = None # A logger (set by set_filename)
30 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.
Martin v. Löwisef04c442008-03-19 05:04:44 +000036
37 # Shortcut for access to Python grammar symbols
38 syms = pygram.python_symbols
39
40 def __init__(self, options, log):
41 """Initializer. Subclass may override.
42
43 Args:
Benjamin Peterson8951b612008-09-03 02:27:16 +000044 options: an dict containing the options passed to RefactoringTool
45 that could be used to customize the fixer through the command line.
Martin v. Löwisef04c442008-03-19 05:04:44 +000046 log: a list to append warnings and other messages to.
47 """
48 self.options = options
49 self.log = log
50 self.compile_pattern()
51
52 def compile_pattern(self):
53 """Compiles self.PATTERN into self.pattern.
54
55 Subclass may override if it doesn't want to use
56 self.{pattern,PATTERN} in .match().
57 """
58 if self.PATTERN is not None:
59 self.pattern = PatternCompiler().compile_pattern(self.PATTERN)
60
61 def set_filename(self, filename):
62 """Set the filename, and a logger derived from it.
63
64 The main refactoring tool should call this.
65 """
66 self.filename = filename
67 self.logger = logging.getLogger(filename)
68
69 def match(self, node):
70 """Returns match for a given parse tree node.
71
72 Should return a true or false object (not necessarily a bool).
73 It may return a non-empty dict of matching sub-nodes as
74 returned by a matching pattern.
75
76 Subclass may override.
77 """
78 results = {"node": node}
79 return self.pattern.match(node, results) and results
80
81 def transform(self, node, results):
82 """Returns the transformation for a given parse tree node.
83
84 Args:
85 node: the root of the parse tree that matched the fixer.
86 results: a dict mapping symbolic names to part of the match.
Martin v. Löwisf733c602008-03-19 05:26:18 +000087
Martin v. Löwisef04c442008-03-19 05:04:44 +000088 Returns:
89 None, or a node that is a modified copy of the
90 argument node. The node argument may also be modified in-place to
91 effect the same change.
92
93 Subclass *must* override.
94 """
95 raise NotImplementedError()
96
Martin v. Löwisef04c442008-03-19 05:04:44 +000097 def new_name(self, template="xxx_todo_changeme"):
98 """Return a string suitable for use as an identifier
99
100 The new name is guaranteed not to conflict with other identifiers.
101 """
102 name = template
103 while name in self.used_names:
Martin v. Löwis8a5f8ca2008-03-19 05:33:36 +0000104 name = template + str(next(self.numbers))
Martin v. Löwisef04c442008-03-19 05:04:44 +0000105 self.used_names.add(name)
106 return name
107
108 def log_message(self, message):
109 if self.first_log:
110 self.first_log = False
111 self.log.append("### In file %s ###" % self.filename)
112 self.log.append(message)
113
114 def cannot_convert(self, node, reason=None):
115 """Warn the user that a given chunk of code is not valid Python 3,
116 but that it cannot be converted automatically.
117
118 First argument is the top-level node for the code in question.
119 Optional second argument is why it can't be converted.
120 """
121 lineno = node.get_lineno()
122 for_output = node.clone()
Benjamin Peterson2c3ac6b2009-06-11 23:47:38 +0000123 for_output.prefix = ""
Martin v. Löwisef04c442008-03-19 05:04:44 +0000124 msg = "Line %d: could not convert: %s"
125 self.log_message(msg % (lineno, for_output))
126 if reason:
127 self.log_message(reason)
128
129 def warning(self, node, reason):
130 """Used for warning the user about possible uncertainty in the
131 translation.
132
133 First argument is the top-level node for the code in question.
134 Optional second argument is why it can't be converted.
135 """
136 lineno = node.get_lineno()
137 self.log_message("Line %d: %s" % (lineno, reason))
138
139 def start_tree(self, tree, filename):
140 """Some fixers need to maintain tree-wide state.
141 This method is called once, at the start of tree fix-up.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000142
Martin v. Löwisef04c442008-03-19 05:04:44 +0000143 tree - the root node of the tree to be processed.
144 filename - the name of the file the tree came from.
145 """
146 self.used_names = tree.used_names
147 self.set_filename(filename)
148 self.numbers = itertools.count(1)
149 self.first_log = True
150
151 def finish_tree(self, tree, filename):
152 """Some fixers need to maintain tree-wide state.
153 This method is called once, at the conclusion of tree fix-up.
Martin v. Löwisf733c602008-03-19 05:26:18 +0000154
Martin v. Löwisef04c442008-03-19 05:04:44 +0000155 tree - the root node of the tree to be processed.
156 filename - the name of the file the tree came from.
157 """
158 pass
Martin v. Löwis3faa84f2008-03-22 00:07:09 +0000159
160
161class ConditionalFix(BaseFix):
162 """ Base class for fixers which not execute if an import is found. """
163
164 # This is the name of the import which, if found, will cause the test to be skipped
165 skip_on = None
166
167 def start_tree(self, *args):
168 super(ConditionalFix, self).start_tree(*args)
169 self._should_skip = None
170
171 def should_skip(self, node):
172 if self._should_skip is not None:
173 return self._should_skip
174 pkg = self.skip_on.split(".")
175 name = pkg[-1]
176 pkg = ".".join(pkg[:-1])
177 self._should_skip = does_tree_import(pkg, name, node)
178 return self._should_skip