Exemplo n.º 1
0
def insert_args(name, class_name, rparen):
    parent = rparen.parent

    if class_name:
        class_node = Node(syms.power, [Name(class_name)])
    else:
        class_node = Node(syms.power, [Name(name), dot_class.clone()])

    idx = parent.children.index(rparen)
    parent.insert_child(idx, Name(name, prefix=" "))
    parent.insert_child(idx, Comma())
    parent.insert_child(idx, class_node)
Exemplo n.º 2
0
 def handle_name(name, prefix):
     if name.type == syms.import_as_name:
         kids = [
             Name(name.children[0].value, prefix=prefix),
             name.children[1].clone(),
             name.children[2].clone(),
         ]
         return [Node(syms.import_as_name, kids)]
     return [Name(name.value, prefix=prefix)]
Exemplo n.º 3
0
    def transform(self, node, results):
        sys_attr = results["attribute"][0]
        index = Number(self.exc_info.index(sys_attr.value))

        call = Call(Name("exc_info"), prefix=sys_attr.prefix)
        attr = Attr(Name("sys"), call)
        attr[1].children[0].prefix = results["dot"].prefix
        attr.append(Subscript(index))
        return Node(syms.power, attr, prefix=node.prefix)
Exemplo n.º 4
0
 def transform_isinstance(self, node, results):
     x = results["x"].clone()  # The thing inside of type()
     T = results["T"].clone()  # The type being compared against
     x.prefix = ""
     T.prefix = " "
     test = Call(Name("isinstance"), [x, Comma(), T])
     if "n" in results:
         test.prefix = " "
         test = Node(syms.not_test, [Name("not"), test])
     test.prefix = node.prefix
     return test
Exemplo n.º 5
0
    def transform(self, node, results):
        arg_list = results.get("args")

        if node.type == syms.import_name:
            new = BlankLine()
            return new

        elif arg_list:
            args = arg_list[0]
            args = args.clone()
            prefix = node.prefix
            return Node(syms.power, [Name("reload"), args], prefix=prefix)
Exemplo n.º 6
0
def fixup_simple_stmt(parent, i, stmt_node):
    """ if there is a semi-colon all the parts count as part of the same
        simple_stmt.  We just want the __metaclass__ part so we move
        everything after the semi-colon into its own simple_stmt node
    """
    for semi_ind, node in enumerate(stmt_node.children):
        if node.type == token.SEMI:  # *sigh*
            break
    else:
        return

    node.remove()  # kill the semicolon
    new_expr = Node(syms.expr_stmt, [])
    new_stmt = Node(syms.simple_stmt, [new_expr])
    while stmt_node.children[semi_ind:]:
        move_node = stmt_node.children[semi_ind]
        new_expr.append_child(move_node.clone())
        move_node.remove()
    parent.insert_child(i, new_stmt)
    new_leaf1 = new_stmt.children[0].children[0]
    old_leaf1 = stmt_node.children[0].children[0]
    new_leaf1.prefix = old_leaf1.prefix
Exemplo n.º 7
0
def fixup_parse_tree(cls_node):
    """ one-line classes don't get a suite in the parse tree so we add
        one to normalize the tree
    """
    for node in cls_node.children:
        if node.type == syms.suite:
            # already in the preferred format, do nothing
            return

    # !%@#! oneliners have no suite node, we have to fake one up
    for i, node in enumerate(cls_node.children):
        if node.type == token.COLON:
            break
    else:
        raise ValueError("No class suite and no ':'!")

    # move everything into a suite node
    suite = Node(syms.suite, [])
    while cls_node.children[i + 1:]:
        move_node = cls_node.children[i + 1]
        suite.append_child(move_node.clone())
        move_node.remove()
    cls_node.append_child(suite)
    node = suite
Exemplo n.º 8
0
 def transform(self, node, results):
     name, val, trc = (results.get("name"), results.get("val"),
                       results.get("trc"))
     chain = results.get("chain")
     if chain is not None:
         self.warning(
             node,
             "explicit exception chaining is not supported in Python 2")
         chain.prev_sibling.remove()
         chain.remove()
     if trc is not None:
         val = val[0] if val else Leaf(token.NAME, "None")
         val.prefix = trc.prefix = " "
         kids = [
             Leaf(token.NAME, "raise"),
             name.clone(),
             Comma(),
             val.clone(),
             Comma(),
             trc.clone()
         ]
         raise_stmt = Node(syms.raise_stmt, kids)
         node.replace(raise_stmt)
Exemplo n.º 9
0
"""
Fixer for:

def something(self):
    super()

->

def something(self):
    super(self.__class__, self)
"""

from crosswind import fixer_base
from crosswind.fixer_util import Comma, Dot, Leaf, Name, Node, syms, token

dot_class = Node(syms.trailer, [Dot(), Name("__class__")])


def get_firstparam(super_node):
    parent = super_node.parent
    while parent.type != syms.funcdef and parent.parent:
        parent = parent.parent

    if parent.type != syms.funcdef:
        # super() called without arguments outside of a funcdef
        return None

    children = parent.children
    assert len(children) > 2
    params = children[2]
    assert params.type == syms.parameters
Exemplo n.º 10
0
    def transform(self, node, results):
        if not has_metaclass(node):
            return

        fixup_parse_tree(node)

        # find metaclasses, keep the last one
        last_metaclass = None
        for suite, i, stmt in find_metas(node):
            last_metaclass = stmt
            stmt.remove()

        text_type = node.children[0].type  # always Leaf(nnn, 'class')

        # figure out what kind of classdef we have
        if len(node.children) == 7:
            # Node(classdef, ['class', 'name', '(', arglist, ')', ':', suite])
            #                 0        1       2    3        4    5    6
            if node.children[3].type == syms.arglist:
                arglist = node.children[3]
            # Node(classdef, ['class', 'name', '(', 'Parent', ')', ':', suite])
            else:
                parent = node.children[3].clone()
                arglist = Node(syms.arglist, [parent])
                node.set_child(3, arglist)
        elif len(node.children) == 6:
            # Node(classdef, ['class', 'name', '(',  ')', ':', suite])
            #                 0        1       2     3    4    5
            arglist = Node(syms.arglist, [])
            node.insert_child(3, arglist)
        elif len(node.children) == 4:
            # Node(classdef, ['class', 'name', ':', suite])
            #                 0        1       2    3
            arglist = Node(syms.arglist, [])
            node.insert_child(2, Leaf(token.RPAR, ")"))
            node.insert_child(2, arglist)
            node.insert_child(2, Leaf(token.LPAR, "("))
        else:
            raise ValueError("Unexpected class definition")

        # now stick the metaclass in the arglist
        meta_txt = last_metaclass.children[0].children[0]
        meta_txt.value = "metaclass"
        orig_meta_prefix = meta_txt.prefix

        if arglist.children:
            arglist.append_child(Leaf(token.COMMA, ","))
            meta_txt.prefix = " "
        else:
            meta_txt.prefix = ""

        # compact the expression "metaclass = Meta" -> "metaclass=Meta"
        expr_stmt = last_metaclass.children[0]
        assert expr_stmt.type == syms.expr_stmt
        expr_stmt.children[1].prefix = ""
        expr_stmt.children[2].prefix = ""

        arglist.append_child(last_metaclass)

        fixup_indent(suite)

        # check for empty suite
        if not suite.children:
            # one-liner that was just __metaclass_
            suite.remove()
            pass_leaf = Leaf(text_type, "pass")
            pass_leaf.prefix = orig_meta_prefix
            node.append_child(pass_leaf)
            node.append_child(Leaf(token.NEWLINE, "\n"))

        elif len(suite.children) > 1 and (
                suite.children[-2].type == token.INDENT
                and suite.children[-1].type == token.DEDENT):
            # there was only one line in the class body and it was __metaclass__
            pass_leaf = Leaf(text_type, "pass")
            suite.insert_child(-1, pass_leaf)
            suite.insert_child(-1, Leaf(token.NEWLINE, "\n"))