"""Move top-level functions, classes and variables of a Python module to another module. Run by the IDE like `python_signature.py`: one JSON request on stdin, one JSON answer on stdout. It only turns texts into texts: the IDE reads the files, updates their `from … import` statements with its module-move rewriter, and passes the results here. This script moves the code, writes the imports the two modules need and rewrites `module.name` uses. rope's `MoveGlobal` is not used: it overwrites nothing but happily defines a name twice, empties re-exports and drops imports. """ import ast import json import re import sys class Refused(Exception): """A move that can't be carried out; the message is shown to the user.""" class Unparsable(Refused): """A file with a syntax error.""" def parse(text, path): try: return ast.parse(text) except SyntaxError as e: raise Unparsable(f"Syntax error in {path}: {e.msg} (line {e.lineno})") def lines_of(text): return [line for line in re.split(r"(?<=\n)", text) if line] class Src: def __init__(self, text): self.text, self.lines, self.starts = text, lines_of(text), [0] for line in self.lines: self.starts.append(self.starts[-1] + len(line)) def off(self, lineno, col): # `ast` columns are UTF-8 byte offsets line = self.lines[lineno - 1] return self.starts[lineno - 1] + len(line.encode("utf-8")[:col].decode("utf-8", "ignore")) def span(self, node): return self.off(node.lineno, node.col_offset), self.off(node.end_lineno, node.end_col_offset) def splice(text, edits): for start, end, new in sorted(set(edits), reverse=True): text = text[:start] + new + text[end:] return text # ---------------------------------------------------------------- what a module defines def targets(node): """The names a top-level statement defines that can be moved.""" if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): return [(node.name, "function")] if isinstance(node, ast.ClassDef): return [(node.name, "class")] if isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name): return [(node.targets[0].id, "variable")] if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) and node.value is not None: return [(node.target.id, "variable")] return [] def first_line(node): return min([node.lineno] + [d.lineno for d in getattr(node, "decorator_list", [])]) def resolve(level, module, package): """The absolute module of `from import …` inside `package`.""" if not level: return module or "" parts = package.split(".") if package else [] keep = len(parts) - (level - 1) if keep <= 0: raise Refused("A relative import reaches above the top-level package") return ".".join(parts[:keep] + ([module] if module else [])) class Binding: def __init__(self, statement=None, defined=False, conditional=False): # `statement`: the import that recreates the name elsewhere self.statement, self.defined, self.conditional = statement, defined, conditional self.statements = [] # `import a.b` and `import a.c` both bind `a` self.count = 0 def bindings(tree, package): """Every name bound at module level, through `if` / `try` / `with` / loops.""" found = {} def add(name, conditional, statement=None, defined=False): b = found.setdefault(name, Binding(statement, defined, conditional)) b.count += 1 if statement and statement not in b.statements: b.statements.append(statement) def walk(node, conditional): if isinstance(node, ast.Import): for a in node.names: if a.asname: add(a.asname, conditional, f"import {a.name} as {a.asname}") else: add(a.name.split(".")[0], conditional, f"import {a.name}") elif isinstance(node, ast.ImportFrom): module = resolve(node.level, node.module, package) for a in node.names: if a.name != "*": tail = f" as {a.asname}" if a.asname else "" add(a.asname or a.name, conditional, f"from {module} import {a.name}{tail}") elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): add(node.name, conditional, defined=True) elif isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store): add(node.id, conditional, defined=True) elif not isinstance(node, (ast.Lambda, ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp)): inner = conditional or isinstance(node, (ast.If, ast.Try, ast.For, ast.While, ast.With, getattr(ast, "Match", ()))) for child in ast.iter_child_nodes(node): walk(child, inner) for statement in tree.body: walk(statement, False) return found def names_read(nodes): """Every name the code reads, string annotations included.""" found = set() for node in nodes: for n in ast.walk(node): if isinstance(n, ast.Name) and not isinstance(n.ctx, ast.Store): found.add(n.id) for note in (getattr(n, "annotation", None), getattr(n, "returns", None)): for c in ast.walk(note) if note is not None else (): if isinstance(c, ast.Constant) and isinstance(c.value, str): try: found |= names_read([ast.parse(c.value, mode="eval")]) except SyntaxError: pass return found # ---------------------------------------------------------------- editing a module def import_position(src, tree): """The line index new imports go to: after the leading imports, the docstring or the comments.""" last = 0 for i, node in enumerate(tree.body): docstring = i == 0 and isinstance(node, ast.Expr) and isinstance(getattr(node.value, "value", None), str) if not docstring and not isinstance(node, (ast.Import, ast.ImportFrom)): break last = node.end_lineno if not last: while last < len(src.lines) and src.lines[last].startswith("#"): last += 1 return last def add_imports(text, statements, path): if not statements: return text src, tree = Src(text), parse(text, path) future = [s for s in statements if s.startswith("from __future__ ")] rest = [s for s in statements if s not in future] at = import_position(src, tree) head, tail = "".join(src.lines[:at]), "".join(src.lines[at:]) if head and not head.endswith("\n"): head += "\n" if future: # must precede every other import first = next((n for n in tree.body if isinstance(n, (ast.Import, ast.ImportFrom))), None) cut = src.starts[first.lineno - 1] if first else len(head) head = head[:cut] + "".join(s + "\n" for s in future) + head[cut:] block = "".join(s + "\n" for s in rest) if block and head and not any(isinstance(n, (ast.Import, ast.ImportFrom)) for n in tree.body): block = "\n" + block if tail.strip() and not tail.startswith("\n") and (rest or future): tail = "\n\n" + tail return head + block + tail def cut_blocks(src, tree, nodes): """(line ranges, texts) of the statements to move, with their decorators and leading comments.""" ranges, texts = [], [] for node in nodes: start, end = first_line(node) - 1, node.end_lineno for other in tree.body: if other is not node and first_line(other) <= end and other.end_lineno > start: raise Refused("A statement shares its line with another one; split them first") above = max((o.end_lineno for o in tree.body if o.end_lineno <= start), default=0) top = start while top > above and src.lines[top - 1].startswith("#") and not re.match(r"#!|#.*coding[:=]", src.lines[top - 1]): top -= 1 # comments reaching the top of the file are its header (copyright, license), not the node's if top and any(line.strip() and not line.startswith("#") for line in src.lines[:top]): start = top # indented comments after the body belong to it probe = end while probe < len(src.lines) and (not src.lines[probe].strip() or src.lines[probe][0] in " \t"): if src.lines[probe].strip().startswith("#"): end = probe + 1 elif src.lines[probe].strip(): break probe += 1 ranges.append((start, end)) texts.append("".join(src.lines[start:end]).rstrip("\n")) return ranges, texts def remove_ranges(src, ranges): lines = list(src.lines) for start, end in sorted(ranges, reverse=True): before, after = "".join(lines[:start]).rstrip("\n"), "".join(lines[end:]).lstrip("\n") if before and after: joined = before + "\n\n\n" + after else: joined = before + "\n" if before else after lines = lines_of(joined) return "".join(lines) # ---------------------------------------------------------------- `module.name` uses def chain(node): parts = [] while isinstance(node, ast.Attribute): parts.append(node.attr) node = node.value return ".".join([node.id] + parts[::-1]) if isinstance(node, ast.Name) else None def takes(tree, module): """Whether the first part of `module` is already bound here to something else.""" root = module.split(".")[0] for node in ast.walk(tree): if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store) and node.id == root: return True if isinstance(node, ast.arg) and node.arg == root: return True if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)) and node.name == root: return True if isinstance(node, ast.ImportFrom) and any((a.asname or a.name) == root for a in node.names): return True if isinstance(node, ast.Import) and any(a.asname == root and a.name != root for a in node.names): return True return False def rewrite_uses(path, text, package, names, source, dest, is_dest, warnings, show): """`source.name` uses become `dest.name` (a bare `name` in the destination itself).""" src, tree = Src(text), parse(text, path) modules = {} # how this file spells the source module -> its import statements stars = [] for node in ast.walk(tree): if isinstance(node, ast.Import): for a in node.names: if a.name == source: modules.setdefault(a.asname or a.name, []).append(node) elif isinstance(node, ast.ImportFrom): try: module = resolve(node.level, node.module, package) except Refused: continue for a in node.names: if a.name == "*" and module == source: stars.append(node) elif a.name != "*" and f"{module}.{a.name}".lstrip(".") == source: modules.setdefault(a.asname or a.name, []).append(node) rebound = {n.id for n in ast.walk(tree) if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Store)} rebound |= {n.arg for n in ast.walk(tree) if isinstance(n, ast.arg)} edits, after = [], {} # after: import node -> statements to put behind it for node in ast.walk(tree): if isinstance(node, ast.Constant) and isinstance(node.value, str): if any(node.value == f"{source}.{n}" or node.value.startswith(f"{source}.{n}.") for n in names): warnings.append(f"{show}:{node.lineno}: the string '{node.value}' still names the old module.") if not (isinstance(node, ast.Attribute) and node.attr in names): continue spelled = chain(node.value) if spelled not in modules: continue if spelled.split(".")[0] in rebound: warnings.append(f"{show}:{node.lineno}: '{spelled}' is also a local name here; '{spelled}.{node.attr}' was not updated.") continue start, end = src.span(node) if is_dest: edits.append((start, end, node.attr)) else: if takes(tree, dest): raise Refused(f"{show} already uses the name '{dest.split('.')[0]}' for something else") edits.append((start, end, f"{dest}.{node.attr}")) for statement in modules[spelled]: after.setdefault(statement, set()).add(f"import {dest}") used = names_read([tree]) for node in stars: wanted = sorted(used & set(names)) if wanted and not is_dest: after.setdefault(node, set()).add(f"from {dest} import {', '.join(wanted)}") warnings.append(f"{show}:{node.lineno}: 'import *' no longer brings {', '.join(wanted)}; an explicit import was added.") for node, statements in after.items(): start, end = src.span(node) before = src.text[src.starts[node.lineno - 1]:start] rest = src.text[end:src.starts[node.end_lineno]].strip() if before.strip() or (rest and not rest.startswith("#")): # shares its line (`import a; a.f()`, `try: import a`) edits.append((end, end, "".join(f"; {s}" for s in sorted(statements)))) else: end = src.starts[node.end_lineno - 1] + len(src.lines[node.end_lineno - 1].rstrip("\r\n")) edits.append((end, end, "".join(f"\n{before}{s}" for s in sorted(statements)))) return splice(text, edits) # ---------------------------------------------------------------- where the code goes DEFS = (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef) def import_time(node): """The parts of a statement that run when its module is imported.""" if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): args = node.args notes = [a.annotation for a in args.posonlyargs + args.args + args.kwonlyargs + [args.vararg, args.kwarg] if a] return [n for n in node.decorator_list + args.defaults + args.kw_defaults + notes + [node.returns] if n] if isinstance(node, ast.ClassDef): head = node.decorator_list + node.bases + [k.value for k in node.keywords] return head + [part for child in node.body for part in import_time(child)] return [node] def is_main_guard(node): return isinstance(node, ast.If) and "__name__" in names_read([node.test]) def place(text, code, moved_nodes, names, path): """`text` with `code` after what it needs to be defined and before what needs it at import.""" src, tree = Src(text), parse(text, path) needs = names_read([part for n in moved_nodes for part in import_time(n)]) - set(names) # local functions and classes that read a moved name: calling them at import needs it too users, grew = set(names), True while grew: grew = False for node in tree.body: if isinstance(node, DEFS) and node.name not in users and names_read([node]) & users: users.add(node.name) grew = True lower, upper = 0, None for node in tree.body: if isinstance(node, (ast.Import, ast.ImportFrom)): bound = {(a.asname or a.name).split(".")[0] for a in node.names} elif isinstance(node, DEFS): bound = {node.name} else: bound = {n.id for n in ast.walk(node) if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Store)} if upper is None and (is_main_guard(node) or names_read(import_time(node)) & users): upper = first_line(node) - 1 if bound & needs: if upper is not None: raise Refused(f"{path} uses a moved name before what the moved code needs is defined") lower = node.end_lineno if upper is None: return (text.rstrip("\n") + "\n\n\n" if text.strip() else "") + code + "\n" while upper > lower and src.lines[upper - 1].startswith("#"): upper -= 1 # as early as the imports and the needed definitions allow when something below uses it at = upper head, tail = "".join(src.lines[:at]).rstrip("\n"), "".join(src.lines[at:]).lstrip("\n") return (head + "\n\n\n" if head else "") + code + "\n\n\n" + tail # ---------------------------------------------------------------- the move def symbols(req): """The movable names of the module; `selected` marks the one at the caret line.""" tree = parse(req["text"], "the file") line = req["line"] + 1 out = [] for node in tree.body: for name, kind in targets(node): if all(s["name"] != name for s in out): out.append({"name": name, "kind": kind, "selected": first_line(node) <= line <= node.end_lineno}) if not out: raise Refused("There are no top-level functions, classes or variables to move") return out def move(req): source, dest, names = req["source"], req["dest"], req["names"] if not names: raise Refused("Select something to move") src, tree = Src(source["text"]), parse(source["text"], source["show"]) dest_text = dest["text"] or "" dest_tree = parse(dest_text, dest["show"]) here = bindings(tree, source["package"]) there = bindings(dest_tree, dest["package"]) warnings = [] nodes = [n for n in tree.body if any(name in names for name, _ in targets(n))] missing = set(names) - {name for n in nodes for name, _ in targets(n)} if missing: raise Refused(f"'{sorted(missing)[0]}' is not a top-level function, class or variable") for name in names: if here[name].count > 1: raise Refused(f"'{name}' is assigned or defined in several places; move it by hand") for node in ast.walk(tree): if isinstance(node, ast.Global) and set(node.names) & set(names): raise Refused(f"'{sorted(set(node.names) & set(names))[0]}' is written through 'global'") for node in (n for m in nodes for n in ast.walk(m)): if isinstance(node, ast.Global) and set(node.names) - set(names): raise Refused(f"The moved code writes the global '{node.names[0]}' of its module") # the destination may already import what is moving there own_imports = {f"from {source['module']} import {n}": n for n in names} for name in names: existing = there.get(name) if existing and (existing.defined or existing.statement not in own_imports): raise Refused(f"'{name}' is already defined in {dest['show']}") # what the moved code needs where it lands read = names_read(nodes) needed, from_source = [], [] for name in sorted(read - set(names)): b = here.get(name) if b is None: continue wanted = [f"from {source['module']} import {name}"] if b.defined else b.statements if any(w.startswith(f"from {dest['module']} import ") for w in wanted): continue # it comes from the destination itself if not b.defined and b.conditional and len(wanted) > 1 and not all(w.startswith("import ") for w in wanted): wanted = wanted[:1] # `try: import ujson as json` / `except: import json` other = there.get(name) if other: # `import a.b` and `import a.c` agree on what `a` is plain = all(w.startswith("import ") and " as " not in w for w in wanted + other.statements) if other.defined or not (plain or set(wanted) & set(other.statements)): raise Refused(f"'{name}' means something else in {dest['show']}") wanted = [w for w in wanted if w not in other.statements] if wanted and b.conditional and not b.defined: warnings.append(f"'{name}' is imported conditionally; {dest['show']} imports it unconditionally.") (from_source if b.defined else needed).extend(wanted) for node in tree.body: if isinstance(node, ast.ImportFrom): if node.module == "__future__": statement = f"from __future__ import {', '.join(a.name for a in node.names)}" if statement not in ast.unparse(dest_tree).split("\n"): needed.append(statement) elif any(a.name == "*" for a in node.names): warnings.append(f"{source['show']} uses 'import *'; check that {dest['show']} imports what the moved code needs.") for name in sorted(read & {"__file__", "__name__", "__package__"}): warnings.append(f"The moved code reads {name}, which changes with the module.") ranges, blocks = cut_blocks(src, tree, nodes) # the source keeps importing what it still uses left = remove_ranges(src, ranges) left_tree = parse(left, source["show"]) exported = { c.value for n in left_tree.body if isinstance(n, (ast.Assign, ast.AnnAssign, ast.AugAssign)) if any(isinstance(t, ast.Name) and t.id == "__all__" for t in ast.walk(n)) for c in ast.walk(n) if isinstance(c, ast.Constant) } still = sorted(set(names) & (names_read([left_tree]) | exported)) if still: left = add_imports(left, [f"from {dest['module']} import {', '.join(still)}"], source["show"]) if still and from_source: warnings.append(f"{source['show']} and {dest['show']} would import each other.") # the destination: drop its imports of the moved names, add what is needed, then the code edits, dest_src = [], Src(dest_text) for node in ast.walk(dest_tree): if isinstance(node, ast.ImportFrom) and resolve(node.level, node.module, dest["package"]) == source["module"]: if any(a.name in names and a.asname for a in node.names): raise Refused(f"{dest['show']} imports a moved name under another name; remove the alias first") kept = [a for a in node.names if a.name not in names] if len(kept) == len(node.names): continue start, end = dest_src.span(node) alone = node in dest_tree.body and not dest_src.text[end:dest_src.starts[node.end_lineno]].strip() if kept: node.names = kept edits.append((start, end, ast.unparse(node))) elif alone and not node.col_offset: edits.append((dest_src.starts[node.lineno - 1], dest_src.starts[node.end_lineno], "")) else: edits.append((start, end, "pass")) new = splice(dest_text, edits) new = rewrite_uses(dest["show"], new, dest["package"], names, source["module"], dest["module"], True, warnings, dest["show"]) new = add_imports(new, needed + from_source, dest["show"]) new = place(new, "\n\n\n".join(blocks), nodes, names, dest["show"]) files = {source["path"]: left, dest["path"]: new} for path, other in req["others"].items(): try: files[path] = rewrite_uses( path, other["text"], other["package"], names, source["module"], dest["module"], False, warnings, other["show"] ) except Unparsable: warnings.append(f"{other['show']} has a syntax error and was not checked.") for path, text in files.items(): original = other_text(req, path) if text != original: try: ast.parse(text) except SyntaxError as e: raise Refused(f"The move would make {path} invalid: {e.msg} (line {e.lineno})") return {"files": files, "warnings": sorted(set(warnings), key=warnings.index)} def other_text(req, path): for side in (req["source"], req["dest"]): if side["path"] == path: return side["text"] return req["others"][path]["text"] def main(): req = json.loads(sys.stdin.buffer.read()) try: out = {"ok": True, "result": symbols(req) if req["op"] == "symbols" else move(req)} except Refused as e: out = {"ok": False, "error": str(e)} json.dump(out, sys.stdout) if __name__ == "__main__": main()