home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / lib / python2.6 / lib2to3 / fixer_base.py < prev    next >
Encoding:
Python Source  |  2009-04-18  |  6.1 KB  |  179 lines

  1. # 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
  7. import logging
  8. import itertools
  9.  
  10. # Local imports
  11. from .patcomp import PatternCompiler
  12. from . import pygram
  13. from .fixer_util import does_tree_import
  14.  
  15. class 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?
  34.     run_order = 5   # Fixers will be sorted by run order before execution
  35.                     # Lower numbers will be run first.
  36.  
  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:
  44.             options: an dict containing the options passed to RefactoringTool
  45.             that could be used to customize the fixer through the command line.
  46.             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.
  87.  
  88.         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.  
  97.     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:
  104.             name = template + str(self.numbers.next())
  105.         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()
  123.         for_output.set_prefix("")
  124.         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.
  142.  
  143.         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.
  154.  
  155.         tree - the root node of the tree to be processed.
  156.         filename - the name of the file the tree came from.
  157.         """
  158.         pass
  159.  
  160.  
  161. class 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
  179.