Пример #1
0
 def transform(self, node, results):
     args = []
     item_id = 0
     while item_id < len(node.children):
         if (node.children[item_id].__class__.__name__ == "Leaf"):
             if node.children[item_id].value == ':':
                 #加花括号
                 args += [
                     Leaf(token.LBRACE, '{'),
                     node.children[item_id + 1].clone(),
                     Leaf(token.RBRACE, '}'),
                     Leaf(4, '\r\n')
                 ]
                 item_id += 1
             #if,elif处理
             elif (node.children[item_id].value
                   == 'elif') | (node.children[item_id].value == 'if'):
                 if node.children[item_id].value == 'elif':
                     leaf_temp = Leaf(1, 'if')
                     leaf_temp.prefix = " "
                     args += [Leaf(1, 'else'), leaf_temp]
                 else:
                     args += [node.children[item_id].clone()]
                 args += [Leaf(7, '(')]
                 args += [node.children[item_id + 1].clone()]
                 args += [Leaf(8, ')')]
                 item_id += 1
             else:
                 args += [node.children[item_id].clone()]
         else:
             print("\nFixerError_if\n")
         item_id += 1
     new = Node(node.type, args)
     new.prefix = node.prefix
     return new
Пример #2
0
	def transform(self, node, results):
		args = []
		for i in range(len(node.children[0].children)):
			if i%2==1:
				if i!=1:
					args.append(Leaf(1, '&&'))
				args.append(Leaf(7, '('))
				args.append(node.children[0].children[i].clone())
				args.append(Leaf(8, ')'))
		args = [\
			Leaf(1, 'if'),Leaf(7, '('),\
			Leaf(1, '!'),Leaf(7, '('),\
			Node(syms.and_expr,args),\
			Leaf(8, ')'),Leaf(8, ')'),\
			Leaf(token.LBRACE, '{'),\
			Node(syms.raise_stmt, [
                        Leaf(1, 'throw'),
                        Leaf(3, '"AssertionError"'),
						Leaf(1, ';'),
                ]),
			Leaf(token.RBRACE, '}'),Leaf(4, '\r\n')
		]
		
		result = Node(syms.testlist1,args)
		result.prefix = node.prefix
		return result
Пример #3
0
def ImportAsName(name, as_name, prefix=None):
    new_name = Name(name)
    new_as = Name(u"as", prefix=u" ")
    new_as_name = Name(as_name, prefix=u" ")
    new_node = Node(syms.import_as_name, [new_name, new_as, new_as_name])
    if prefix is not None:
        new_node.prefix = prefix
    return new_node
Пример #4
0
def ImportAsName(name, as_name, prefix=None):
    new_name = Name(name)
    new_as = Name(u"as", prefix=u" ")
    new_as_name = Name(as_name, prefix=u" ")
    new_node = Node(syms.import_as_name, [new_name, new_as, new_as_name])
    if prefix is not None:
        new_node.prefix = prefix
    return new_node
Пример #5
0
	def transform(self, node, results):
		args = [Leaf(1, 'while')]
		args += [Leaf(7, '(')]
		args += [n.clone() for n in results["test_content"]]
		args += [Leaf(8, ')'),Leaf(token.LBRACE, '{')]
		args += [n.clone() for n in results["content"]]
		new = Node(node.type,args)
		new.prefix = node.prefix 
		return new
Пример #6
0
 def transform(self, node, results):
     args = [Leaf(1, 'for')]
     args += [Leaf(7, '(')]
     args += [Leaf(1, 'auto')]  #c++11
     args += [n.clone() for n in results["in_before"]]
     args += [Leaf(token.COLON, ':')]
     args += [n.clone() for n in results["in_after"]]
     args += [Leaf(8, ')'), Leaf(token.LBRACE, '{')]
     args += [n.clone() for n in results["content"]]
     new = Node(node.type, args)
     new.prefix = node.prefix
     return new
Пример #7
0
	def transform(self, node, results):
		args = []
		if results['first']:
			args.append(Node(syms.simple_stmt,[\
				Leaf(1, 'TODO_PyObject'),
				results['name'].clone(),
				Leaf(1, ';'),
				Leaf(4, '\r\n'),]))
		if results['out'][0].type==syms.trailer:
			args.append(deal_cout(results['out'][0].children[1]))
		args.append(deal_cin(results['name']))
		result = Node(syms.testlist1,args)
		result.prefix = node.prefix
		return result
Пример #8
0
    def _describe_classdef(self, node: Node) -> None:
        prefix = node.prefix.rstrip(" ").lstrip("\n") + find_indentation(node)
        next_sibling = node.next_sibling
        if next_sibling is not None:
            self.upper_bound = min(next_sibling.get_lineno(), self.upper_bound)

        node = node.clone()
        node.prefix = prefix

        if self.lower_bounds and self.lower_bounds[-1] < node.get_lineno():
            self.describe_skipping()

        max_limit = node.get_lineno() + self.n
        v = CuttingNodeVisitor(max_limit)
        v.visit(node)
        self.lower_bounds.extend(sorted(list(v.seen)))
        print(node)
Пример #9
0
 def transform(self, node, results):
     comp_for = results.get("comp_for").clone()
     is_dict = bool(results.get("col"))  # is it a dict?
     n1 = results.get("n1").clone()
     if is_dict:
         n2 = results.get("n2").clone()
         n2.prefix = " "
         impl_assign = tup((n1, n2))
     else:
         impl_assign = n1
     our_gencomp = Node(syms.listmaker, [(impl_assign), (comp_for)])
     if is_dict:
         new_node = Node(syms.power, [Name("dict"), parenthesize(Node(syms.atom, [our_gencomp]))])
     else:
         new_node = Node(syms.power, [Name("set"), parenthesize(Node(syms.atom, [our_gencomp]))])
     new_node.prefix = node.prefix
     return new_node
Пример #10
0
 def transform(self, node, results):
     if (type(results["content"]) == type(node)):
         args = [results["content"].clone()]
     else:
         args = [n.clone() for n in results["content"]]
     for temp_leaf in args:
         if temp_leaf.type == syms.suite:
             indent_leaf = Leaf(token.RBRACE, '}')
             indent_leaf.prefix = calculate_indent(node.prefix)
             temp_leaf.insert_child(
                 len(temp_leaf.children) - 1, indent_leaf)
             temp_leaf.insert_child(
                 len(temp_leaf.children) - 1, Leaf(4, '\r\n'))
     args = [n.clone()
             for n in results["head"]] + [Leaf(token.LBRACE, '{')] + args
     new = Node(node.type, args)
     new.prefix = node.prefix
     return new
Пример #11
0
def add_end_part(end, file, parent, loc):
    if isNone(end):
        return
    if end.type == token.STRING and end.value in ("' '", '" "', "u' '", 'u" "',
                                                  "b' '", 'b" "'):
        return
    if file is None:
        touch_import(None, "sys", parent)
        file = Node(syms.power,
                    [Name("sys"),
                     Node(syms.trailer, [Dot(), Name("stdout")])])
    end_part = Node(syms.power, [
        file,
        Node(syms.trailer, [Dot(), Name("write")]),
        Node(syms.trailer, [LParen(), end, RParen()])
    ])
    end_part.prefix = " "
    parent.insert_child(loc, Leaf(token.SEMI, ";"))
    parent.insert_child(loc + 1, end_part)
Пример #12
0
    def transform(self, node, results):
        args = []
        as_list = [[], []]
        for i in node.children:
            if i.type == 11:
                args.append(Leaf(token.LBRACE, '{'))
            elif i.type == syms.suite:
                #as 语句
                for j in range(len(as_list[0])):
                    args.append(i.children[0].clone())
                    args.append(i.children[1].clone())
                    args.append(Node(syms.simple_stmt,[\
                     Leaf(1, 'auto'),
                     as_list[0][j].clone(),
                     Leaf(22, '='),
                     as_list[1][j].clone(),
                     Leaf(1, ';'),]))
                as_list[0] = []
                as_list[1] = []
                args.append(i.clone())
                args.append(Leaf(token.RBRACE, '}'))
                args.append(Leaf(4, '\r\n'))
                args.append(i.children[-1].clone())
            elif i.type == syms.except_clause:
                except_args = [Leaf(1, 'catch'),\
                 Leaf(7, '(')]
                for j in i.children[1:]:
                    #as 语句
                    if (j.type == 1) & (j.value == 'as'):
                        as_list[0].append(except_args[-1].clone())
                    elif len(as_list[0]) != len(as_list[1]):
                        as_list[1].append(j.clone())

                    else:
                        except_args.append(j.clone())
                except_args.append(Leaf(8, ')'))
                args.append(
                    Node(syms.except_clause, except_args, prefix=i.prefix))
            else:
                args.append(i.clone())
        new = Node(node.type, args)
        new.prefix = node.prefix
        return new
Пример #13
0
    def insert_annotation(self, arg_type):
        """Modifies tree to set string arg_type as our type annotation"""
        # maybe the right way to do this is to insert as next child
        # in our parent instead? Or could replace self._arg[-1]
        # with modified version of itself
        assert self.arg_type is None, 'already annotated'
        assert not self._wasModified, 'can only set annotation once'
        self._wasModified = True

        name = self._name_nodes[-1]
        assert name.type == token.NAME

        typed_name = Node(syms.tname,
                          [Leaf(token.NAME, self.name),
                           Leaf(token.COLON, ':'),
                           clean_clone(arg_type, False)])

        typed_name.prefix = name.prefix

        name.replace(typed_name)
Пример #14
0
	def transform(self, node, results):
		args = []
		item_id = 0
		while item_id <len(node.children):
			if (node.children[item_id].__class__.__name__=="Leaf"):
				if node.children[item_id].value==':':
					#取:号下一行的第二个元素前的空行,因为第一个元素是换行。
					leaf_temp0 = Leaf(token.RBRACE, '}')
					leaf_temp0.prefix = change_indent(calculate_indent(node.children[item_id+1].children[1].value), -1)
					#加花括号
					args+=[Leaf(token.LBRACE, '{'),
					node.children[item_id+1].clone(),
					Leaf(4, '\r\n'),
					leaf_temp0,
					Leaf(4, '\r\n')]
					item_id+=1
				#if,elif处理
				elif (node.children[item_id].value=='elif') | (node.children[item_id].value=='if'):
					if node.children[item_id].value=='elif':
						leaf_temp0 = Leaf(1, 'else')
						leaf_temp0.prefix = change_indent(calculate_indent(node.children[item_id+3].children[1].value), -1)
						leaf_temp1 = Leaf(1, 'if')
						leaf_temp1.prefix = " "
						args+=[leaf_temp0,leaf_temp1]
					else:
						args+=[node.children[item_id].clone()]
					args+=[Leaf(7, '(')]
					args+=[node.children[item_id+1].clone()]
					args+=[Leaf(8, ')')]
					item_id+=1
				else:
					leaf_temp0 = node.children[item_id].clone()
					if(node.children[item_id].value=='else'):
						leaf_temp0.prefix = change_indent(calculate_indent(node.children[item_id+2].children[1].value), -1)
					args+=[leaf_temp0]
			else:
				print("\nFixerError_if\n")
			item_id+=1
		new = Node(node.type,args)
		new.prefix = node.prefix 
		return new
Пример #15
0
    def insert_annotation(self, arg_type):
        """Modifies tree to set string arg_type as our type annotation."""
        # maybe the right way to do this is to insert as next child
        # in our parent instead? Or could replace self._arg[-1]
        # with modified version of itself
        assert self.arg_type is None, 'already annotated'
        assert not self._was_modified, 'can only set annotation once'
        self._was_modified = True

        name = self._name_nodes[-1]
        assert name.type == token.NAME

        typed_name = Node(syms.tname, [
            Leaf(token.NAME, self.name),
            Leaf(token.COLON, ':'),
            clean_clone(arg_type, False)
        ])

        typed_name.prefix = name.prefix

        name.replace(typed_name)
Пример #16
0
    def transform(self, node, results):
        #处理"%s" %d问题
        def deal_term(node):
            from lib2to3.fixer_util import Call
            args = []
            args += get_atom(node.children[0])
            for i in range(1, len(node.children)):
                if i % 2 == 1:
                    continue
                args += get_atom(node.children[i])
            temp = len(args) - 1
            for i in range(temp):
                args.insert(2 * i + 1, Leaf(12, ','))
            return Node(syms.simple_stmt,[\
             Call(Leaf(1,'printf'),args),
             Leaf(1, ';'),
             Leaf(4, '\r\n'),])

        item_list = []
        i = 1
        args = []
        while i < len(node.children[0].children):
            item_list.append(node.children[0].children[i])
            i += 2
        for item in item_list:
            if item.type == syms.atom:
                item_list.insert(item_list.index(item) + 1, item.children[1])
            elif item.type == syms.testlist_gexp:
                i = 0
                while i < len(item.parent.children) / 2:
                    item_list.insert(
                        item_list.index(item) + i + 1, item.children[i * 2])
                    i += 1
            elif item.type == syms.term:
                args.append(deal_term(item))
            else:
                args.append(deal_cout(item))
        result = Node(syms.testlist1, args)
        result.prefix = node.prefix
        return result
Пример #17
0
 def transform(self, node, results):
     comp_for = results.get("comp_for").clone()
     is_dict = bool(results.get("col"))  # is it a dict?
     n1 = results.get("n1").clone()
     if is_dict:
         n2 = results.get("n2").clone()
         n2.prefix = " "
         impl_assign = tup((n1, n2))
     else:
         impl_assign = n1
     our_gencomp = Node(syms.listmaker, [(impl_assign), (comp_for)])
     if is_dict:
         new_node = Node(
             syms.power,
             [Name("dict"),
              parenthesize(Node(syms.atom, [our_gencomp]))])
     else:
         new_node = Node(
             syms.power,
             [Name("set"),
              parenthesize(Node(syms.atom, [our_gencomp]))])
     new_node.prefix = node.prefix
     return new_node
Пример #18
0
def wrap_parens(arg_node: PyNode, checker_fn: callable) -> PyNode or PyLeaf:
    """
    If a node that represents an argument to assert_ function should be grouped, return a new node that adds
    parentheses around arg_node. Otherwise, return arg_node.
    :param arg_node: the arg_node to parenthesize
    :return: the arg_node for the parenthesized expression, or the arg_node itself
    """
    if isinstance(arg_node, PyNode) and checker_fn(arg_node):
        # log.info('adding parens: "{}" ({}), "{}" ({})'.format(first_child, first_child.type, sibling, sibling.type))
        # sometimes arg_node has parent, need to remove it before giving to parenthesize() then re-insert:
        parent = arg_node.parent
        if parent is not None:
            pos_parent = arg_node.remove()
            new_node = parenthesize(arg_node)
            parent.insert_child(pos_parent, new_node)
        else:
            new_node = parenthesize(arg_node)

        new_node.prefix = arg_node.prefix
        arg_node.prefix = ''
        return new_node

    return arg_node
Пример #19
0
def wrap_parens(arg_node: PyNode, checker_fn: callable) -> PyNode or PyLeaf:
    """
    If a node that represents an argument to assert_ function should be grouped, return a new node that adds
    parentheses around arg_node. Otherwise, return arg_node.
    :param arg_node: the arg_node to parenthesize
    :return: the arg_node for the parenthesized expression, or the arg_node itself
    """
    if isinstance(arg_node, PyNode) and checker_fn(arg_node):
        # log.info('adding parens: "{}" ({}), "{}" ({})'.format(first_child, first_child.type, sibling, sibling.type))
        # sometimes arg_node has parent, need to remove it before giving to parenthesize() then re-insert:
        parent = arg_node.parent
        if parent is not None:
            pos_parent = arg_node.remove()
            new_node = parenthesize(arg_node)
            parent.insert_child(pos_parent, new_node)
        else:
            new_node = parenthesize(arg_node)

        new_node.prefix = arg_node.prefix
        arg_node.prefix = ''
        return new_node

    return arg_node