"""Private lexical module inventory; NOT a declaration atlas or Lean verification.""" import argparse from collections import Counter import gzip import hashlib import io import json from pathlib import Path, PurePosixPath import re import tarfile from verify_source import verify, PARTS class Parts(io.RawIOBase): def __init__(self, paths): self.paths, self.current = iter(paths), None def readable(self): return True def readinto(self, buffer): while True: if self.current is None: try: self.current = next(self.paths).open('rb') except StopIteration: return 0 n = self.current.readinto(buffer) if n: return n self.current.close() self.current = None def close(self): if self.current: self.current.close() super().close() def header_imports(text): # Scan only the header: nested block comments, line comments and whitespace. # Stop at the first declaration/command. Fail on unsupported import names. pos, imports = 0, [] name = re.compile(r"[\w']+(?:\.[\w']+)*") def skip(i): while i < len(text): if text[i].isspace(): i += 1 elif text.startswith('--', i): end = text.find('\n', i); i = len(text) if end == -1 else end + 1 elif text.startswith('/-', i): depth = 1; i += 2 while depth and i < len(text): if text.startswith('/-', i): depth += 1; i += 2 elif text.startswith('-/', i): depth -= 1; i += 2 else: i += 1 if depth: raise ValueError('unterminated header comment') else: break return i while True: pos = skip(pos) match = name.match(text, pos) if not match: break word = match[0] if word in {'module', 'prelude'}: pos = match.end(); continue if word in {'public', 'meta'}: pos = skip(match.end()); match = name.match(text, pos) if not match: break word = match[0] if word != 'import': break pos = skip(match.end()); match = name.match(text, pos) if not match: raise ValueError('unsupported/missing import name') imports.append(match[0]); pos = match.end() # Imports used by this source must be one name per command. Anything # following the name on the same line, except comments, is rejected. rest = text[pos:].split('\n', 1)[0].strip() if rest and not rest.startswith(('--', '/-')): raise ValueError('unsupported tokens after import name: ' + repr(rest[:100])) return sorted(set(imports)) def main(): p = argparse.ArgumentParser(description=__doc__) p.add_argument('--cache', required=True, type=Path) p.add_argument('--private-graph', required=True, type=Path) p.add_argument('--summary', required=True, type=Path) args = p.parse_args() provenance = verify(args.cache) rows, configs = {}, {} with io.BufferedReader(Parts([args.cache / n for n in PARTS])) as stream: with tarfile.open(fileobj=stream, mode='r|gz') as archive: for item in archive: if not item.isfile(): continue if item.name in {'lean/lean-toolchain', 'lean/lake-manifest.json', 'lean/lakefile.toml'}: configs[item.name] = archive.extractfile(item).read() if not (item.name.startswith('lean/src/') and item.name.endswith('.lean')): continue module = item.name[len('lean/src/'):-5].replace('/', '.') if module in rows: raise ValueError('duplicate source module') raw = archive.extractfile(item).read() try: imports = header_imports(raw.decode('utf-8-sig')) except ValueError as error: raise ValueError(item.name + ': ' + str(error)) from error rows[module] = {'module': module, 'bytes': len(raw), 'source_lines': len(raw.splitlines()), 'source_sha256': hashlib.sha256(raw).hexdigest(), 'imports': imports} seen, todo = set(), ['Main'] while todo: n = todo.pop() if n in seen: continue if n not in rows: raise ValueError('missing project entry point: ' + n) seen.add(n) todo.extend(d for d in rows[n]['imports'] if d in rows and d not in seen) external = sorted({d for n in seen for d in rows[n]['imports'] if d not in rows}) with args.private_graph.open('wb') as output: with gzip.GzipFile(fileobj=output, mode='wb', mtime=0, filename='') as gz: for n in sorted(rows): gz.write((json.dumps(rows[n], sort_keys=True) + '\n').encode()) manifest = json.loads(configs['lean/lake-manifest.json']) summary = {'scope': 'Lexical source module headers only; not elaborated declarations or theorem dependencies.', 'source_archive_sha256': provenance['archive_sha256'], 'source_modules': len(rows), 'source_bytes': sum(r['bytes'] for r in rows.values()), 'source_lines': sum(r['source_lines'] for r in rows.values()), 'module_families': dict(sorted(Counter(n.split('.')[0] for n in rows).items())), 'main_project_module_cone': len(seen), 'main_project_cone_source_lines': sum(rows[n]['source_lines'] for n in seen), 'main_direct_imports': rows['Main']['imports'], 'main_cone_external_module_imports': external, 'lean_toolchain': configs['lean/lean-toolchain'].decode().strip(), 'mathlib_revision': next(x['rev'] for x in manifest['packages'] if x['name']=='mathlib'), 'private_graph_sha256': hashlib.sha256(args.private_graph.read_bytes()).hexdigest(), 'private_graph_bytes': args.private_graph.stat().st_size, 'notes': 'A source import cone over-approximates theorem dependencies. External names were not resolved against built Mathlib/core. No source or declaration types published.'} args.summary.write_text(json.dumps(summary, indent=2) + '\n', encoding='utf-8') print(json.dumps(summary, indent=2)) if __name__ == '__main__': main()