|
| 1 | +"""Insert an absent canonical method before an unchanged class anchor.""" |
| 2 | + |
| 3 | +import ast |
| 4 | + |
| 5 | +from update_lib.cmd_copy_test import _definition |
| 6 | + |
| 7 | + |
| 8 | +def _class_scope_nodes(cls): |
| 9 | + """Visit class bindings, not bindings inside nested lexical scopes. |
| 10 | +
|
| 11 | + Definition names and header expressions still belong to the surrounding |
| 12 | + scope. Inspect annotations conservatively too, even when evaluation is |
| 13 | + deferred; do not inspect nested bodies or type-parameter scopes. |
| 14 | + """ |
| 15 | + |
| 16 | + def visit(node): |
| 17 | + yield node |
| 18 | + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): |
| 19 | + children = [node.args, *node.decorator_list] |
| 20 | + if node.returns is not None: |
| 21 | + children.append(node.returns) |
| 22 | + elif isinstance(node, ast.Lambda): |
| 23 | + children = [node.args] |
| 24 | + elif isinstance(node, ast.ClassDef): |
| 25 | + children = [*node.bases, *node.keywords, *node.decorator_list] |
| 26 | + elif isinstance( |
| 27 | + node, (ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp) |
| 28 | + ): |
| 29 | + # Only the outermost iterable is evaluated outside the implicit |
| 30 | + # comprehension scope. Its iteration targets are not class bindings. |
| 31 | + children = [node.generators[0].iter] |
| 32 | + else: |
| 33 | + children = ast.iter_child_nodes(node) |
| 34 | + for child in children: |
| 35 | + yield from visit(child) |
| 36 | + |
| 37 | + for node in cls.body: |
| 38 | + yield from visit(node) |
| 39 | + |
| 40 | + |
| 41 | +def insert_test(source: str, destination: str, qualified_name: str, before: str) -> str: |
| 42 | + """Insert an absent direct method before an unchanged canonical anchor. |
| 43 | +
|
| 44 | + This intentionally excludes guarded classes/methods and non-LF inputs. |
| 45 | + It copies no imports or helpers: callers must review those dependencies. |
| 46 | + """ |
| 47 | + if any("\r" in text or not text.endswith("\n") for text in (source, destination)): |
| 48 | + raise ValueError("Insertion requires LF input with a final newline") |
| 49 | + method, guards, start, end = _definition(source, qualified_name) |
| 50 | + anchor, anchor_guards, anchor_start, anchor_end = _definition(source, before) |
| 51 | + dst_anchor, dst_guards, dst_start, dst_end = _definition(destination, before) |
| 52 | + class_name, name = qualified_name.split(".") |
| 53 | + if before.split(".")[0] != class_name: |
| 54 | + raise ValueError("Insertion anchor must be in the same class") |
| 55 | + if guards or anchor_guards or dst_guards: |
| 56 | + raise ValueError("Insertion does not support guarded definitions") |
| 57 | + src_tree, dst_tree = ast.parse(source), ast.parse(destination) |
| 58 | + src_class = next( |
| 59 | + node |
| 60 | + for node in src_tree.body |
| 61 | + if isinstance(node, ast.ClassDef) and node.name == class_name |
| 62 | + ) |
| 63 | + dst_class = next( |
| 64 | + node |
| 65 | + for node in dst_tree.body |
| 66 | + if isinstance(node, ast.ClassDef) and node.name == class_name |
| 67 | + ) |
| 68 | + if any( |
| 69 | + isinstance(node, (ast.Global, ast.Nonlocal)) |
| 70 | + for cls in (src_class, dst_class) |
| 71 | + for node in _class_scope_nodes(cls) |
| 72 | + ): |
| 73 | + raise ValueError("Insertion does not support scope declarations in classes") |
| 74 | + # Nodes come from separate parses; compare their unique source locations. |
| 75 | + members = {node.lineno: index for index, node in enumerate(src_class.body)} |
| 76 | + if members.get(anchor.lineno) != members.get(method.lineno, -2) + 1: |
| 77 | + raise ValueError("Source test must immediately precede its direct anchor") |
| 78 | + if not any(node.lineno == dst_anchor.lineno for node in dst_class.body): |
| 79 | + raise ValueError("Destination anchor must be a direct class member") |
| 80 | + for node in _class_scope_nodes(dst_class): |
| 81 | + if ( |
| 82 | + ( |
| 83 | + isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)) |
| 84 | + and node.name == name |
| 85 | + ) |
| 86 | + or ( |
| 87 | + isinstance(node, ast.Name) |
| 88 | + and isinstance(node.ctx, ast.Store) |
| 89 | + and node.id == name |
| 90 | + ) |
| 91 | + or ( |
| 92 | + isinstance(node, ast.alias) |
| 93 | + and (node.asname or node.name.split(".")[0]) == name |
| 94 | + ) |
| 95 | + or ( |
| 96 | + isinstance(node, (ast.MatchAs, ast.MatchStar, ast.ExceptHandler)) |
| 97 | + and node.name == name |
| 98 | + ) |
| 99 | + or (isinstance(node, ast.MatchMapping) and node.rest == name) |
| 100 | + ): |
| 101 | + raise ValueError("Insertion test name already exists in destination class") |
| 102 | + |
| 103 | + # AST line numbers count LF, not Unicode separators embedded in strings. |
| 104 | + def lines(text): |
| 105 | + return [line + "\n" for line in text.split("\n")[:-1]] |
| 106 | + |
| 107 | + src_lines, dst_lines = lines(source), lines(destination) |
| 108 | + |
| 109 | + def header(cls, lines): |
| 110 | + first = min([cls.lineno, *(node.lineno for node in cls.decorator_list)]) - 1 |
| 111 | + child = cls.body[0] |
| 112 | + child_start = ( |
| 113 | + min( |
| 114 | + [ |
| 115 | + child.lineno, |
| 116 | + *(node.lineno for node in getattr(child, "decorator_list", [])), |
| 117 | + ] |
| 118 | + ) |
| 119 | + - 1 |
| 120 | + ) |
| 121 | + return lines[first:child_start] |
| 122 | + |
| 123 | + if header(src_class, src_lines) != header(dst_class, dst_lines): |
| 124 | + raise ValueError("Insertion class headers differ") |
| 125 | + if src_lines[anchor_start:anchor_end] != dst_lines[dst_start:dst_end]: |
| 126 | + raise ValueError("Insertion anchor text differs") |
| 127 | + if ( |
| 128 | + method.col_offset != anchor.col_offset |
| 129 | + or method.col_offset != dst_anchor.col_offset |
| 130 | + ): |
| 131 | + raise ValueError("Insertion indentation differs") |
| 132 | + # Do not split or silently omit comments attached to either definition. |
| 133 | + previous = [node.end_lineno for node in src_class.body if node.end_lineno <= start] |
| 134 | + previous_end = max(previous, default=src_class.lineno) |
| 135 | + dst_previous = [ |
| 136 | + node.end_lineno for node in dst_class.body if node.end_lineno <= dst_start |
| 137 | + ] |
| 138 | + dst_previous_end = max(dst_previous, default=dst_class.lineno) |
| 139 | + for gap in ( |
| 140 | + src_lines[previous_end:start], |
| 141 | + src_lines[end:anchor_start], |
| 142 | + dst_lines[dst_previous_end:dst_start], |
| 143 | + ): |
| 144 | + if any(line.strip() for line in gap): |
| 145 | + raise ValueError("Insertion requires blank definition boundaries") |
| 146 | + block = src_lines[start:anchor_start] |
| 147 | + result = "".join(dst_lines[:dst_start] + block + dst_lines[dst_start:]) |
| 148 | + _, _, result_start, result_end = _definition(result, qualified_name) |
| 149 | + if lines(result)[result_start:result_end] != src_lines[start:end]: |
| 150 | + raise ValueError("Inserted definition is not byte-identical to the source") |
| 151 | + return result |
0 commit comments