lean-pkg 0.25.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. lean_pkg/__init__.py +3 -0
  2. lean_pkg/adapters/__init__.py +148 -0
  3. lean_pkg/adapters/github.py +65 -0
  4. lean_pkg/adapters/leansearch.py +68 -0
  5. lean_pkg/adapters/loogle.py +45 -0
  6. lean_pkg/adapters/palomar.py +170 -0
  7. lean_pkg/adapters/reservoir.py +127 -0
  8. lean_pkg/anchor.py +678 -0
  9. lean_pkg/audit.py +716 -0
  10. lean_pkg/binding_file.py +446 -0
  11. lean_pkg/blueprint.py +213 -0
  12. lean_pkg/build_scope.py +282 -0
  13. lean_pkg/ci_github.py +917 -0
  14. lean_pkg/claim_axioms.py +421 -0
  15. lean_pkg/claims.py +1155 -0
  16. lean_pkg/claims_mark.py +197 -0
  17. lean_pkg/cli.py +5208 -0
  18. lean_pkg/cli_parser.py +768 -0
  19. lean_pkg/command_tree.py +615 -0
  20. lean_pkg/comparator_config.py +990 -0
  21. lean_pkg/comparator_contracts.py +382 -0
  22. lean_pkg/comparator_receipt.py +2854 -0
  23. lean_pkg/comparator_stage.py +623 -0
  24. lean_pkg/comparator_types.py +830 -0
  25. lean_pkg/container.py +172 -0
  26. lean_pkg/core.py +1570 -0
  27. lean_pkg/coverage.py +1278 -0
  28. lean_pkg/data/stacks/lts-2026.10.yaml +73 -0
  29. lean_pkg/data/toolchain-advisories.yaml +77 -0
  30. lean_pkg/data/upgrade-breaking.yaml +20 -0
  31. lean_pkg/data/verify-workflow-pins.yaml +14 -0
  32. lean_pkg/deps_closure.py +512 -0
  33. lean_pkg/deps_fill.py +445 -0
  34. lean_pkg/dup_constants.py +448 -0
  35. lean_pkg/exercise.py +828 -0
  36. lean_pkg/exercise_forbid.py +288 -0
  37. lean_pkg/export_paths.py +77 -0
  38. lean_pkg/extract.py +1172 -0
  39. lean_pkg/extract_decls.py +501 -0
  40. lean_pkg/extract_ledger.py +1408 -0
  41. lean_pkg/extract_summary.py +132 -0
  42. lean_pkg/extract_types.py +502 -0
  43. lean_pkg/extract_write.py +138 -0
  44. lean_pkg/formalization.py +1078 -0
  45. lean_pkg/formalization_kept.py +182 -0
  46. lean_pkg/fresh_repo.py +709 -0
  47. lean_pkg/gate.py +2141 -0
  48. lean_pkg/headline.py +211 -0
  49. lean_pkg/help_topics.py +442 -0
  50. lean_pkg/holes.py +289 -0
  51. lean_pkg/host_routes.py +376 -0
  52. lean_pkg/hypotheses.py +788 -0
  53. lean_pkg/index.py +1749 -0
  54. lean_pkg/json_stdout.py +48 -0
  55. lean_pkg/lake_hygiene.py +289 -0
  56. lean_pkg/lean_diag.py +280 -0
  57. lean_pkg/lean_scan.py +1300 -0
  58. lean_pkg/ledger.py +582 -0
  59. lean_pkg/next_step.py +510 -0
  60. lean_pkg/page.py +1831 -0
  61. lean_pkg/page_html.py +153 -0
  62. lean_pkg/palomar.py +316 -0
  63. lean_pkg/palomar_check.py +1027 -0
  64. lean_pkg/port_modules.py +677 -0
  65. lean_pkg/prior_art.py +286 -0
  66. lean_pkg/producer.py +212 -0
  67. lean_pkg/producer_skew.py +208 -0
  68. lean_pkg/public_safety.py +1487 -0
  69. lean_pkg/publish.py +402 -0
  70. lean_pkg/rebase.py +984 -0
  71. lean_pkg/receipt.py +2385 -0
  72. lean_pkg/receipt_check.py +1064 -0
  73. lean_pkg/receipt_ci.py +660 -0
  74. lean_pkg/receipt_systemd.py +890 -0
  75. lean_pkg/recommended.py +232 -0
  76. lean_pkg/report.py +727 -0
  77. lean_pkg/reservoir.py +203 -0
  78. lean_pkg/scaffold.py +588 -0
  79. lean_pkg/schemas/formalization-0.4.schema.json +344 -0
  80. lean_pkg/schemas/formalization-0.4.schema.source.txt +15 -0
  81. lean_pkg/scripts/ClaimAxioms.lean +47 -0
  82. lean_pkg/scripts/ContractsOnly.lean +300 -0
  83. lean_pkg/scripts/DupConstants.lean +149 -0
  84. lean_pkg/scripts/HypProbe.lean +257 -0
  85. lean_pkg/scripts/comparator-check.sh +396 -0
  86. lean_pkg/scripts/verify-comparator.sh +135 -0
  87. lean_pkg/seal_bundle.py +647 -0
  88. lean_pkg/search.py +865 -0
  89. lean_pkg/site_profiles/easley.yaml +10 -0
  90. lean_pkg/site_profiles/github-actions.yaml +12 -0
  91. lean_pkg/sites.py +225 -0
  92. lean_pkg/stacks.py +373 -0
  93. lean_pkg/statements_module.py +217 -0
  94. lean_pkg/templates/Apache-2.0.txt +202 -0
  95. lean_pkg/toolchain_advisories.py +225 -0
  96. lean_pkg/upgrade.py +706 -0
  97. lean_pkg/verify.py +495 -0
  98. lean_pkg-0.25.0.dist-info/METADATA +93 -0
  99. lean_pkg-0.25.0.dist-info/RECORD +103 -0
  100. lean_pkg-0.25.0.dist-info/WHEEL +5 -0
  101. lean_pkg-0.25.0.dist-info/entry_points.txt +5 -0
  102. lean_pkg-0.25.0.dist-info/licenses/LICENSE +202 -0
  103. lean_pkg-0.25.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,132 @@
1
+ # lean-pkg-extract recheck --public-summary -- the public summary of an extraction ledger (proposal 0009, S5)
2
+ """The public summary of an extraction ledger: `lean-pkg-extract recheck --public-summary PATH`.
3
+
4
+ The extraction ledger is private: it names source paths, the source commit, source module and
5
+ declaration names and the reasons of drops and allowed differences. The summary
6
+ (`lean-pkg-extract-ledger-summary/1`) is what may be published: a report, written on request and never
7
+ read back as evidence. It holds the method, the SHA-256 of the ledger file it summarizes, the target
8
+ commit and the target module names; per declaration the target name (null for a DROPPED one: the name it
9
+ would have had is the mapped source name), the target module, the verdict, `target_sha256` and
10
+ `source_sha256` (a hash commitment: a holder of the source can verify it, and it tells anyone else
11
+ nothing); the same for each module's context row; and the totals. It leaves out source paths, source
12
+ module and declaration names (a rename reveals the old name), every reason, the warnings (they quote
13
+ both sides' pins) and the source commit, unless `--include-source-commit`.
14
+
15
+ Rules: written only when the recheck passes (exit 0), once (an existing path or a symbolic link is
16
+ refused, and the file is opened exclusively), never inside SRC (its work tree or git directory; the
17
+ extraction tools leave SRC unchanged), and allowed inside the target. Before it is written it is
18
+ staged beside PATH and scanned with public-safety as `decls` scans its tree (the source repository's
19
+ patterns file applies); a blocking hit refuses and nothing is written. Deterministic: keys sorted, rows
20
+ sorted by target-side values only (so their order reveals nothing about source names), no timestamp,
21
+ no host path.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import hashlib
27
+ import json
28
+ import pathlib
29
+ import shutil
30
+ import tempfile
31
+
32
+ from . import public_safety as ps
33
+
34
+ SUMMARY_SCHEMA = "lean-pkg-extract-ledger-summary/1"
35
+ SUMMARY_KEYS = ("schema", "method", "ok", "ledger_sha256", "at_ledger_commits", "source_commit", "target",
36
+ "entries", "context", "totals")
37
+ SUMMARY_ENTRY_KEYS = ("target", "target_module", "verdict", "source_sha256", "target_sha256")
38
+ SUMMARY_CONTEXT_KEYS = ("target_module", "verdict", "source_sha256", "target_sha256")
39
+ SCAN_NAME = "lean-pkg-extract-recheck"
40
+
41
+
42
+ def _inside(p: pathlib.Path, roots) -> bool:
43
+ return any(r is not None and (p == r or r in p.parents) for r in roots)
44
+
45
+
46
+ def path_refusals(arg: str, src_roots) -> list[str]:
47
+ """Why --public-summary PATH cannot be written: inside SRC (its work tree or git directory), a
48
+ symbolic link, existing, or in a missing directory. Inside the target is allowed."""
49
+ refusals = []
50
+ p = pathlib.Path(arg).expanduser()
51
+ real = p.parent.resolve() / p.name
52
+ if _inside(real, [r.resolve() if r is not None else None for r in src_roots]):
53
+ refusals.append(f"--public-summary {arg}: inside the source repository, which lean-pkg-extract leaves "
54
+ f"unchanged; write the summary outside SRC (inside the target is allowed)")
55
+ if p.is_symlink():
56
+ refusals.append(f"--public-summary {arg}: a symlink; name a new regular file")
57
+ elif p.exists():
58
+ refusals.append(f"--public-summary {arg}: exists; a summary is written once, so name a new path")
59
+ elif not real.parent.is_dir():
60
+ refusals.append(f"--public-summary {arg}: its directory does not exist")
61
+ return refusals
62
+
63
+
64
+ def summary(led: dict, ledger_bytes: bytes, at_ledger_commits: bool, include_source_commit: bool) -> dict:
65
+ """The summary of a passing recheck: `led` the recomputed ledger, `ledger_bytes` the ledger file read. A
66
+ row with no target declaration (DROPPED) has `target: null`: the name it would have had is the source
67
+ name under the map, which would reveal the source name."""
68
+ entries = [{"target": e["target"] if e["target_sha256"] is not None else None, "target_module": e["target_module"], "verdict": e["verdict"],
69
+ "source_sha256": e["source_sha256"], "target_sha256": e["target_sha256"]} for e in led["entries"]]
70
+ context = [{"target_module": c["target_module"], "verdict": c["verdict"], "source_sha256": c["source_sha256"],
71
+ "target_sha256": c["target_sha256"]} for c in led["context"]]
72
+
73
+ def order(row: dict) -> tuple:
74
+ return tuple("" if row[k] is None else row[k] for k in ("target_module", "target", "verdict",
75
+ "target_sha256", "source_sha256") if k in row)
76
+
77
+ return {
78
+ "schema": SUMMARY_SCHEMA,
79
+ "method": led["method"],
80
+ "ok": True,
81
+ "ledger_sha256": hashlib.sha256(ledger_bytes).hexdigest(),
82
+ "at_ledger_commits": at_ledger_commits,
83
+ "source_commit": led["source"]["commit"] if include_source_commit else None,
84
+ "target": {"commit": led["target"]["commit"], "modules": sorted(r["module"] for r in led["target"]["modules"])},
85
+ "entries": sorted(entries, key=order),
86
+ "context": sorted(context, key=order),
87
+ "totals": dict(led["totals"]),
88
+ }
89
+
90
+
91
+ def summary_json(s: dict) -> str:
92
+ return json.dumps(s, indent=2, sort_keys=True, ensure_ascii=False) + "\n"
93
+
94
+
95
+ def scan_summary(scan: dict) -> dict:
96
+ return {"ok": scan["ok"], "block_hits": scan["block_hits"], "warn_hits": scan["warn_hits"]}
97
+
98
+
99
+ def write(arg: str, text: str, patterns_root: pathlib.Path | None, source_repo: pathlib.Path | None
100
+ ) -> tuple[dict | None, list[str]]:
101
+ """Stage the summary beside PATH, scan it with public-safety, and write PATH exclusively when no hit
102
+ blocks. Returns (scan summary or None, refusals); on a refusal nothing is written and the staging
103
+ directory is removed."""
104
+ p = pathlib.Path(arg).expanduser()
105
+ data = text.encode("utf-8")
106
+ try:
107
+ stage = pathlib.Path(tempfile.mkdtemp(prefix=f".{p.name}.", suffix=".lean-pkg-stage", dir=p.parent))
108
+ except OSError as e:
109
+ return None, [f"--public-summary {arg}: cannot be staged ({e.strerror or e}); nothing written"]
110
+ try:
111
+ (stage / p.name).write_bytes(data)
112
+ scan = ps.scan({"name": SCAN_NAME}, stage, export=True, patterns_root=patterns_root,
113
+ source_repo=source_repo, public_allow_root=stage)
114
+ blocking = ps.blocking(scan["hits"])
115
+ if blocking:
116
+ lines = [f"public-safety: {len(blocking)} blocking hit(s) in the public summary; nothing written"]
117
+ lines += [f"public-safety:{ps.hit_line(h)}" for h in blocking]
118
+ return scan_summary(scan), lines
119
+ try:
120
+ f = open(p, "xb")
121
+ except OSError as e:
122
+ return scan_summary(scan), [f"--public-summary {arg}: cannot be written ({e.strerror or e})"]
123
+ try:
124
+ with f:
125
+ f.write(data)
126
+ except OSError as e:
127
+ p.unlink(missing_ok=True)
128
+ return scan_summary(scan), [f"--public-summary {arg}: writing failed ({e.strerror or e}); nothing "
129
+ f"written"]
130
+ return scan_summary(scan), []
131
+ finally:
132
+ shutil.rmtree(stage, ignore_errors=True)
@@ -0,0 +1,502 @@
1
+ # lean-pkg-extract ledger --method types -- the elaborated-type comparison method types/1 (proposal 0009, S4)
2
+ """The comparison method `types/1` of the extraction ledger (proposal 0009, stage S4, #329).
3
+
4
+ lean-pkg never runs Lean for it. `--emit-script DIR` writes two Lean programs, `DIR/source.lean` and
5
+ `DIR/target.lean`; the author runs each in its own checkout, at the commit the ledger compares, after
6
+ building the modules:
7
+
8
+ cd SRC && git checkout C && lake build Src.A Src.B && lake env lean --run DIR/source.lean > source.out
9
+ cd TDIR && lake build New.A New.B && lake env lean --run DIR/target.lean > target.out
10
+
11
+ and `--from-output source.out target.out` reads the two outputs back. Each program imports its side's
12
+ mapped modules (`importModules`, core Lean only) and, for every declaration the text comparison pairs
13
+ (both sides present, a named declaration), prints one canonical serialization of its elaborated type:
14
+ the `Expr` walked structurally, every constant renamed by the ledger's map on the source side (the
15
+ rename map on a name and every name under it, so generated names such as `foo.match_1` follow; else the
16
+ longest namespace prefix), binder names left out (alpha-equivalence), binder annotations kept, universe
17
+ parameters numbered by position, `mdata` dropped, private names marked as private and compared by their
18
+ user names. An inductive type (a `structure` or `class` too) carries its constructors' types. Nothing is
19
+ pretty-printed: the pretty printer's output is neither canonical nor round-trip safe.
20
+
21
+ Output contract (`lean-pkg-extract-types/1`), one JSON object per line, nothing else:
22
+
23
+ {"schema": "lean-pkg-extract-types/1", "side": "source"|"target", "script_sha256": H,
24
+ "commit": "<40 hex git HEAD of the working directory>"|null, "dirty": bool|null,
25
+ "lean": Lean.versionString, "lean_githash": Lean.githash, "count": N}
26
+ {"i": k, "decl": KEY, "kinds": ["theorem", ...], "type": SERIALIZATION} (k = 0 .. N-1, in order)
27
+ {"i": k, "decl": KEY, "missing": [NAME, ...]} (not in the environment)
28
+ {"done": N}
29
+
30
+ `script_sha256` is the SHA-256 of the program with its own hash left as the placeholder; lean-pkg
31
+ regenerates the program for the ledger it computes and refuses an output whose hash, side, commit,
32
+ declaration list or line structure does not match, a dirty or non-git checkout, two different Lean
33
+ builds, and a truncated or duplicated output. The ledger records the SHA-256 of each serialization.
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ import hashlib
39
+ import json
40
+ import pathlib
41
+ import re
42
+
43
+ from . import lean_scan
44
+
45
+ TYPES_OUTPUT_SCHEMA = "lean-pkg-extract-types/1"
46
+ SIDES = ("source", "target")
47
+ SCRIPT_FILES = {"source": "source.lean", "target": "target.lean"}
48
+ SHA_PLACEHOLDER = "__LEAN_PKG_SCRIPT_SHA256__"
49
+ DATA_PLACEHOLDER = "__LEAN_PKG_PLAN__"
50
+ # Lean's constant kinds whose elaborated type is the whole statement: a theorem's proof is irrelevant, an
51
+ # axiom and an opaque constant have no unfoldable value, an inductive type is its type and constructors.
52
+ # A `def`, `abbrev` or `instance` (kind def) has a value the types do not compare.
53
+ STATEMENT_KINDS = frozenset({"theorem", "axiom", "opaque", "inductive"})
54
+ CONST_KINDS = STATEMENT_KINDS | {"def", "quot", "constructor", "recursor"}
55
+ HEADER_KEYS = ("schema", "side", "script_sha256", "commit", "dirty", "lean", "lean_githash", "count")
56
+ TYPE_ROW_KEYS = ("i", "decl", "kinds", "type")
57
+ MISSING_ROW_KEYS = ("i", "decl", "missing")
58
+ HEX64 = re.compile(r"[0-9a-f]{64}")
59
+ HEX40 = re.compile(r"[0-9a-f]{40}")
60
+ SCHEMA_RE = re.compile(r"lean-pkg-extract-types/(\d+)")
61
+
62
+ LEAN_PROGRAM = """\
63
+ -- lean-pkg-extract types/1: the __SIDE__ side of an extraction ledger (proposal 0009). Generated; do not edit
64
+ -- (the output carries this program's hash, and lean-pkg-extract refuses an output of an edited program).
65
+ --
66
+ -- Run it in the __SIDE__ checkout, clean and at the commit the ledger compares, after building the modules:
67
+ -- lake build __BUILD__
68
+ -- lake env lean --run __FILE__ > __SIDE__.out
69
+ -- then pass both outputs to `lean-pkg-extract ledger --method types --from-output source.out target.out`.
70
+ -- It reads the compiled environment and `git rev-parse HEAD` / `git status`; it writes only to stdout.
71
+ import Lean
72
+
73
+ open Lean
74
+
75
+ namespace LeanPkgExtractTypes
76
+
77
+ def scriptSha256 : String := "__LEAN_PKG_SCRIPT_SHA256__"
78
+
79
+ /-- The plan: this side's modules, the name map (source side only) and the declarations to print. -/
80
+ def planJson : String := __LEAN_PKG_PLAN__
81
+
82
+ structure Plan where
83
+ side : String
84
+ modules : Array Name
85
+ renames : List (Name × Name)
86
+ namespaces : List (Name × Name)
87
+ decls : Array (String × Name × Array Name)
88
+
89
+ def toName (j : Json) : Except String Name := do
90
+ let parts ← j.getArr?
91
+ parts.foldlM (init := Name.anonymous) fun n c => do return Name.mkStr n (← c.getStr?)
92
+
93
+ def toPair (j : Json) : Except String (Name × Name) := do
94
+ let a ← j.getArr?
95
+ if a.size != 2 then throw "a map entry is not a pair"
96
+ return (← toName a[0]!, ← toName a[1]!)
97
+
98
+ def toDecl (j : Json) : Except String (String × Name × Array Name) := do
99
+ let key ← (← j.getObjVal? "key").getStr?
100
+ let m ← toName (← j.getObjVal? "module")
101
+ let names ← (← (← j.getObjVal? "names").getArr?).mapM toName
102
+ return (key, m, names)
103
+
104
+ def readPlan : Except String Plan := do
105
+ let j ← Json.parse planJson
106
+ return {
107
+ side := ← (← j.getObjVal? "side").getStr?
108
+ modules := ← (← (← j.getObjVal? "modules").getArr?).mapM toName
109
+ renames := (← (← (← j.getObjVal? "renames").getArr?).mapM toPair).toList
110
+ namespaces := (← (← (← j.getObjVal? "namespaces").getArr?).mapM toPair).toList
111
+ decls := ← (← (← j.getObjVal? "decls").getArr?).mapM toDecl }
112
+
113
+ def q (s : String) : String := (Json.str s).compress
114
+
115
+ /-- The entry of `tbl` whose old name is the longest prefix of `n` (`n` itself only when not `proper`). -/
116
+ def best (n : Name) (tbl : List (Name × Name)) (proper : Bool) : Option (Name × Name) :=
117
+ tbl.foldl (init := none) fun acc (o, t) =>
118
+ if o.isPrefixOf n && (!proper || o != n) then
119
+ match acc with
120
+ | some (o', _) => if o.getNumParts > o'.getNumParts then some (o, t) else acc
121
+ | none => some (o, t)
122
+ else acc
123
+
124
+ /-- A constant's name under the map: a renamed name or a name under it, else the namespace map. -/
125
+ def mapUser (p : Plan) (n : Name) : Name :=
126
+ match best n p.renames false with
127
+ | some (o, t) => n.replacePrefix o t
128
+ | none =>
129
+ match best n p.namespaces true with
130
+ | some (o, t) => n.replacePrefix o t
131
+ | none => n
132
+
133
+ def cname (p : Plan) (n : Name) : String :=
134
+ match privateToUserName? n with
135
+ | some u => "(P " ++ q (toString (mapUser p u)) ++ ")"
136
+ | none => q (toString (mapUser p n))
137
+
138
+ def idx (ps : List Name) (x : Name) : Option Nat :=
139
+ let rec go : List Name → Nat → Option Nat
140
+ | [], _ => none
141
+ | y :: ys, i => if y == x then some i else go ys (i + 1)
142
+ go ps 0
143
+
144
+ partial def lvl (ps : List Name) : Level → String
145
+ | .zero => "z"
146
+ | .succ l => "(s " ++ lvl ps l ++ ")"
147
+ | .max a b => "(m " ++ lvl ps a ++ " " ++ lvl ps b ++ ")"
148
+ | .imax a b => "(i " ++ lvl ps a ++ " " ++ lvl ps b ++ ")"
149
+ | .param x =>
150
+ match idx ps x with
151
+ | some i => "(u " ++ toString i ++ ")"
152
+ | none => "(un " ++ q (toString x) ++ ")"
153
+ | .mvar _ => "(?)"
154
+
155
+ def binfo : BinderInfo → String
156
+ | .default => "d"
157
+ | .implicit => "i"
158
+ | .strictImplicit => "s"
159
+ | .instImplicit => "c"
160
+
161
+ /-- The canonical serialization: binder names left out, universe parameters by position. -/
162
+ partial def ser (p : Plan) (ps : List Name) : Expr → String
163
+ | .bvar i => "#" ++ toString i
164
+ | .fvar _ => "(?)"
165
+ | .mvar _ => "(?)"
166
+ | .sort l => "(S " ++ lvl ps l ++ ")"
167
+ | .const n ls => "(C " ++ cname p n ++ " [" ++ " ".intercalate (ls.map (lvl ps)) ++ "])"
168
+ | .app f a => "(A " ++ ser p ps f ++ " " ++ ser p ps a ++ ")"
169
+ | .lam _ t b bi => "(L " ++ binfo bi ++ " " ++ ser p ps t ++ " " ++ ser p ps b ++ ")"
170
+ | .forallE _ t b bi => "(F " ++ binfo bi ++ " " ++ ser p ps t ++ " " ++ ser p ps b ++ ")"
171
+ | .letE _ t v b _ => "(E " ++ ser p ps t ++ " " ++ ser p ps v ++ " " ++ ser p ps b ++ ")"
172
+ | .lit (.natVal n) => "(N " ++ toString n ++ ")"
173
+ | .lit (.strVal s) => "(T " ++ q s ++ ")"
174
+ | .mdata _ e => ser p ps e
175
+ | .proj s i e => "(J " ++ cname p s ++ " " ++ toString i ++ " " ++ ser p ps e ++ ")"
176
+
177
+ def kindOf : ConstantInfo → String
178
+ | .axiomInfo _ => "axiom"
179
+ | .defnInfo _ => "def"
180
+ | .thmInfo _ => "theorem"
181
+ | .opaqueInfo _ => "opaque"
182
+ | .quotInfo _ => "quot"
183
+ | .inductInfo _ => "inductive"
184
+ | .ctorInfo _ => "constructor"
185
+ | .recInfo _ => "recursor"
186
+
187
+ def typeOf (p : Plan) (ci : ConstantInfo) : String :=
188
+ "(" ++ toString ci.levelParams.length ++ " " ++ ser p ci.levelParams ci.type ++ ")"
189
+
190
+ /-- A declaration by name, or by its private name in its module. -/
191
+ def find? (env : Environment) (m n : Name) : Option ConstantInfo :=
192
+ (env.find? n).orElse fun _ => env.find? (Name.mkNum (privateHeader ++ m) 0 ++ n)
193
+
194
+ /-- (kind, serialization) of one constant: its mapped name and type; an inductive's constructors too. -/
195
+ def decl (p : Plan) (env : Environment) (m n : Name) : Option (String × String) := do
196
+ let ci ← find? env m n
197
+ let mut out := "(D " ++ cname p ci.name ++ " " ++ typeOf p ci
198
+ if let .inductInfo v := ci then
199
+ for c in v.ctors do
200
+ match env.find? c with
201
+ | some cc => out := out ++ " (K " ++ cname p c ++ " " ++ typeOf p cc ++ ")"
202
+ | none => out := out ++ " (K? " ++ cname p c ++ ")"
203
+ return (kindOf ci, out ++ ")")
204
+
205
+ /-- The first line of a git command's output in the working directory, or none. -/
206
+ def git (args : Array String) : IO (Option String) := do
207
+ try
208
+ let o ← IO.Process.output { cmd := "git", args := args }
209
+ return if o.exitCode == 0 then some ((o.stdout.splitOn "\\n").headD "") else none
210
+ catch _ => return none
211
+
212
+ end LeanPkgExtractTypes
213
+
214
+ open LeanPkgExtractTypes in
215
+ def main : IO UInt32 := do
216
+ let p ← match readPlan with
217
+ | .ok p => pure p
218
+ | .error e => IO.eprintln s!"lean-pkg-extract types: unreadable plan: {e}"; return 2
219
+ initSearchPath (← findSysroot)
220
+ let commit ← git #["rev-parse", "--verify", "HEAD^{commit}"]
221
+ let status ← git #["status", "--porcelain", "--untracked-files=no"]
222
+ let env ← importModules (p.modules.map fun m => ({ module := m } : Import)) {}
223
+ IO.println (Json.mkObj [("schema", "lean-pkg-extract-types/1"), ("side", p.side),
224
+ ("script_sha256", scriptSha256), ("commit", match commit with | some c => Json.str c | none => Json.null),
225
+ ("dirty", match status with | some s => Json.bool (!s.isEmpty) | none => Json.null),
226
+ ("lean", Lean.versionString), ("lean_githash", Lean.githash), ("count", toJson p.decls.size)]).compress
227
+ let mut i : Nat := 0
228
+ for (key, m, names) in p.decls do
229
+ let mut kinds : Array Json := #[]
230
+ let mut parts : Array String := #[]
231
+ let mut missing : Array Json := #[]
232
+ for n in names do
233
+ match decl p env m n with
234
+ | some (k, s) =>
235
+ kinds := kinds.push k
236
+ parts := parts.push s
237
+ | none => missing := missing.push (toString n)
238
+ if missing.isEmpty then
239
+ IO.println (Json.mkObj [("i", toJson i), ("decl", key), ("kinds", Json.arr kinds),
240
+ ("type", " ".intercalate parts.toList)]).compress
241
+ else
242
+ IO.println (Json.mkObj [("i", toJson i), ("decl", key), ("missing", Json.arr missing)]).compress
243
+ i := i + 1
244
+ IO.println (Json.mkObj [("done", toJson p.decls.size)]).compress
245
+ return 0
246
+ """
247
+
248
+
249
+ def _sha(text: str) -> str:
250
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()
251
+
252
+
253
+ def _components(name: str) -> list[str]:
254
+ """A Lean name's components as Lean stores them («» removed)."""
255
+ parts = lean_scan.split_name(name) or [name]
256
+ return [p[1:-1] if p.startswith("«") and p.endswith("»") else p for p in parts]
257
+
258
+
259
+ def lean_string(s: str) -> str:
260
+ """A Lean string literal holding s."""
261
+ out = []
262
+ for ch in s:
263
+ if ch == "\\":
264
+ out.append("\\\\")
265
+ elif ch == '"':
266
+ out.append('\\"')
267
+ elif ch == "\n":
268
+ out.append("\\n")
269
+ elif ch == "\t":
270
+ out.append("\\t")
271
+ elif ord(ch) < 0x20 or ord(ch) == 0x7f:
272
+ out.append(f"\\x{ord(ch):02x}")
273
+ else:
274
+ out.append(ch)
275
+ return '"' + "".join(out) + '"'
276
+
277
+
278
+ # ----------------------------------------------------------------------------------------------------
279
+ # the plan: which declarations are compared, and the program of each side
280
+
281
+ def plan(led: dict, names: dict) -> list[dict]:
282
+ """The entries the types compare, in ledger order: both sides present and named (not an anonymous
283
+ instance or an example). `names` maps a source key to (source names, target names), as `compute`
284
+ fills it: the source names in the order of their mapped names, the target names sorted."""
285
+ out = []
286
+ for e in led["entries"]:
287
+ if e["source"] is None or e["target_sha256"] is None or e["verdict"] not in ("IDENTICAL", "DIFFERS"):
288
+ continue
289
+ pair = names.get(e["source"])
290
+ if not pair or not pair[0] or not pair[1]:
291
+ continue
292
+ out.append({"source": e["source"], "target": e["target"], "source_module": e["source_module"],
293
+ "target_module": e["target_module"], "source_names": list(pair[0]),
294
+ "target_names": list(pair[1])})
295
+ return out
296
+
297
+
298
+ def program(side: str, items: list[dict], led: dict) -> tuple[str, str]:
299
+ """(the Lean program of one side, its script_sha256)."""
300
+ modules = sorted(r["module"] for r in led[side]["modules"])
301
+ m = led["map"]
302
+ data = {"side": side,
303
+ "modules": [_components(x) for x in modules],
304
+ "renames": [[_components(r["from"]), _components(r["to"])] for r in m["renames"]] if side == "source" else [],
305
+ "namespaces": ([[_components(r["from"]), _components(r["to"])] for r in m["namespaces"]]
306
+ if side == "source" else []),
307
+ "decls": [{"key": it[side], "module": _components(it[f"{side}_module"]),
308
+ "names": [_components(n) for n in it[f"{side}_names"]]} for it in items]}
309
+ text = (LEAN_PROGRAM.replace("__SIDE__", side).replace("__FILE__", SCRIPT_FILES[side])
310
+ .replace("__BUILD__", " ".join(modules) or "(no module)"))
311
+ text = text.replace(DATA_PLACEHOLDER, lean_string(json.dumps(data, sort_keys=True, ensure_ascii=False,
312
+ separators=(",", ":"))), 1)
313
+ sha = _sha(text)
314
+ head, sep, tail = text.partition(SHA_PLACEHOLDER)
315
+ return head + sha + tail, sha
316
+
317
+
318
+ def programs(led: dict, names: dict) -> tuple[list[dict], dict[str, tuple[str, str]]]:
319
+ items = plan(led, names)
320
+ return items, {side: program(side, items, led) for side in SIDES}
321
+
322
+
323
+ # ----------------------------------------------------------------------------------------------------
324
+ # reading an output back: strict
325
+
326
+ def read_output(data: bytes, where: str, refusals: list[str]) -> dict | None:
327
+ """{"header": {...}, "rows": [...]} of one output, or None (refusals say why)."""
328
+ n0 = len(refusals)
329
+ try:
330
+ text = data.decode("utf-8")
331
+ except UnicodeDecodeError:
332
+ refusals.append(f"{where}: not UTF-8")
333
+ return None
334
+ if not text:
335
+ refusals.append(f"{where}: empty (did the program run? its errors go to stderr)")
336
+ return None
337
+ if not text.endswith("\n"):
338
+ refusals.append(f"{where}: truncated (no final newline)")
339
+ return None
340
+ lines = text[:-1].split("\n")
341
+ objs = []
342
+ from . import extract as ex
343
+ for k, line in enumerate(lines, 1):
344
+ obj, err = ex.load_json_strict(line.encode("utf-8"), f"{where} line {k}")
345
+ if err or not isinstance(obj, dict):
346
+ refusals.append(f"{where} line {k}: not a line the program writes ({err or 'not an object'}); "
347
+ f"send only its stdout to the file")
348
+ return None
349
+ objs.append(obj)
350
+ head = objs[0]
351
+ schema = head.get("schema")
352
+ if schema != TYPES_OUTPUT_SCHEMA:
353
+ m = SCHEMA_RE.fullmatch(schema) if isinstance(schema, str) else None
354
+ if m and int(m.group(1)) > 1:
355
+ refusals.append(f"{where}: schema {schema} is newer than this lean-pkg reads ({TYPES_OUTPUT_SCHEMA}): "
356
+ f"upgrade lean-pkg")
357
+ else:
358
+ refusals.append(f"{where}: the first line is not a {TYPES_OUTPUT_SCHEMA} header")
359
+ return None
360
+ if not ex._keys(head, HEADER_KEYS, HEADER_KEYS, f"{where} header", refusals):
361
+ return None
362
+ if head["side"] not in SIDES:
363
+ refusals.append(f"{where}: side {head['side']!r} is not source or target")
364
+ if not (isinstance(head["script_sha256"], str) and HEX64.fullmatch(head["script_sha256"])):
365
+ refusals.append(f"{where}: script_sha256 is not a SHA-256")
366
+ if not (head["commit"] is None or (isinstance(head["commit"], str) and HEX40.fullmatch(head["commit"]))):
367
+ refusals.append(f"{where}: commit is not a 40-hex commit or null")
368
+ if head["dirty"] not in (True, False, None):
369
+ refusals.append(f"{where}: dirty is not a boolean or null")
370
+ for k in ("lean", "lean_githash"):
371
+ if not isinstance(head[k], str):
372
+ refusals.append(f"{where}: {k} is not a string")
373
+ count = head["count"]
374
+ if type(count) is not int or count < 0:
375
+ refusals.append(f"{where}: count is not a non-negative integer")
376
+ return None
377
+ if len(refusals) != n0:
378
+ return None
379
+ body, last = objs[1:-1], objs[-1] if len(objs) > 1 else None
380
+ if last is None or set(last) != {"done"}:
381
+ refusals.append(f"{where}: truncated (no final done line; {len(objs) - 1} of {count} declaration(s) "
382
+ f"after the header)")
383
+ return None
384
+ if last["done"] != count or type(last["done"]) is not int:
385
+ refusals.append(f"{where}: the done line says {last['done']!r}, the header {count}")
386
+ return None
387
+ rows, seen = [], set()
388
+ for k, r in enumerate(body):
389
+ w = f"{where} line {k + 2}"
390
+ keys = TYPE_ROW_KEYS if "kinds" in r or "type" in r else MISSING_ROW_KEYS
391
+ if not ex._keys(r, keys, keys, w, refusals):
392
+ continue
393
+ i = r["i"]
394
+ if type(i) is not int:
395
+ refusals.append(f"{w}: i is not an integer")
396
+ continue
397
+ if i in seen:
398
+ refusals.append(f"{w}: declaration {i} is duplicated")
399
+ continue
400
+ seen.add(i)
401
+ if i != len(rows):
402
+ refusals.append(f"{w}: declaration {i} out of order (expected {len(rows)})")
403
+ continue
404
+ if not isinstance(r["decl"], str):
405
+ refusals.append(f"{w}: decl is not a string")
406
+ if "missing" in r:
407
+ if not (isinstance(r["missing"], list) and r["missing"] and all(isinstance(x, str) for x in r["missing"])):
408
+ refusals.append(f"{w}: missing is not a non-empty list of names")
409
+ else:
410
+ if not (isinstance(r["kinds"], list) and r["kinds"] and all(x in CONST_KINDS for x in r["kinds"])):
411
+ refusals.append(f"{w}: kinds is not a non-empty list of Lean constant kinds")
412
+ if not (isinstance(r["type"], str) and r["type"].startswith("(D ")):
413
+ refusals.append(f"{w}: type is not a serialization the program writes")
414
+ rows.append(r)
415
+ if len(refusals) == n0 and len(rows) != count:
416
+ refusals.append(f"{where}: {len(rows)} declaration line(s), the header says {count}")
417
+ return {"header": head, "rows": rows} if len(refusals) == n0 else None
418
+
419
+
420
+ def load_outputs(paths: list[str], refusals: list[str]) -> dict[str, dict]:
421
+ """{side: output} of the --from-output files: one per side, each read strictly."""
422
+ got: dict[str, dict] = {}
423
+ where_of: dict[str, str] = {}
424
+ for p in paths:
425
+ path = pathlib.Path(p).expanduser()
426
+ try:
427
+ data = path.read_bytes() if path.is_file() else None
428
+ except OSError:
429
+ data = None
430
+ if data is None:
431
+ refusals.append(f"--from-output {p}: not a readable regular file")
432
+ continue
433
+ out = read_output(data, f"--from-output {p}", refusals)
434
+ if out is None:
435
+ continue
436
+ side = out["header"]["side"]
437
+ if side in got:
438
+ refusals.append(f"--from-output {p}: a second {side} output (the first is {where_of[side]})")
439
+ continue
440
+ got[side], where_of[side] = out, p
441
+ for side in SIDES:
442
+ if side not in got and not any(r.startswith("--from-output") for r in refusals):
443
+ refusals.append(f"--from-output: no {side} output (pass the output of {SCRIPT_FILES[side]})")
444
+ for side in got:
445
+ got[side]["path"] = where_of[side]
446
+ return got
447
+
448
+
449
+ def bind(outputs: dict, items: list[dict], progs: dict, led: dict, refusals: list[str],
450
+ warnings: list[str]) -> dict | None:
451
+ """{source key: (source type sha256, target type sha256, statement?)} from the two outputs, after
452
+ checking that each was written by this ledger's program at the ledger's commit; None on a refusal."""
453
+ n0 = len(refusals)
454
+ for side in SIDES:
455
+ o = outputs[side]
456
+ h, where = o["header"], f"--from-output {o['path']} ({side})"
457
+ if h["script_sha256"] != progs[side][1]:
458
+ refusals.append(f"{where}: written by another program (script_sha256 {h['script_sha256'][:12]}, this "
459
+ f"ledger's {side} program is {progs[side][1][:12]}): emit it again with --emit-script "
460
+ f"and rerun it")
461
+ want = led[side]["commit"]
462
+ if h["commit"] is None:
463
+ refusals.append(f"{where}: no commit (the program ran outside a git checkout); run it in the "
464
+ f"{side} checkout at {want}")
465
+ elif h["commit"] != want:
466
+ refusals.append(f"{where}: run at commit {h['commit']}, but the ledger compares {want}")
467
+ if h["dirty"] is not False:
468
+ refusals.append(f"{where}: the checkout had uncommitted changes to tracked files (dirty "
469
+ f"{h['dirty']!r}); its types are not those of {h['commit']}")
470
+ rows = o["rows"]
471
+ if [r["decl"] for r in rows] != [it[side] for it in items]:
472
+ refusals.append(f"{where}: its declarations do not match the ledger's ({len(rows)} printed, "
473
+ f"{len(items)} compared)")
474
+ continue
475
+ for r in rows:
476
+ if "missing" in r:
477
+ refusals.append(f"{where}: {r['decl']}: {', '.join(r['missing'])} not in the environment (build "
478
+ f"the modules before running the program)")
479
+ elif len(r["kinds"]) != len(items[r["i"]][f"{side}_names"]):
480
+ refusals.append(f"{where}: {r['decl']}: {len(r['kinds'])} kind(s) for "
481
+ f"{len(items[r['i']][f'{side}_names'])} name(s)")
482
+ pin = led[side]["lean_toolchain"]
483
+ if pin is not None and not (pin == f"v{h['lean']}" or pin.endswith(f":v{h['lean']}")):
484
+ warnings.append(f"types/1: the {side} program ran under Lean {h['lean']}, the {side} pins {pin}")
485
+ s, t = outputs["source"]["header"], outputs["target"]["header"]
486
+ if (s["lean"], s["lean_githash"]) != (t["lean"], t["lean_githash"]):
487
+ refusals.append(f"--from-output: the two programs ran under different Lean builds (source {s['lean']} "
488
+ f"{s['lean_githash'][:12]}, target {t['lean']} {t['lean_githash'][:12]}); an elaborated "
489
+ f"type is only comparable under one toolchain")
490
+ if len(refusals) != n0:
491
+ return None
492
+ out = {}
493
+ for it, a, b in zip(items, outputs["source"]["rows"], outputs["target"]["rows"], strict=True):
494
+ statement = all(k in STATEMENT_KINDS for k in a["kinds"] + b["kinds"])
495
+ out[it["source"]] = (_sha(a["type"]), _sha(b["type"]), statement)
496
+ return out
497
+
498
+
499
+ def types_block(outputs: dict, progs: dict) -> dict:
500
+ s = outputs["source"]["header"]
501
+ return {"lean": s["lean"], "lean_githash": s["lean_githash"],
502
+ "source_script_sha256": progs["source"][1], "target_script_sha256": progs["target"][1]}