#!/usr/bin/env python3 """Audit source imports from modules with headline-used declarations.""" import argparse import csv import io import re import subprocess from collections import Counter, defaultdict, deque from pathlib import Path TABLES = Path(__file__).resolve().parent ROOT = TABLES.parents[1] CLASSIFICATIONS = ("direct", "transitive_only", "unimported") HEADER_TOKEN = re.compile(r"\s+|--[^\n]*|/-|(?P[\w']+(?:\.[\w']+)*)") COMMENT_EDGE = re.compile(r"/-|-/") def header_words(source): cursor = 0 while match := HEADER_TOKEN.match(source, cursor): cursor = match.end() if match["word"]: yield match["word"] elif match[0] == "/-": depth = 1 while depth: edge = COMMENT_EDGE.search(source, cursor) if edge is None: raise ValueError("Unclosed block comment") cursor = edge.end() depth += 1 if edge[0] == "/-" else -1 def source_imports(path): words = header_words(path.read_text(encoding="utf-8-sig")) word = next(words, None) if word == "module": word = next(words, None) if word == "prelude": word = next(words, None) while word is not None: if word == "public": word = next(words, None) if word == "meta": word = next(words, None) if word != "import": return module = next(words, None) if module == "all": module = next(words, None) if module is None: raise ValueError(f"Missing or unsupported import name in {path}") yield module word = next(words, None) def collect_sources(): tracked = subprocess.check_output( ["git", "ls-files", "-z", "--", "*.lean"], cwd=ROOT, text=True ) sources = {} for entry in tracked.split("\0")[:-1]: path = Path(entry) sources[".".join(path.with_suffix("").parts)] = path return sources def read_usage(sources): usage = {} with (ROOT / "verification/module-usage.tsv").open(encoding="utf-8") as stream: for row in csv.DictReader(stream, delimiter="\t"): name = row["module"] if name not in sources or name in usage: raise ValueError(f"Unknown or duplicate module in usage table: {name}") usage[name] = int(row["used"]) return usage def shortest_paths(imports, reached): # Each reached module starts at distance zero. The first visit gives a shortest path. visits = {module: (0, "") for module in sorted(reached)} pending = deque(visits) while pending: importer = pending.popleft() distance, _ = visits[importer] for imported in imports[importer]: if imported in imports and imported not in visits: visits[imported] = distance + 1, importer pending.append(imported) return visits def area_for(folder): parts = Path(folder).parts return "/".join(parts[:2]) if parts and parts[0] == "YM" else folder def tsv(header, rows): output = io.StringIO() writer = csv.writer(output, delimiter="\t", lineterminator="\n") writer.writerow(header) writer.writerows(rows) return output.getvalue().encode("utf-8") def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--check", action="store_true", help="Compare with both checked-in tables") args = parser.parse_args() sources = collect_sources() imports = {module: tuple(source_imports(ROOT / path)) for module, path in sources.items()} usage = read_usage(sources) reached = {module for module, used in usage.items() if used > 0} visits = shortest_paths(imports, reached) module_rows = [] folder_counts = defaultdict(Counter) totals = Counter() for module in sorted(usage.keys() - reached): path = sources[module] distance, importer = visits.get(module, (0, "")) if distance == 1: classification = "direct" elif distance > 1: classification = "transitive_only" else: classification = "unimported" module_rows.append((module, path.as_posix(), classification, distance or "", importer)) folder_counts[path.parent.as_posix()][classification] += 1 totals[classification] += 1 folder_rows = [ (folder, area_for(folder), *(counts[label] for label in CLASSIFICATIONS), sum(counts.values())) for folder, counts in sorted(folder_counts.items()) ] tables = { "unreached-modules.tsv": tsv( ("module", "source", "classification", "distance", "imported_by"), module_rows ), "unreached-modules-by-folder.tsv": tsv( ("folder", "area", *CLASSIFICATIONS, "total"), folder_rows ), } for name, data in tables.items(): path = TABLES / name if args.check: if not path.exists() or path.read_bytes() != data: parser.exit(1, f"{name} differs. Regenerate the tables and inspect the source changes.\n") else: path.write_bytes(data) print(f"{len(sources)} Lean files, {sum(map(len, imports.values()))} source import statements") print(f"{len(usage)} usage rows: {len(reached)} reached, {len(module_rows)} with zero usage") print(", ".join(f"{label}={totals[label]}" for label in CLASSIFICATIONS)) print(f"Both tables {'match' if args.check else 'written'}.") if __name__ == "__main__": main()