home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / lib / python2.6 / lib2to3 / fixer_util.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-04-20  |  14.1 KB  |  463 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Utility functions, node construction macros, etc.'''
  5. from pgen2 import token
  6. from pytree import Leaf, Node
  7. from pygram import python_symbols as syms
  8. from  import patcomp
  9.  
  10. def KeywordArg(keyword, value):
  11.     return Node(syms.argument, [
  12.         keyword,
  13.         Leaf(token.EQUAL, '='),
  14.         value])
  15.  
  16.  
  17. def LParen():
  18.     return Leaf(token.LPAR, '(')
  19.  
  20.  
  21. def RParen():
  22.     return Leaf(token.RPAR, ')')
  23.  
  24.  
  25. def Assign(target, source):
  26.     '''Build an assignment statement'''
  27.     if not isinstance(target, list):
  28.         target = [
  29.             target]
  30.     
  31.     if not isinstance(source, list):
  32.         source.set_prefix(' ')
  33.         source = [
  34.             source]
  35.     
  36.     return Node(syms.atom, target + [
  37.         Leaf(token.EQUAL, '=', prefix = ' ')] + source)
  38.  
  39.  
  40. def Name(name, prefix = None):
  41.     '''Return a NAME leaf'''
  42.     return Leaf(token.NAME, name, prefix = prefix)
  43.  
  44.  
  45. def Attr(obj, attr):
  46.     '''A node tuple for obj.attr'''
  47.     return [
  48.         obj,
  49.         Node(syms.trailer, [
  50.             Dot(),
  51.             attr])]
  52.  
  53.  
  54. def Comma():
  55.     '''A comma leaf'''
  56.     return Leaf(token.COMMA, ',')
  57.  
  58.  
  59. def Dot():
  60.     '''A period (.) leaf'''
  61.     return Leaf(token.DOT, '.')
  62.  
  63.  
  64. def ArgList(args, lparen = LParen(), rparen = RParen()):
  65.     '''A parenthesised argument list, used by Call()'''
  66.     node = Node(syms.trailer, [
  67.         lparen.clone(),
  68.         rparen.clone()])
  69.     if args:
  70.         node.insert_child(1, Node(syms.arglist, args))
  71.     
  72.     return node
  73.  
  74.  
  75. def Call(func_name, args = None, prefix = None):
  76.     '''A function call'''
  77.     node = Node(syms.power, [
  78.         func_name,
  79.         ArgList(args)])
  80.     if prefix is not None:
  81.         node.set_prefix(prefix)
  82.     
  83.     return node
  84.  
  85.  
  86. def Newline():
  87.     '''A newline literal'''
  88.     return Leaf(token.NEWLINE, '\n')
  89.  
  90.  
  91. def BlankLine():
  92.     '''A blank line'''
  93.     return Leaf(token.NEWLINE, '')
  94.  
  95.  
  96. def Number(n, prefix = None):
  97.     return Leaf(token.NUMBER, n, prefix = prefix)
  98.  
  99.  
  100. def Subscript(index_node):
  101.     '''A numeric or string subscript'''
  102.     return Node(syms.trailer, [
  103.         Leaf(token.LBRACE, '['),
  104.         index_node,
  105.         Leaf(token.RBRACE, ']')])
  106.  
  107.  
  108. def String(string, prefix = None):
  109.     '''A string leaf'''
  110.     return Leaf(token.STRING, string, prefix = prefix)
  111.  
  112.  
  113. def ListComp(xp, fp, it, test = None):
  114.     '''A list comprehension of the form [xp for fp in it if test].
  115.  
  116.     If test is None, the "if test" part is omitted.
  117.     '''
  118.     xp.set_prefix('')
  119.     fp.set_prefix(' ')
  120.     it.set_prefix(' ')
  121.     for_leaf = Leaf(token.NAME, 'for')
  122.     for_leaf.set_prefix(' ')
  123.     in_leaf = Leaf(token.NAME, 'in')
  124.     in_leaf.set_prefix(' ')
  125.     inner_args = [
  126.         for_leaf,
  127.         fp,
  128.         in_leaf,
  129.         it]
  130.     if test:
  131.         test.set_prefix(' ')
  132.         if_leaf = Leaf(token.NAME, 'if')
  133.         if_leaf.set_prefix(' ')
  134.         inner_args.append(Node(syms.comp_if, [
  135.             if_leaf,
  136.             test]))
  137.     
  138.     inner = Node(syms.listmaker, [
  139.         xp,
  140.         Node(syms.comp_for, inner_args)])
  141.     return Node(syms.atom, [
  142.         Leaf(token.LBRACE, '['),
  143.         inner,
  144.         Leaf(token.RBRACE, ']')])
  145.  
  146.  
  147. def FromImport(package_name, name_leafs):
  148.     ''' Return an import statement in the form:
  149.         from package import name_leafs'''
  150.     for leaf in name_leafs:
  151.         leaf.remove()
  152.     
  153.     children = [
  154.         Leaf(token.NAME, 'from'),
  155.         Leaf(token.NAME, package_name, prefix = ' '),
  156.         Leaf(token.NAME, 'import', prefix = ' '),
  157.         Node(syms.import_as_names, name_leafs)]
  158.     imp = Node(syms.import_from, children)
  159.     return imp
  160.  
  161.  
  162. def is_tuple(node):
  163.     '''Does the node represent a tuple literal?'''
  164.     if isinstance(node, Node) and node.children == [
  165.         LParen(),
  166.         RParen()]:
  167.         return True
  168.     if isinstance(node, Node) and len(node.children) == 3 and isinstance(node.children[0], Leaf) and isinstance(node.children[1], Node) and isinstance(node.children[2], Leaf) and node.children[0].value == '(':
  169.         pass
  170.     return node.children[2].value == ')'
  171.  
  172.  
  173. def is_list(node):
  174.     '''Does the node represent a list literal?'''
  175.     if isinstance(node, Node) and len(node.children) > 1 and isinstance(node.children[0], Leaf) and isinstance(node.children[-1], Leaf) and node.children[0].value == '[':
  176.         pass
  177.     return node.children[-1].value == ']'
  178.  
  179.  
  180. def parenthesize(node):
  181.     return Node(syms.atom, [
  182.         LParen(),
  183.         node,
  184.         RParen()])
  185.  
  186. consuming_calls = set([
  187.     'sorted',
  188.     'list',
  189.     'set',
  190.     'any',
  191.     'all',
  192.     'tuple',
  193.     'sum',
  194.     'min',
  195.     'max'])
  196.  
  197. def attr_chain(obj, attr):
  198.     '''Follow an attribute chain.
  199.  
  200.     If you have a chain of objects where a.foo -> b, b.foo-> c, etc,
  201.     use this to iterate over all objects in the chain. Iteration is
  202.     terminated by getattr(x, attr) is None.
  203.  
  204.     Args:
  205.         obj: the starting object
  206.         attr: the name of the chaining attribute
  207.  
  208.     Yields:
  209.         Each successive object in the chain.
  210.     '''
  211.     next = getattr(obj, attr)
  212.     while next:
  213.         yield next
  214.         next = getattr(next, attr)
  215.  
  216. p0 = "for_stmt< 'for' any 'in' node=any ':' any* >\n        | comp_for< 'for' any 'in' node=any any* >\n     "
  217. p1 = "\npower<\n    ( 'iter' | 'list' | 'tuple' | 'sorted' | 'set' | 'sum' |\n      'any' | 'all' | (any* trailer< '.' 'join' >) )\n    trailer< '(' node=any ')' >\n    any*\n>\n"
  218. p2 = "\npower<\n    'sorted'\n    trailer< '(' arglist<node=any any*> ')' >\n    any*\n>\n"
  219. pats_built = False
  220.  
  221. def in_special_context(node):
  222.     """ Returns true if node is in an environment where all that is required
  223.         of it is being itterable (ie, it doesn't matter if it returns a list
  224.         or an itterator).
  225.         See test_map_nochange in test_fixers.py for some examples and tests.
  226.         """
  227.     global p1, p0, p2, pats_built
  228.     if not pats_built:
  229.         p1 = patcomp.compile_pattern(p1)
  230.         p0 = patcomp.compile_pattern(p0)
  231.         p2 = patcomp.compile_pattern(p2)
  232.         pats_built = True
  233.     
  234.     patterns = [
  235.         p0,
  236.         p1,
  237.         p2]
  238.     for pattern, parent in zip(patterns, attr_chain(node, 'parent')):
  239.         results = { }
  240.         if pattern.match(parent, results) and results['node'] is node:
  241.             return True
  242.     
  243.     return False
  244.  
  245.  
  246. def is_probably_builtin(node):
  247.     """
  248.     Check that something isn't an attribute or function name etc.
  249.     """
  250.     prev = node.get_prev_sibling()
  251.     if prev is not None and prev.type == token.DOT:
  252.         return False
  253.     parent = node.parent
  254.     if parent.type in (syms.funcdef, syms.classdef):
  255.         return False
  256.     if parent.type == syms.expr_stmt and parent.children[0] is node:
  257.         return False
  258.     if parent.type == syms.parameters or parent.type == syms.typedargslist:
  259.         if prev is not None or prev.type == token.COMMA or parent.children[0] is node:
  260.             return False
  261.         return True
  262.  
  263.  
  264. def make_suite(node):
  265.     if node.type == syms.suite:
  266.         return node
  267.     node = node.clone()
  268.     parent = node.parent
  269.     node.parent = None
  270.     suite = Node(syms.suite, [
  271.         node])
  272.     suite.parent = parent
  273.     return suite
  274.  
  275.  
  276. def find_root(node):
  277.     '''Find the top level namespace.'''
  278.     while node.type != syms.file_input:
  279.         if not node.parent:
  280.             raise AssertionError, 'Tree is insane! root found before file_input node was found.'
  281.         node = node.parent
  282.         continue
  283.         node.parent
  284.     return node
  285.  
  286.  
  287. def does_tree_import(package, name, node):
  288.     """ Returns true if name is imported from package at the
  289.         top level of the tree which node belongs to.
  290.         To cover the case of an import like 'import foo', use
  291.         None for the package and 'foo' for the name. """
  292.     binding = find_binding(name, find_root(node), package)
  293.     return bool(binding)
  294.  
  295.  
  296. def is_import(node):
  297.     '''Returns true if the node is an import statement.'''
  298.     return node.type in (syms.import_name, syms.import_from)
  299.  
  300.  
  301. def touch_import(package, name, node):
  302.     ''' Works like `does_tree_import` but adds an import statement
  303.         if it was not imported. '''
  304.     
  305.     def is_import_stmt(node):
  306.         if node.type == syms.simple_stmt and node.children:
  307.             pass
  308.         return is_import(node.children[0])
  309.  
  310.     root = find_root(node)
  311.     if does_tree_import(package, name, root):
  312.         return None
  313.     add_newline_before = False
  314.     for idx, node in enumerate(root.children):
  315.         for offset, node2 in enumerate(root.children[idx:]):
  316.             if not is_import_stmt(node2):
  317.                 break
  318.                 continue
  319.             None if not is_import_stmt(node) else does_tree_import(package, name, root)
  320.         
  321.         insert_pos = idx + offset
  322.     
  323.     if insert_pos == 0:
  324.         for idx, node in enumerate(root.children):
  325.             if node.type == syms.simple_stmt and node.children and node.children[0].type == token.STRING:
  326.                 insert_pos = idx + 1
  327.                 add_newline_before
  328.                 break
  329.                 continue
  330.         
  331.     
  332.     if package is None:
  333.         import_ = Node(syms.import_name, [
  334.             Leaf(token.NAME, 'import'),
  335.             Leaf(token.NAME, name, prefix = ' ')])
  336.     else:
  337.         import_ = FromImport(package, [
  338.             Leaf(token.NAME, name, prefix = ' ')])
  339.     children = [
  340.         import_,
  341.         Newline()]
  342.     if add_newline_before:
  343.         children.insert(0, Newline())
  344.     
  345.     root.insert_child(insert_pos, Node(syms.simple_stmt, children))
  346.  
  347. _def_syms = set([
  348.     syms.classdef,
  349.     syms.funcdef])
  350.  
  351. def find_binding(name, node, package = None):
  352.     ''' Returns the node which binds variable name, otherwise None.
  353.         If optional argument package is supplied, only imports will
  354.         be returned.
  355.         See test cases for examples.'''
  356.     for child in node.children:
  357.         ret = None
  358.         if child.type == syms.for_stmt:
  359.             if _find(name, child.children[1]):
  360.                 return child
  361.             n = find_binding(name, make_suite(child.children[-1]), package)
  362.             if n:
  363.                 ret = n
  364.             
  365.         elif child.type in (syms.if_stmt, syms.while_stmt):
  366.             n = find_binding(name, make_suite(child.children[-1]), package)
  367.             if n:
  368.                 ret = n
  369.             
  370.         elif child.type == syms.try_stmt:
  371.             n = find_binding(name, make_suite(child.children[2]), package)
  372.             if n:
  373.                 ret = n
  374.             else:
  375.                 for i, kid in enumerate(child.children[3:]):
  376.                     if kid.type == token.COLON and kid.value == ':':
  377.                         n = find_binding(name, make_suite(child.children[i + 4]), package)
  378.                         if n:
  379.                             ret = n
  380.                         
  381.                     n
  382.                 
  383.         elif child.type in _def_syms and child.children[1].value == name:
  384.             ret = child
  385.         elif _is_import_binding(child, name, package):
  386.             ret = child
  387.         elif child.type == syms.simple_stmt:
  388.             ret = find_binding(name, child, package)
  389.         elif child.type == syms.expr_stmt:
  390.             if _find(name, child.children[0]):
  391.                 ret = child
  392.             
  393.         
  394.         if ret:
  395.             if not package:
  396.                 return ret
  397.             if is_import(ret):
  398.                 return ret
  399.             continue
  400.         is_import(ret)
  401.     
  402.  
  403. _block_syms = set([
  404.     syms.funcdef,
  405.     syms.classdef,
  406.     syms.trailer])
  407.  
  408. def _find(name, node):
  409.     nodes = [
  410.         node]
  411.     while nodes:
  412.         node = nodes.pop()
  413.         if node.type > 256 and node.type not in _block_syms:
  414.             nodes.extend(node.children)
  415.             continue
  416.         if node.type == token.NAME and node.value == name:
  417.             return node
  418.         continue
  419.         node.value == name
  420.  
  421.  
  422. def _is_import_binding(node, name, package = None):
  423.     ''' Will reuturn node if node will import name, or node
  424.         will import * from package.  None is returned otherwise.
  425.         See test cases for examples. '''
  426.     if node.type == syms.import_name and not package:
  427.         imp = node.children[1]
  428.         if imp.type == syms.dotted_as_names:
  429.             for child in imp.children:
  430.                 if child.type == syms.dotted_as_name:
  431.                     if child.children[2].value == name:
  432.                         return node
  433.                     continue
  434.                 child.children[2].value == name
  435.                 if child.type == token.NAME and child.value == name:
  436.                     return node
  437.             
  438.         elif imp.type == syms.dotted_as_name:
  439.             last = imp.children[-1]
  440.             if last.type == token.NAME and last.value == name:
  441.                 return node
  442.         elif imp.type == token.NAME and imp.value == name:
  443.             return node
  444.     elif node.type == syms.import_from:
  445.         if package and unicode(node.children[1]).strip() != package:
  446.             return None
  447.         n = node.children[3]
  448.         if package and _find('as', n):
  449.             return None
  450.         if n.type == syms.import_as_names and _find(name, n):
  451.             return node
  452.         if n.type == syms.import_as_name:
  453.             child = n.children[2]
  454.             if child.type == token.NAME and child.value == name:
  455.                 return node
  456.         elif n.type == token.NAME and n.value == name:
  457.             return node
  458.         _find(name, n)
  459.         if package and n.type == token.STAR:
  460.             return node
  461.     
  462.  
  463.