"""install.py joined from the modules of the installer/ package.""" from __future__ import annotations import ast import heapq import sys from collections.abc import Iterator from dataclasses import dataclass, field from pathlib import Path PACKAGE = "installer" OUTPUT = "install.py" COMMAND = "python scripts/build_installer.py" SHEBANG = "#!/usr/bin/env python3\n" NOTICE = ( "# Generated by scripts/build_installer.py from the installer/ package. Edit\n" "# the modules there and run the script: a change made here is overwritten.\n" ) # C extensions a Python built without their libraries lacks. The installer # imports them behind a guard that says so, instead of stopping on a # ModuleNotFoundError traceback. GUARDED = frozenset({"unicodedata", "zlib"}) GUARD = ( "# Built as C extensions that a Python compiled without their libraries\n" "# lacks: the run stopped on a ModuleNotFoundError traceback.\n" "try:\n" "{imports}" "except ImportError as _missing:\n" ' print(f"Error: this Python was built without its {{_missing.name}} module, which "\n' ' "the installer needs. Run it with another Python 3.8 or newer.", file=sys.stderr)\n' " sys.exit(1)\n" ) LINE_LENGTH = 120 MARKER_WIDTH = 79 _SCOPES = (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda, ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp) class BuildError(Exception): """The package cannot be joined into one module.""" @dataclass class Module: name: str body: str statements: list[ast.stmt] plain: set[tuple[str, str | None]] = field(default_factory=set) froms: set[tuple[str, str]] = field(default_factory=set) imports: dict[str, set[str]] = field(default_factory=dict) type_imports: dict[str, set[str]] = field(default_factory=dict) defines: set[str] = field(default_factory=set) def _is_docstring(node: ast.stmt) -> bool: return (isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant) and isinstance(node.value.value, str)) def _is_type_checking_block(node: ast.stmt) -> bool: return (isinstance(node, ast.If) and isinstance(node.test, ast.Name) and node.test.id == "TYPE_CHECKING" and not node.orelse) def _is_stdlib(module: str) -> bool: return module.split(".")[0] in sys.stdlib_module_names def _package_import(module: Module, node: ast.ImportFrom, where: str, type_only: bool) -> None: """Record an import from another module of the package.""" parts = (node.module or "").split(".") if node.level or len(parts) != 2 or parts[0] != PACKAGE: raise BuildError(f"{where}:{node.lineno}: import from {PACKAGE}. by its full name") for alias in node.names: if alias.asname and alias.asname != alias.name: raise BuildError(f"{where}:{node.lineno}: {alias.name} imported as {alias.asname}: " "one namespace keeps one name") target = module.type_imports if type_only else module.imports target.setdefault(parts[1], set()).update(alias.name for alias in node.names) def _stdlib_import(module: Module, node: ast.Import | ast.ImportFrom, where: str) -> None: if isinstance(node, ast.Import): for alias in node.names: if not _is_stdlib(alias.name): raise BuildError(f"{where}:{node.lineno}: {alias.name} is not in the standard library") module.plain.add((alias.name, alias.asname)) return for alias in node.names: if alias.asname and alias.asname != alias.name: raise BuildError(f"{where}:{node.lineno}: {alias.name} imported as {alias.asname}") module.froms.add((node.module or "", alias.name)) def _read_header(module: Module, header: list[ast.stmt], where: str) -> None: for node in header: if isinstance(node, ast.If): for sub in node.body: if not isinstance(sub, ast.ImportFrom): raise BuildError(f"{where}:{sub.lineno}: a TYPE_CHECKING block holds imports only") _package_import(module, sub, where, type_only=True) elif isinstance(node, ast.ImportFrom) and node.module == "__future__": continue elif isinstance(node, ast.ImportFrom) and (node.level or not _is_stdlib(node.module or "")): _package_import(module, node, where, type_only=False) elif isinstance(node, (ast.Import, ast.ImportFrom)): _stdlib_import(module, node, where) def _check_nested_imports(statements: list[ast.stmt], where: str) -> None: """Imports below the header are joined as written: inside functions, standard library only.""" for statement in statements: for node in ast.walk(statement): if isinstance(node, ast.Import): names = [alias.name for alias in node.names] elif isinstance(node, ast.ImportFrom): names = [node.module or "." * node.level] else: continue for name in names: if node.col_offset == 0 or not _is_stdlib(name): raise BuildError(f"{where}:{node.lineno}: import {name} below the header " "(module imports go first, nested ones from the standard library)") def _header_length(tree: ast.Module, where: str) -> int: """How many leading statements are the docstring, the imports and the TYPE_CHECKING block.""" body = tree.body if not body or not _is_docstring(body[0]): raise BuildError(f"{where}: no module docstring") count = 1 while count < len(body) and (isinstance(body[count], (ast.Import, ast.ImportFrom)) or _is_type_checking_block(body[count])): count += 1 future = any(isinstance(node, ast.ImportFrom) and node.module == "__future__" and any(alias.name == "annotations" for alias in node.names) for node in body[:count]) if not future: raise BuildError(f"{where}: no 'from __future__ import annotations', which install.py holds") return count def _module_scope(node: ast.AST) -> Iterator[ast.AST]: """The nodes of the module scope, the scopes it opens yielded but not entered.""" stack = [node] while stack: current = stack.pop() yield current if current is not node and isinstance(current, _SCOPES): continue if isinstance(current, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)): continue stack.extend(ast.iter_child_nodes(current)) def _defined_names(statements: list[ast.stmt]) -> set[str]: names: set[str] = set() for statement in statements: for node in _module_scope(statement): if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): names.add(node.name) elif isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store): names.add(node.id) elif isinstance(node, ast.ExceptHandler) and node.name: names.add(node.name) return names def read_module(path: Path) -> Module: where = f"{PACKAGE}/{path.name}" source = path.read_text(encoding="utf-8") tree = ast.parse(source, filename=where) count = _header_length(tree, where) lines = source.splitlines(keepends=True) start = tree.body[count - 1].end_lineno or 0 module = Module(path.stem, "".join(lines[start:]).strip("\n"), tree.body[count:]) _read_header(module, tree.body[1:count], where) _check_nested_imports(module.statements, where) module.defines = _defined_names(module.statements) if "TYPE_CHECKING" in {node.id for statement in module.statements for node in ast.walk(statement) if isinstance(node, ast.Name)}: raise BuildError(f"{where}: TYPE_CHECKING read below the header") return module def read_package(package: Path) -> dict[str, Module]: modules = {path.stem: read_module(path) for path in sorted(package.glob("*.py")) if path.name != "__init__.py"} owners: dict[str, str] = {} imported = {alias or name.split(".")[0] for module in modules.values() for name, alias in module.plain} imported |= {name for module in modules.values() for _source, name in module.froms} for module in modules.values(): for name in sorted(module.defines): if name in owners: raise BuildError(f"{name} is defined in {owners[name]}.py and {module.name}.py") if name in imported: raise BuildError(f"{module.name}.py defines {name}, a name the standard library imports bind") owners[name] = module.name for module in modules.values(): for other, names in sorted([*module.imports.items(), *module.type_imports.items()]): if other not in modules or other == module.name: raise BuildError(f"{module.name}.py imports from {PACKAGE}.{other}, not another module of it") for name in sorted(names - modules[other].defines): raise BuildError(f"{module.name}.py imports {name} from {other}.py, which does not define it") return modules def module_order(modules: dict[str, Module]) -> list[str]: """Each module after the ones it imports outside TYPE_CHECKING, ties in name order.""" waiting = {name: len(module.imports) for name, module in modules.items()} users: dict[str, set[str]] = {name: set() for name in modules} for name, module in modules.items(): for dep in module.imports: users[dep].add(name) ready = [name for name, count in waiting.items() if count == 0] heapq.heapify(ready) order: list[str] = [] while ready: name = heapq.heappop(ready) order.append(name) for user in users[name]: waiting[user] -= 1 if waiting[user] == 0: heapq.heappush(ready, user) if len(order) != len(modules): cycle = sorted(name for name, count in waiting.items() if count) raise BuildError(f"import cycle among {', '.join(cycle)}") return order def _loads_at_import(statement: ast.stmt) -> Iterator[ast.Name]: """The names a statement reads when the module runs, not when its functions are called.""" stack: list[ast.AST] = [statement] while stack: node = stack.pop() if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)): args = node.args stack.extend(default for default in [*args.defaults, *args.kw_defaults] if default is not None) stack.extend(getattr(node, "decorator_list", [])) continue if isinstance(node, ast.AnnAssign): stack.extend(child for child in (node.target, node.value) if child is not None) continue if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load): yield node stack.extend(ast.iter_child_nodes(node)) def check_import_time(modules: dict[str, Module], order: list[str]) -> None: position = {name: index for index, name in enumerate(order)} owners = {name: module.name for module in modules.values() for name in module.defines} for module in modules.values(): for statement in module.statements: for node in _loads_at_import(statement): owner = owners.get(node.id) if owner is not None and position[owner] > position[module.name]: raise BuildError(f"{module.name}.py:{node.lineno}: {node.id} is read at import time " f"but {owner}.py comes later") def _type_key(name: str) -> tuple[int, str]: if len(name) > 1 and name.isupper(): return (0, name) return (1 if name[0].isupper() else 2, name) def _from_line(module: str, names: set[str]) -> str: ordered = sorted(names, key=_type_key) line = f"from {module} import {', '.join(ordered)}" if len(line) <= LINE_LENGTH: return line + "\n" return f"from {module} import (\n" + "".join(f" {name},\n" for name in ordered) + ")\n" def import_header(modules: dict[str, Module]) -> tuple[str, str]: """The merged standard library imports, and the guard of the C extensions among them.""" plain = {entry for module in modules.values() for entry in module.plain} guarded = sorted(name for name, alias in plain if name in GUARDED and alias is None) lines = [f"import {name}" + (f" as {alias}" if alias else "") + "\n" for name, alias in sorted(plain, key=lambda entry: (entry[0].lower(), entry[1] or "")) if name not in guarded] froms: dict[str, set[str]] = {} for module in modules.values(): for source, name in module.froms: if (source, name) != ("typing", "TYPE_CHECKING"): froms.setdefault(source, set()).add(name) lines += [_from_line(source, names) for source, names in sorted(froms.items())] guard = GUARD.format(imports="".join(f" import {name}\n" for name in guarded)) if guarded else "" return "".join(lines), guard def _marker(name: str) -> str: head = f"# --- {PACKAGE}/{name}.py " return head + "-" * max(3, MARKER_WIDTH - len(head)) + "\n" def _docstring(package: Path) -> str: text = (package / "__init__.py").read_text(encoding="utf-8").strip("\n") body = ast.parse(text).body if len(body) != 1 or not _is_docstring(body[0]): raise BuildError(f"{PACKAGE}/__init__.py holds the docstring of install.py and nothing else") return text + "\n" def build(package: Path) -> str: """install.py as the package gives it.""" docstring = _docstring(package) modules = read_package(package) order = module_order(modules) check_import_time(modules, order) imports, guard = import_header(modules) parts = [SHEBANG, NOTICE, docstring, "from __future__ import annotations\n\n", imports] if guard: parts += ["\n", guard] for name in order: if modules[name].body: parts += ["\n\n", _marker(name), "\n", modules[name].body, "\n"] return "".join(parts)