diff --git a/.gitignore b/.gitignore index f89e5d0..dce6fa0 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,7 @@ lean/scratch/ # Generated Marqdo cache directories are per-user artifacts. /.marqdo/ + +# Backend scratch/build state generated at runtime +lean/.marqdo-gen/ +lean/MarqdoProof/Generated/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..60cb4f1 --- /dev/null +++ b/README.md @@ -0,0 +1,141 @@ +# marqdo-prove + +Static, link-driven mathematical proof checking for Marqdo knowledge documents. + +A `.mq.md` document stays ordinary, readable Markdown. A Knowledge H2 that also +has a direct `### 证明依赖` section is a *proof target*: its single display math +block is compiled to a Lean 4 proposition, its Markdown links are resolved to +other selected knowledge theorems (or to a finite exact-integer program model), +and the fixed Lean + Mathlib backend either proves the proposition or reports, +honestly, that it could not. Every verified result is saved as a +content-addressed proof bundle that can be replayed without running proof +search. + +The normative design and acceptance gates live in +[`docs/DEVELOPMENT.md`](docs/DEVELOPMENT.md). [`docs/STATUS.md`](docs/STATUS.md) +records what has actually been executed; planning is never presented as +capability. + +## What this first release supports + +* **Selection**: a proof unit is an effective-mode Knowledge H2 with exactly one + direct H3 named `证明依赖`. Its goal is the *one and only* display math block + in its direct body. Nothing is guessed: zero or several display blocks are an + error, and formulas in H3 sections, tables, quotes or code blocks never + become targets. +* **Math**: arbitrary-precision integers, an optional single outer + `\forall x,y,... \in \mathbb{Z}` binder, `+ - \cdot \times`, constant + natural exponents `x^{12}`, comparisons, `\neg`, `\land`, `\lor`, + `\Rightarrow`. No reals, matrices, sums, existence, fractions, implicit + multiplication or free variables. +* **Links**: dependency list items are exactly one Markdown link each. Links + resolve inside an explicit controlled root only; exact anchor first, then the + documented exact canonical-name fallback. Cycles, missing/ambiguous/external + targets, escaped roots and incompatible project contexts are errors. +* **Reuse**: declared dependencies must be verified first and are imported as + real Lean theorems; a target's proof term may only use project declarations + from that verified closure. `declared`, `used` and transitive dependencies are + reported separately. +* **Program models**: an Exec H2 with explicit all-`Int` parameters, local + `+ - *` assignments and one final `return` can be referenced with + `\operatorname{name}(...)`. The generated Lean definition is checked; this is + an exact-integer model, **not** a statement about the real runtime. +* **Verification**: search and verification are separate. The payload is the + stock `lean4export` NDJSON closure; the verifier kernel-replays it with the + bundled independent checker (`con-leche --verified`), regenerates the expected + proposition from the current sources (never from the proof process), checks + alpha-equivalence of the target type, rejects metavariables, and enforces the + fixed axiom set `propext`, `Classical.choice`, `Quot.sound`. +* **Bundles**: one directory with `manifest.json` + `proof.ndjson`, bound to + source/Analysis digests, goal digest, models, dependencies, environment and + payload SHA-256. A cache hit is replayed, never trusted. +* **CLI**: `check` and `replay` only. Exit codes: 0 all requested targets + verified (or no target), 1 at least one not verified, 2 engineering failure. + +## What it deliberately does not do + +Real/rational/complex/matrix mathematics, general automated theorem proving, +natural-language formalization, LLMs, network knowledge, arbitrary `.olean` +imports, executing fenced code, loops/branches/calls/floats in program models, +or claims about the runtime. Unsupported input stays readable knowledge and is +reported as `unsupported`/`invalid`; it is never silently accepted. + +## Repository layout + +```text +src/ + main.rs argument handling, presentation, exit codes + lib.rs shared contract types (spans, outcomes, diagnostics, limits) + analysis.rs the only `marqdo check --emit` integration + rev 3 validation + document.rs proof-unit selection from the public document AST + formula.rs the only restricted math lexer/parser/type checker + linker.rs controlled multi-entry catalog, exact links, DAG, cycles + model.rs finite exact-integer program model validation + Lean mapping + lean.rs fixed backend: trusted generation, search, export, replay + certificate.rs single `marqdo.proof` bundle contract and content cache + prove.rs single orchestration of `check` / `replay` +lean/ pinned Lean project (`lean-toolchain`, `lake-manifest.json`) +examples/ author-facing `.mq.md` fixtures used by the tests +tests/ real-CLI integration, formula/model contracts, acceptance +docs/ the specification and executed-evidence status +tool.json Marqdo CLI Tool manifest (api_revision 1, analysis 3) +``` + +## Build + +Requires a Rust toolchain and the pinned Lean 4 + Mathlib environment. + +```sh +cargo build --release +``` + +The Lean backend is pinned by `lean/lean-toolchain` and +`lean/lake-manifest.json`. To set it up (one-time, needs network): + +```sh +# install the exact toolchain and fetch the mathlib oleans for the pinned rev +cd lean +lake update +lake exe cache get +lake build marqdo-replay +``` + +`marqdo-prove` never downloads anything at runtime. It discovers the backend +via `MARQDO_PROVE_LEAN_ROOT` (the `lean/` directory) and +`MARQDO_PROVE_LEAN_BIN_DIR` (the toolchain `bin` directory); see +`docs/STATUS.md` for the exact paths used in verified runs. + +The upstream CLI is required for static Analysis and is invoked only through +`MARQDO_BIN` (an absolute path, argv, no shell): + +```sh +export MARQDO_BIN=/path/to/marqdo +cargo run --release -- check examples/vector.mq.md --json +cargo run --release -- check examples/arithmetic.mq.md --unit '平方函数的非负性' +cargo run --release -- check examples/vector.mq.md --out /tmp/vector-proof +cargo run --release -- replay examples/vector.mq.md /tmp/vector-proof +``` + +## Tests + +```sh +cargo fmt --all -- --check +cargo clippy --workspace --all-targets --locked -- -D warnings +cargo test --workspace --locked +``` + +Real-CLI tests read `MARQDO_BIN`; they skip (and say so) when it is not set. +Lean-backed end-to-end tests additionally require the backend above and are +marked `#[ignore]` when they need large machinery; see `docs/STATUS.md` for the +exact commands executed. + +## Exit codes and output + +Machine output is one JSON object on stdout (`--json`); diagnostics and progress +go to stderr. Human output lists each target's outcome, scope, freshness, +normalized statement, premises, declared/used dependencies, axioms and +certificate location, followed by a summary. + +## License + +Apache-2.0 (matching the upstream Marqdo CLI). diff --git a/marqdo-prove-development.md b/docs/DEVELOPMENT.md similarity index 100% rename from marqdo-prove-development.md rename to docs/DEVELOPMENT.md diff --git a/lean/MarqdoProof/ArtTest/Dep.lean b/lean/MarqdoProof/ArtTest/Dep.lean deleted file mode 100644 index 2ef3717..0000000 --- a/lean/MarqdoProof/ArtTest/Dep.lean +++ /dev/null @@ -1,5 +0,0 @@ -module - -public import MarqdoProof.Basic - -public theorem art_dep_sq (x : Int) : x * x ≥ 0 := by nlinarith [sq_nonneg x] diff --git a/lean/MarqdoProof/ArtTest/Target.lean b/lean/MarqdoProof/ArtTest/Target.lean deleted file mode 100644 index 87cb1b6..0000000 --- a/lean/MarqdoProof/ArtTest/Target.lean +++ /dev/null @@ -1,8 +0,0 @@ -module - -public import MarqdoProof.ArtTest.Dep - -public theorem art_target_sum (x y : Int) : x * x + y * y ≥ 0 := by - have h1 := art_dep_sq x - have h2 := art_dep_sq y - omega diff --git a/lean/MarqdoProof/DepTest/Dep.lean b/lean/MarqdoProof/DepTest/Dep.lean deleted file mode 100644 index 5eca0a9..0000000 --- a/lean/MarqdoProof/DepTest/Dep.lean +++ /dev/null @@ -1,5 +0,0 @@ -module - -public import MarqdoProof.Basic - -public theorem dep_square (x : Int) : x * x ≥ 0 := by nlinarith [sq_nonneg x] diff --git a/lean/MarqdoProof/DepTest/Use.lean b/lean/MarqdoProof/DepTest/Use.lean deleted file mode 100644 index d91a1ab..0000000 --- a/lean/MarqdoProof/DepTest/Use.lean +++ /dev/null @@ -1,5 +0,0 @@ -module - -public import MarqdoProof.DepTest.Dep - -public theorem use_square (x : Int) : x * x ≥ 0 := dep_square x diff --git a/lean/MarqdoProof/Replay.lean b/lean/MarqdoProof/Replay.lean new file mode 100644 index 0000000..b6ad82b --- /dev/null +++ b/lean/MarqdoProof/Replay.lean @@ -0,0 +1,180 @@ +module + +public import LeanExport.Parse +public import Lean.Declaration +public import Lean.Expr +import Lean.Util.FoldConsts +import Lean.Data.Json + +/-! +# `marqdo-replay`: independent statement/axiom verifier for proof payloads + +This executable is part of the *verifier* side of `marqdo-prove`. It consumes +two Lean NDJSON export streams (the toolchain's own proof export format, written +by the stock `leanexport` tool): + +* the **payload** produced by the proof search process, which must contain the + project theorem declaration and its full dependency closure; +* the **expected** proposition reconstructed *by the trusted frontend from the + current sources* (it never comes from the proof search process). + +It then checks, without importing or trusting any `.olean`: + +1. the payload contains exactly one declaration for the target name, and it is + a theorem (not an axiom, definition, opaque constant or a second copy); +2. its type is alpha-equivalent to the expected proposition expression; +3. the target proof term contains no metavariables; +4. the transitive axiom closure of the exported payload is a subset of the + fixed allowed base axioms (`propext`, `Classical.choice`, `Quot.sound`), + with a specific diagnostic for `sorryAx` and native/compiler axioms. + +The actual kernel replay of the proof terms is performed by the bundled +independent checker (`con-leche --verified`); this program deliberately does not +implement a second kernel. +-/ + +open Lean + +namespace MarqdoProof.Replay + +/-- The only base axioms accepted in a payload. `sorryAx` and any native / +compiler trust axiom are rejected by omission and named in diagnostics. -/ +def allowedAxioms : Array Name := + #[``propext, ``Classical.choice, ``Quot.sound] + +def isAllowedAxiom (name : Name) : Bool := + allowedAxioms.contains name + +private def escape (text : String) : String := + Id.run do + let mut out := String.mk [] + for c in text.toList do + match c with + | '"' => out := out.push '\\' |>.push '"' + | '\\' => out := out.push '\\' |>.push '\\' + | '\n' => out := out.push '\\' |>.push 'n' + | '\t' => out := out.push '\\' |>.push 't' + | c => out := out.push c + return out + +def renderArray (items : Array String) : String := + let items := items.toList.map (fun item : String => "\"" ++ escape item ++ "\"") + "[" ++ String.intercalate ", " items ++ "]" + +def render (ok : Bool) (target : String) (expectedType : String) + (axioms : Array String) (reason : String) (used : Array String := #[]) + (projectDecls : Array String := #[]) : String := + "{\"schema\": \"marqdo.replay\", \"ok\": " ++ (if ok then "true" else "false") ++ + ", \"target\": \"" ++ escape target ++ "\"" ++ + ", \"expected_type\": \"" ++ escape expectedType ++ "\"" ++ + ", \"axioms\": " ++ renderArray axioms ++ + ", \"used\": " ++ renderArray used ++ + ", \"project_decls\": " ++ renderArray projectDecls ++ + ", \"reason\": \"" ++ escape reason ++ "\"}" + +private def fail (target : String) (reason : String) : IO UInt32 := do + IO.println (render false target "" #[] reason) + return 1 + +/-- Internal name prefixes of project declarations in this tool. -/ +def isProjectConstant (name : Name) : Bool := + let text := name.toString + text.startsWith "marqdoTarget_" || text.startsWith "marqdoModel_" + +private def loadExport (path : String) : IO LeanExport.ExportedEnv := do + let handle ← IO.FS.Handle.mk path IO.FS.Mode.read + let stream := IO.FS.Stream.ofHandle handle + LeanExport.parseStream stream + +private partial def hasMetavariable (expr : Expr) : Bool := + if expr.isMVar then + true + else + expr.getAppArgs.any hasMetavariable || + (match expr with + | .lam _ type body _ => hasMetavariable type || hasMetavariable body + | .forallE _ type body _ => hasMetavariable type || hasMetavariable body + | .letE _ type value body _ => + hasMetavariable type || hasMetavariable value || hasMetavariable body + | .mdata _ inner => hasMetavariable inner + | .proj _ _ inner => hasMetavariable inner + | _ => false) + +private def kindName : ConstantInfo → String + | .axiomInfo _ => "axiom" + | .defnInfo _ => "definition" + | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" + | .quotInfo _ => "quotient" + | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" + | .recInfo _ => "recursor" + +/-- Run the verifier. Exit 0 only when every check passed. -/ +def run (args : List String) : IO UInt32 := do + let (payloadPath, expectedPath, targetLiteral, expectedLiteral) ← + match args with + | [payload, expected, target, expectedName] => + pure (payload, expected, target, expectedName) + | _ => + IO.eprintln "usage: marqdo-replay PAYLOAD.ndjson EXPECTED.ndjson TARGET_NAME EXPECTED_NAME" + return 2 + let target := Name.mkSimple targetLiteral + let expectedName := Name.mkSimple expectedLiteral + let payload ← loadExport payloadPath + let expected ← loadExport expectedPath + if payload.constOrder.size != payload.constMap.size then + return ← fail targetLiteral "payload export contains duplicate declarations" + if expected.constOrder.size != expected.constMap.size then + return ← fail targetLiteral "expected export contains duplicate declarations" + let some targetInfo := payload.constMap.get? target + | return ← fail targetLiteral s!"payload does not declare `{target}`" + let some expectedInfo := expected.constMap.get? expectedName + | return ← fail targetLiteral s!"expected module does not declare `{expectedName}`" + let expectedExpr : Expr ← + match expectedInfo with + | .defnInfo value => pure value.value + | other => + return ← fail targetLiteral + s!"expected declaration has unexpected kind `{kindName other}`" + -- Axiom closure of the payload (the stream is closed under the target's + -- dependencies by construction of `leanexport`). + let mut axioms : Array String := #[] + let mut projectDecls : Array String := #[] + for (name, info) in payload.constMap.toList do + if isProjectConstant name then + projectDecls := projectDecls.push name.toString + if let .axiomInfo _ := info then + axioms := axioms.push name.toString + if !isAllowedAxiom name then + let reason := + if name == ``sorryAx then + "payload depends on `sorryAx`" + else if name.toString.contains "trustCompiler" || name.toString.endsWith "_native" then + s!"payload depends on native/compiler trust axiom `{name}`" + else + s!"payload depends on untrusted axiom `{name}`" + return ← fail targetLiteral reason + match targetInfo with + | .thmInfo thm => + if thm.type.hasMVar then + return ← fail targetLiteral "target theorem type contains metavariables" + if hasMetavariable thm.value then + return ← fail targetLiteral "target proof term contains metavariables" + if !thm.type.eqv expectedExpr then + return ← fail targetLiteral + s!"target proposition does not match the expected proposition" + let used := + (thm.type.getUsedConstants ++ thm.value.getUsedConstants).filterMap fun name => + if isProjectConstant name then some name.toString else none + IO.println (render true targetLiteral (toString expectedExpr) axioms "" used projectDecls) + return 0 + | other => + return ← fail targetLiteral + s!"payload target is not a theorem (kind `{kindName other}`)" + +end MarqdoProof.Replay + +/-- Executable entry point (must be in the root namespace for `lake exe`). -/ +public def main (args : List String) : IO UInt32 := + MarqdoProof.Replay.run args diff --git a/lean/lakefile.toml b/lean/lakefile.toml index d6703a1..eba00fc 100644 --- a/lean/lakefile.toml +++ b/lean/lakefile.toml @@ -9,3 +9,7 @@ rev = "fc4f59e577feb1a4956671bc04ac18aaaf8cd842" [[lean_lib]] name = "MarqdoProof" + +[[lean_exe]] +name = "marqdo-replay" +root = "MarqdoProof.Replay" diff --git a/scripts/package-tool.sh b/scripts/package-tool.sh new file mode 100755 index 0000000..dcce938 --- /dev/null +++ b/scripts/package-tool.sh @@ -0,0 +1,25 @@ +#!/bin/sh +# Assemble the installable Marqdo CLI Tool bundle for `marqdo tool install`. +# +# The bundle contains the executable, the tool manifest and the pinned Lean +# backend project. The Lean toolchain/Mathlib build is a *prerequisite* because +# shipping a multi-gigabyte toolchain inside every tool bundle would duplicate +# the fixed environment; see README.md §Fixed backend for the pinned setup. +set -eu + +repo_root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +out=${1:-"$repo_root/dist/marqdo-prove-tool"} + +cargo build --release --locked --manifest-path "$repo_root/Cargo.toml" + +rm -rf "$out" +mkdir -p "$out/bin" "$out/lean" +cp "$repo_root/target/release/marqdo-prove" "$out/bin/marqdo-prove" +cp "$repo_root/tool.json" "$out/tool.json" +cp -R "$repo_root/lean/MarqdoProof" "$out/lean/" +cp "$repo_root/lean/MarqdoProof.lean" "$out/lean/" +cp "$repo_root/lean/lakefile.toml" "$out/lean/" +cp "$repo_root/lean/lake-manifest.json" "$out/lean/" +cp "$repo_root/lean/lean-toolchain" "$out/lean/" +echo "bundle assembled at $out" +echo "install with: marqdo tool install $out/tool.json" diff --git a/src/analysis.rs b/src/analysis.rs index 2d6fc58..ef42263 100644 --- a/src/analysis.rs +++ b/src/analysis.rs @@ -87,6 +87,13 @@ impl ModuleData { } } + /// Look up a function record by canonical FunctionId. + pub fn function(&self, function_id: &str) -> Option<&Function> { + self.functions + .iter() + .find(|function| function.id == function_id) + } + /// Source slice for a span, if the span is valid for this module. pub fn slice(&self, span: Span) -> Option<&str> { if span.is_valid_in(&self.source) { diff --git a/src/certificate.rs b/src/certificate.rs index 29cdf6d..031479b 100644 --- a/src/certificate.rs +++ b/src/certificate.rs @@ -1 +1,611 @@ //! Content-addressed proof bundles, manifests and replay (docs/DEVELOPMENT.md §8). +//! +//! One bundle is one directory with exactly two files: `manifest.json` and the +//! Lean proof payload (`proof.ndjson`, the toolchain's own `lean4export` +//! format). The manifest binds the current sources, Analysis bytes, target +//! proposition, declared dependencies, program models, environment identity and +//! the payload digest. A cached `verified: true` flag is never trusted on its +//! own: every hit is replayed through the independent verifier before it is +//! reported as current. +//! +//! Bundles are written through an exclusive temporary directory and an atomic +//! rename; a failure never leaves a bundle-looking half result. + +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; + +use crate::{codes, sha256_hex, Failure, Result, Span, PROOF_SCHEMA, PROOF_SCHEMA_VERSION}; + +/// Directory name of the tool-owned cache inside a project root. +pub const CACHE_DIR: &str = ".marqdo/prove"; + +pub const MANIFEST_FILE: &str = "manifest.json"; +pub const PAYLOAD_FILE: &str = "proof.ndjson"; + +/// The allowed base axioms of the fixed Lean environment. +pub const ALLOWED_AXIOMS: [&str; 3] = ["propext", "Classical.choice", "Quot.sound"]; + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ToolIdentity { + pub name: String, + pub version: String, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SourceBinding { + /// Portable package-relative locator of a document participating in the run. + pub locator: String, + pub module_id: String, + pub source_digest: String, + pub analysis_digest: String, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ModelBinding { + pub unit_id: String, + pub locator: String, + pub function_id: String, + pub lean_name: String, + pub digest: String, + pub module_name: String, + pub semantics: String, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct DeclaredDependency { + pub kind: String, + pub locator: String, + pub unit_id: String, + pub link_text: String, + /// Cache key of the dependency bundle for theorem dependencies, or the + /// model key for program model dependencies. + pub binding: String, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct TargetIdentity { + /// Canonical unit id of the Knowledge H2 (never split for identity). + pub unit_id: String, + pub unit_path: Vec, + pub locator: String, + /// `mathematical` or `program_model`. + pub scope: String, + /// `verified` or `refuted`. + pub outcome: String, + /// Raw display-math payload from the source document. + pub statement_literal: String, + /// Deterministic human-readable normalized proposition. + pub statement_normalized: String, + /// Lean source of the proposition as generated by the trusted frontend. + pub statement_lean: String, + pub goal_span: Span, + pub goal_payload_span: Option, + pub goal_digest: String, + /// Display premises: the whole antecedent is preserved, never dropped. + pub premises: Vec, + pub theorem_name: String, + pub expected_name: String, + /// Non-empty when the target depends on a program model. + pub model_definitions: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct EnvironmentIdentity { + pub lean_toolchain: String, + pub lean_version: String, + pub mathlib_rev: String, + pub lake_manifest_digest: String, + pub replay_verifier_digest: String, + pub con_leche_version: String, + pub formula_compiler: String, + pub semantic_mapping: String, + /// Content identity over the fields above. + pub environment_id: String, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ProofPayload { + pub file: String, + pub bytes: u64, + pub sha256: String, + pub export_format: String, + pub target_decl: String, + pub expected_decl: String, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct BundleManifest { + pub schema: String, + pub schema_version: u64, + pub tool: ToolIdentity, + pub target: TargetIdentity, + pub sources: Vec, + pub environment: EnvironmentIdentity, + pub declared_dependencies: Vec, + /// Actual direct project theorem/model declarations used by the proof term. + pub used_dependencies: Vec, + /// Actual transitive project dependency closure in the payload. + pub transitive_dependencies: Vec, + pub axioms: Vec, + pub proof: ProofPayload, + /// Content address of this bundle: every participating identity is hashed. + pub cache_key: String, +} + +impl BundleManifest { + pub fn to_bytes(&self) -> Result> { + serde_json::to_vec_pretty(self).map_err(|error| { + Failure::new( + codes::CERTIFICATE_INVALID, + format!("cannot serialize proof manifest: {error}"), + ) + }) + } + + /// Strictly re-validate a manifest read from disk (untrusted data). + pub fn validate(&self) -> Result<()> { + if self.schema != PROOF_SCHEMA { + return invalid(format!("unexpected proof schema `{}`", self.schema)); + } + if self.schema_version != PROOF_SCHEMA_VERSION { + return invalid(format!( + "proof schema_version {} does not match required {PROOF_SCHEMA_VERSION}", + self.schema_version + )); + } + if self.tool.name != crate::TOOL_NAME || self.tool.version != env!("CARGO_PKG_VERSION") { + return invalid("proof bundle was produced by an incompatible tool version"); + } + if self.target.outcome != "verified" && self.target.outcome != "refuted" { + return invalid(format!( + "proof target outcome `{}` is not a verifiable outcome", + self.target.outcome + )); + } + if self.target.scope != "mathematical" && self.target.scope != "program_model" { + return invalid(format!("unknown proof scope `{}`", self.target.scope)); + } + if self.target.locator.is_empty() || self.target.unit_id.is_empty() { + return invalid("proof target has an empty unit identity"); + } + if !is_hex_sha256(&self.target.goal_digest) { + return invalid("proof target goal_digest is not a canonical sha256 digest"); + } + if self.proof.file != PAYLOAD_FILE { + return invalid(format!("unexpected proof payload file `{}`", self.proof.file)); + } + if !is_hex_sha256(&self.proof.sha256) { + return invalid("proof payload sha256 is not a canonical digest"); + } + if self.proof.target_decl != self.target.theorem_name + || self.proof.expected_decl != self.target.expected_name + { + return invalid("proof payload declaration names are not bound to the target identity"); + } + if self.sources.is_empty() { + return invalid("proof bundle has no source bindings"); + } + for source in &self.sources { + if source.locator.is_empty() + || !is_hex_sha256(&source.source_digest) + || !is_hex_sha256(&source.analysis_digest) + { + return invalid("proof source binding is malformed"); + } + } + let mut sorted = self.sources.clone(); + sorted.sort_by(|left, right| left.locator.cmp(&right.locator)); + if sorted + .iter() + .zip(&self.sources) + .any(|(left, right)| left.locator != right.locator) + { + return invalid("proof sources are not sorted by locator"); + } + for axiom in &self.axioms { + if !ALLOWED_AXIOMS.contains(&axiom.as_str()) { + return invalid(format!("proof bundle reports untrusted axiom `{axiom}`")); + } + } + let mut sorted_axioms = self.axioms.clone(); + sorted_axioms.sort(); + sorted_axioms.dedup(); + if sorted_axioms != self.axioms { + return invalid("proof axioms are not sorted and deduplicated"); + } + if !is_hex_sha256(&self.cache_key) { + return invalid("proof cache_key is not a canonical sha256 digest"); + } + Ok(()) + } +} + +/// One loaded bundle: manifest plus payload bytes. +#[derive(Clone, Debug)] +pub struct Bundle { + pub directory: PathBuf, + pub manifest: BundleManifest, + pub payload: Vec, +} + +impl Bundle { + pub fn load(directory: &Path) -> Result { + let manifest_path = directory.join(MANIFEST_FILE); + let payload_path = directory.join(PAYLOAD_FILE); + let manifest_bytes = std::fs::read(&manifest_path).map_err(|error| { + Failure::new( + codes::CERTIFICATE_INVALID, + format!("cannot read `{}`: {error}", manifest_path.display()), + ) + })?; + if manifest_bytes.len() > 4 * 1024 * 1024 { + return invalid("proof manifest is unreasonably large"); + } + let manifest: BundleManifest = serde_json::from_slice(&manifest_bytes).map_err(|error| { + Failure::new( + codes::CERTIFICATE_INVALID, + format!( + "`{}` does not match the current marqdo.proof revision 1 shape: {error}", + manifest_path.display() + ), + ) + .with_hint("delete the generated cache entry and re-run `check`; there is no migration") + })?; + manifest.validate()?; + let payload = std::fs::read(&payload_path).map_err(|error| { + Failure::new( + codes::CERTIFICATE_INVALID, + format!("cannot read proof payload `{}`: {error}", payload_path.display()), + ) + })?; + if payload.len() as u64 != manifest.proof.bytes { + return invalid("proof payload byte count does not match the manifest"); + } + if payload.len() as u64 > crate::limits::MAX_PROOF_BYTES { + return invalid("proof payload is larger than the allowed limit"); + } + let digest = sha256_hex(&payload); + if digest != manifest.proof.sha256 { + return invalid("proof payload SHA-256 does not match the manifest"); + } + Ok(Bundle { + directory: directory.to_path_buf(), + manifest, + payload, + }) + } + + pub fn write_to(&self, directory: &Path) -> Result<()> { + publish_manifest_and_payload(directory, &self.manifest, &self.payload) + } +} + +/// Identity inputs for a content-addressed cache key. +pub struct CacheIdentity { + pub target_locator: String, + pub target_unit_id: String, + pub goal_digest: String, + pub scope: String, + pub sources: Vec<(String, String, String)>, + pub environment_id: String, + pub declared: Vec<(String, String, String, String)>, + pub models: Vec<(String, String)>, +} + +impl CacheIdentity { + /// Deterministic content address over every participating identity. + pub fn cache_key(&self) -> String { + let mut buffer = String::new(); + buffer.push_str("marqdo-prove/cache/v1\n"); + buffer.push_str(crate::TOOL_NAME); + buffer.push('\n'); + buffer.push_str(env!("CARGO_PKG_VERSION")); + buffer.push('\n'); + buffer.push_str(&self.environment_id); + buffer.push('\n'); + buffer.push_str(&self.scope); + buffer.push('\n'); + buffer.push_str(&self.target_locator); + buffer.push('\n'); + buffer.push_str(&self.target_unit_id); + buffer.push('\n'); + buffer.push_str(&self.goal_digest); + buffer.push('\n'); + let mut sources = self.sources.clone(); + sources.sort(); + for (locator, source_digest, analysis_digest) in sources { + buffer.push_str(&format!("source:{locator}\0{source_digest}\0{analysis_digest}\n")); + } + let mut declared = self.declared.clone(); + declared.sort(); + for (kind, locator, unit_id, binding) in declared { + buffer.push_str(&format!("dep:{kind}\0{locator}\0{unit_id}\0{binding}\n")); + } + let mut models = self.models.clone(); + models.sort(); + for (function_id, digest) in models { + buffer.push_str(&format!("model:{function_id}\0{digest}\n")); + } + sha256_hex(buffer.as_bytes()) + } +} + +/// Tool-owned, content-addressed cache under `/.marqdo/prove/`. +pub struct CacheStore { + root: PathBuf, +} + +impl CacheStore { + pub fn new(project_root: &Path) -> CacheStore { + Self { + root: project_root.join(CACHE_DIR), + } + } + + pub fn root(&self) -> &Path { + &self.root + } + + pub fn bundle_dir(&self, cache_key: &str) -> PathBuf { + self.root.join("bundles").join(cache_key) + } + + pub fn artifacts_dir(&self) -> PathBuf { + self.root.join("artifacts") + } + + pub fn work_dir(&self) -> PathBuf { + self.root.join("work") + } + + /// Look up a bundle by content address. A mismatching manifest is not a + /// cache hit; it is left in place for inspection but reported as stale. + pub fn lookup(&self, cache_key: &str) -> Option { + let directory = self.bundle_dir(cache_key); + if !directory.is_dir() { + return None; + } + match Bundle::load(&directory) { + Ok(bundle) if bundle.manifest.cache_key == cache_key => Some(bundle), + _ => None, + } + } + + /// Publish a bundle atomically. Returns the cache key it was stored under. + pub fn publish(&self, manifest: &BundleManifest, payload: &[u8]) -> Result { + let directory = self.bundle_dir(&manifest.cache_key); + if directory.is_dir() { + // Replace only if the identity is identical; otherwise the caller + // has a key collision, which is never acceptable. + if let Ok(existing) = Bundle::load(&directory) { + if existing.manifest.cache_key == manifest.cache_key + && existing.manifest.proof.sha256 == manifest.proof.sha256 + { + return Ok(directory); + } + } + std::fs::remove_dir_all(&directory).map_err(|error| { + Failure::new( + codes::CERTIFICATE_INVALID, + format!("cannot replace stale cache entry `{}`: {error}", directory.display()), + ) + })?; + } + publish_manifest_and_payload(&directory, manifest, payload)?; + Ok(directory) + } +} + +fn publish_manifest_and_payload( + directory: &Path, + manifest: &BundleManifest, + payload: &[u8], +) -> Result<()> { + if directory.exists() { + return invalid(format!( + "refusing to overwrite existing bundle directory `{}`", + directory.display() + )); + } + let parent = directory.parent().ok_or_else(|| { + Failure::new(codes::CERTIFICATE_INVALID, "bundle directory has no parent") + })?; + std::fs::create_dir_all(parent).map_err(|error| { + Failure::new( + codes::CERTIFICATE_INVALID, + format!("cannot create bundle parent `{}`: {error}", parent.display()), + ) + })?; + let unique = format!( + ".tmp-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|duration| duration.as_nanos()) + .unwrap_or(0) + ); + let temporary = parent.join(unique); + std::fs::create_dir(&temporary).map_err(|error| { + Failure::new( + codes::CERTIFICATE_INVALID, + format!("cannot create temporary bundle `{}`: {error}", temporary.display()), + ) + })?; + let result = (|| -> Result<()> { + let manifest_bytes = manifest.to_bytes()?; + write_file(&temporary.join(MANIFEST_FILE), &manifest_bytes)?; + write_file(&temporary.join(PAYLOAD_FILE), payload)?; + std::fs::rename(&temporary, directory).map_err(|error| { + Failure::new( + codes::CERTIFICATE_INVALID, + format!( + "cannot publish bundle `{}` atomically: {error}", + directory.display() + ), + ) + })?; + Ok(()) + })(); + if result.is_err() { + let _ = std::fs::remove_dir_all(&temporary); + } + result +} + +fn write_file(path: &Path, bytes: &[u8]) -> Result<()> { + use std::io::Write; + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let mut file = options.open(path).map_err(|error| { + Failure::new( + codes::CERTIFICATE_INVALID, + format!("cannot create `{}`: {error}", path.display()), + ) + })?; + file.write_all(bytes) + .and_then(|()| file.sync_all()) + .map_err(|error| { + Failure::new( + codes::CERTIFICATE_INVALID, + format!("cannot write `{}`: {error}", path.display()), + ) + }) +} + +fn is_hex_sha256(value: &str) -> bool { + value.len() == 64 && value.bytes().all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()) +} + +fn invalid(message: impl Into) -> Result { + Err(Failure::new(codes::CERTIFICATE_INVALID, message.into())) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn manifest() -> BundleManifest { + BundleManifest { + schema: PROOF_SCHEMA.to_string(), + schema_version: PROOF_SCHEMA_VERSION, + tool: ToolIdentity { + name: crate::TOOL_NAME.to_string(), + version: env!("CARGO_PKG_VERSION").to_string(), + }, + target: TargetIdentity { + unit_id: "root:t::a.mq.md#A".to_string(), + unit_path: vec!["A".to_string()], + locator: "a.mq.md".to_string(), + scope: "mathematical".to_string(), + outcome: "verified".to_string(), + statement_literal: "x = 1".to_string(), + statement_normalized: "x = 1".to_string(), + statement_lean: "(1 : Int) = (1 : Int)".to_string(), + goal_span: Span::new(1, 2), + goal_payload_span: None, + goal_digest: sha256_hex(b"x = 1"), + premises: vec![], + theorem_name: "marqdoTarget_abc".to_string(), + expected_name: "marqdoExpected_abc".to_string(), + model_definitions: vec![], + }, + sources: vec![SourceBinding { + locator: "a.mq.md".to_string(), + module_id: "root:t::a.mq.md".to_string(), + source_digest: sha256_hex(b"# A\n"), + analysis_digest: sha256_hex(b"{}"), + }], + environment: EnvironmentIdentity { + lean_toolchain: "leanprover/lean4:v4.36.0".to_string(), + lean_version: "4.36.0".to_string(), + mathlib_rev: "fc4f59e".to_string(), + lake_manifest_digest: sha256_hex(b"manifest"), + replay_verifier_digest: sha256_hex(b"replay"), + con_leche_version: "0.1".to_string(), + formula_compiler: "marqdo-prove".to_string(), + semantic_mapping: "int-exact-v1".to_string(), + environment_id: sha256_hex(b"env"), + }, + declared_dependencies: vec![], + used_dependencies: vec![], + transitive_dependencies: vec![], + axioms: vec!["propext".to_string()], + proof: ProofPayload { + file: PAYLOAD_FILE.to_string(), + bytes: 3, + sha256: sha256_hex(b"abc"), + export_format: "lean4export-3.1.0".to_string(), + target_decl: "marqdoTarget_abc".to_string(), + expected_decl: "marqdoExpected_abc".to_string(), + }, + cache_key: sha256_hex(b"key"), + } + } + + #[test] + fn validates_a_well_formed_manifest() { + manifest().validate().unwrap(); + } + + #[test] + fn rejects_untrusted_axioms_and_bad_revision() { + let mut m = manifest(); + m.axioms = vec!["sorryAx".to_string()]; + assert_eq!(m.validate().unwrap_err().code, codes::CERTIFICATE_INVALID); + let mut m = manifest(); + m.schema_version = 2; + assert!(m.validate().is_err()); + } + + #[test] + fn rejects_payload_digest_mismatch_when_loading() { + let root = std::env::temp_dir().join(format!("marqdo-prove-cert-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let mut m = manifest(); + let payload = b"abc".to_vec(); + m.proof.bytes = payload.len() as u64; + m.proof.sha256 = sha256_hex(&payload); + let directory = root.join("bundle"); + m.cache_key = sha256_hex(b"k"); + publish_manifest_and_payload(&directory, &m, &payload).unwrap(); + let loaded = Bundle::load(&directory).unwrap(); + assert_eq!(loaded.payload, payload); + // Tamper the payload on disk. + std::fs::write(directory.join(PAYLOAD_FILE), b"abd").unwrap(); + let error = Bundle::load(&directory).unwrap_err(); + assert_eq!(error.code, codes::CERTIFICATE_INVALID); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn cache_key_is_deterministic_and_identity_sensitive() { + let mut identity = CacheIdentity { + target_locator: "a.mq.md".to_string(), + target_unit_id: "root:t::a.mq.md#A".to_string(), + goal_digest: sha256_hex(b"goal"), + scope: "mathematical".to_string(), + sources: vec![("a.mq.md".to_string(), sha256_hex(b"s"), sha256_hex(b"a"))], + environment_id: sha256_hex(b"env"), + declared: vec![], + models: vec![], + }; + let first = identity.cache_key(); + assert_eq!(first, identity.cache_key()); + identity.goal_digest = sha256_hex(b"other goal"); + assert_ne!(first, identity.cache_key()); + } +} diff --git a/src/formula.rs b/src/formula.rs index fddc535..12945e8 100644 --- a/src/formula.rs +++ b/src/formula.rs @@ -1,3 +1,2782 @@ //! Restricted integer mathematics: lexer, parser, typed AST, Lean rendering. //! -//! Implemented in a later commit of this milestone; see docs/DEVELOPMENT.md §4. +//! This module is the **only** mathematical parser in `marqdo-prove`. It +//! implements exactly the fixed first-version fragment of +//! `docs/DEVELOPMENT.md` §4: an optional single leading `\forall ... \in +//! \mathbb{Z}` binder followed by a closed proposition over arbitrary-precision +//! integers, integer variables, literals, parentheses, `+ - \cdot \times`, +//! constant natural exponents, comparisons, negation, conjunction, disjunction +//! and implication. No other LaTeX math is interpreted here: anything outside +//! the documented grammar is either an `Unsupported` (a construct the tool +//! deliberately does not model), a `Syntax` error (a malformed token sequence) +//! or a `FreeVariable` error (an identifier that no binder introduced). The +//! parser never rewrites, repairs or guesses at the author's intent. +//! +//! Design invariants: +//! +//! * Every parse produces one typed [`Goal`]; all input bytes must be consumed. +//! * Bound variables are resolved to de Bruijn-style indices at parse time and +//! are renamed to internal `mqx0`, `mqx1`, ... names for Lean rendering, so no +//! user-controlled identifier ever reaches generated Lean source. +//! * Parsing is deterministic and total: no `unwrap` on parsed input, no panics +//! on arbitrary bytes, and every allocation is bounded by a token/digit budget +//! before it happens. +//! * The syntax tree is small and explicitly bounded +//! ([`limits::MAX_AST_DEPTH`], [`limits::MAX_FORMULA_TOKENS`], +//! [`limits::MAX_VARS`], [`limits::MAX_LITERAL_DIGITS`], +//! [`limits::MAX_EXPONENT`]); exceeding a budget is a `Budget` error rather +//! than a crash. +//! +//! The module is deliberately dependency-light (`num-bigint` only) and keeps +//! rendering separate from parsing: [`Goal::lean_prop`] emits the fixed Lean 4 +//! target wording (ASCII/Unicode as specified), [`Goal::normal`] emits the +//! deterministic human-readable normal form used in reports, and +//! [`Goal::evaluate`] performs an exact closed-instance evaluation used as a +//! cheap sanity check. The Lean kernel remains the authority for proofs; the +//! evaluator is only a diagnostic aid. + +use num_bigint::BigInt; +use std::collections::{BTreeMap, BTreeSet}; + +use crate::{codes, limits, Span}; + +/// Result alias for the parser and renderers. +type FormulaResult = std::result::Result; + +// --------------------------------------------------------------------------- +// Public typed AST +// --------------------------------------------------------------------------- + +/// Binary comparison relation between two integer expressions. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Rel { + Eq, + Ne, + Lt, + Gt, + Le, + Ge, +} + +impl Rel { + /// The surface command for this relation (used only in diagnostics). + fn command(self) -> &'static str { + match self { + Rel::Eq => "=", + Rel::Ne => "\\neq", + Rel::Lt => "<", + Rel::Gt => ">", + Rel::Le => "\\leq", + Rel::Ge => "\\geq", + } + } + + /// The Unicode glyph used by the report normal form. + fn glyph(self) -> &'static str { + match self { + Rel::Eq => "=", + Rel::Ne => "≠", + Rel::Lt => "<", + Rel::Gt => ">", + Rel::Le => "≤", + Rel::Ge => "≥", + } + } +} + +/// A typed integer expression (`Int` in Lean). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum IntExpr { + /// Decimal literal. Carries no sign: unary minus is [`IntExpr::Neg`]. + Lit(BigInt), + /// Bound variable, as an index into [`Goal::vars`] (binder order). + Var(usize), + Neg(Box), + Add(Box, Box), + Sub(Box, Box), + Mul(Box, Box), + /// Constant natural exponent in `0..=limits::MAX_EXPONENT`. + Pow(Box, u32), + /// A `\operatorname{name}(...)` model call: the alias is bound to an + /// exact program-model definition elsewhere; arguments are integers. + ModelCall { + alias: String, + args: Vec, + }, +} + +/// A typed proposition (`Prop` in Lean). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum PropExpr { + Cmp(Rel, IntExpr, IntExpr), + Not(Box), + And(Box, Box), + Or(Box, Box), + Imp(Box, Box), +} + +/// One parsed goal. `vars` is the binder order and `Var(i)` indexes into it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Goal { + /// Bound variable names in binder order. + pub vars: Vec, + /// The proposition body (binder already resolved to indices). + pub body: PropExpr, + /// The exact display-math payload text that was parsed. + pub literal: String, + /// Caller-supplied span of the display-math block in the source document. + pub span: Span, +} + +/// Classification of a formula failure. The variants map to stable diagnostic +/// codes through [`FormulaError::code`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FormulaErrorKind { + Syntax, + Unsupported, + FreeVariable, + Budget, +} + +/// A structured formula failure: kind, explanation, byte offset into the +/// literal (when known) and an optional corrective hint. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct FormulaError { + pub kind: FormulaErrorKind, + pub message: String, + /// Byte offset into the literal where the problem starts. + pub offset: Option, + pub hint: Option, +} + +impl FormulaError { + /// Stable diagnostic code for this failure. + pub fn code(&self) -> &'static str { + match self.kind { + FormulaErrorKind::Syntax | FormulaErrorKind::Budget => codes::FORMULA_SYNTAX, + FormulaErrorKind::Unsupported => codes::FORMULA_UNSUPPORTED, + FormulaErrorKind::FreeVariable => codes::FORMULA_FREE_VARIABLE, + } + } + + fn new( + kind: FormulaErrorKind, + offset: Option, + message: impl Into, + ) -> FormulaError { + FormulaError { + kind, + message: message.into(), + offset, + hint: None, + } + } + + fn at(kind: FormulaErrorKind, offset: usize, message: impl Into) -> FormulaError { + FormulaError::new(kind, Some(offset), message) + } + + fn with_hint(mut self, hint: impl Into) -> FormulaError { + self.hint = Some(hint.into()); + self + } +} + +impl std::fmt::Display for FormulaError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}: {}", self.code(), self.message) + } +} + +impl std::error::Error for FormulaError {} + +fn syntax(offset: usize, message: impl Into) -> FormulaError { + FormulaError::at(FormulaErrorKind::Syntax, offset, message) +} + +fn unsupported(offset: usize, message: impl Into) -> FormulaError { + FormulaError::at(FormulaErrorKind::Unsupported, offset, message) +} + +fn budget(offset: usize, message: impl Into) -> FormulaError { + FormulaError::at(FormulaErrorKind::Budget, offset, message) +} + +fn free_variable(offset: usize, name: &str) -> FormulaError { + FormulaError::at( + FormulaErrorKind::FreeVariable, + offset, + format!( + "variable `{}` is not bound by the leading `\\forall` binder", + excerpt(name) + ), + ) + .with_hint("add an explicit binder such as `\\forall x\\in\\mathbb{Z}, ...`; free variables have no integer domain") +} + +// --------------------------------------------------------------------------- +// Lexer +// --------------------------------------------------------------------------- + +/// One lexical token of the restricted grammar. Whitespace, `\,`, `\;`, +/// `\quad` and `\qquad` are not tokens: they are dropped by the lexer. +#[derive(Clone, Debug)] +enum Tok { + Forall, + In, + Mathbb(char), + Comma, + Imp, + Or, + And, + Neg, + Rel(Rel), + Plus, + Minus, + Star, + Caret, + LParen, + RParen, + LBrace, + RBrace, + /// A maximal run of ASCII digits (decimal only, no sign). + Nat(String), + /// A variable or model-name identifier: ASCII letter then letters/digits/`_`. + Id(String), + /// A `\operatorname{Id}` command, before its argument list. + OperatorName(String), +} + +#[derive(Clone, Debug)] +struct Token { + tok: Tok, + offset: usize, +} + +/// Bounded excerpt of an identifier for diagnostics. Identifiers can be as long +/// as the whole payload, so messages never repeat unbounded user text verbatim. +fn excerpt(text: &str) -> String { + const LIMIT: usize = 48; + if text.len() <= LIMIT { + return text.to_owned(); + } + let mut end = LIMIT; + while end > 0 && !text.is_char_boundary(end) { + end -= 1; + } + format!("{}…", &text[..end]) +} + +/// Human-readable token description for diagnostics. Does not include raw +/// multi-kilobyte literal text: only bounded excerpts. +fn tok_name(tok: &Tok) -> String { + match tok { + Tok::Forall => "`\\forall`".to_owned(), + Tok::In => "`\\in`".to_owned(), + Tok::Mathbb(c) => format!("`\\mathbb{{{c}}}`"), + Tok::Comma => "`,`".to_owned(), + Tok::Imp => "`\\Rightarrow`".to_owned(), + Tok::Or => "`\\lor`".to_owned(), + Tok::And => "`\\land`".to_owned(), + Tok::Neg => "`\\neg`".to_owned(), + Tok::Rel(rel) => format!("`{}`", rel.command()), + Tok::Plus => "`+`".to_owned(), + Tok::Minus => "`-`".to_owned(), + Tok::Star => "`\\cdot`/`\\times`".to_owned(), + Tok::Caret => "`^`".to_owned(), + Tok::LParen => "`(`".to_owned(), + Tok::RParen => "`)`".to_owned(), + Tok::LBrace => "`{`".to_owned(), + Tok::RBrace => "`}`".to_owned(), + Tok::Nat(text) => { + if text.len() > 8 { + "a number".to_owned() + } else { + format!("the number `{text}`") + } + } + Tok::Id(name) => format!("the identifier `{}`", excerpt(name)), + Tok::OperatorName(name) => { + format!("the model call `\\operatorname{{{}}}`", excerpt(name)) + } + } +} + +/// Lex one `\...` command starting at `start` (which must point at the +/// backslash). Returns the token and the next byte offset, `None` for an +/// ignored formatting command. +fn lex_command(text: &str, start: usize) -> FormulaResult<(Option, usize)> { + let bytes = text.as_bytes(); + let j = start + 1; + if j >= bytes.len() { + return Err(syntax( + start, + "the formula ends with a dangling backslash; expected a LaTeX command name", + )); + } + if !bytes[j].is_ascii_alphabetic() { + // Non-alphabetic escapes: only the four documented formatting commands + // are ignored; everything else is unsupported math. + return match bytes[j] { + b',' | b';' => Ok((None, j + 1)), + other => Err(unsupported( + start, + format!( + "backslash escape `\\{}` is not supported; only `\\,`, `\\;`, `\\quad` and `\\qquad` are ignored formatting commands", + if other.is_ascii_graphic() { + (other as char).to_string() + } else { + format!("U+{other:02X}") + } + ), + )), + }; + } + let mut k = j + 1; + while k < bytes.len() && bytes[k].is_ascii_alphabetic() { + k += 1; + } + let name = &text[j..k]; + let token = match name { + "forall" => Tok::Forall, + "in" => Tok::In, + "Rightarrow" => Tok::Imp, + "lor" => Tok::Or, + "land" => Tok::And, + "neg" => Tok::Neg, + "neq" => Tok::Rel(Rel::Ne), + "leq" => Tok::Rel(Rel::Le), + "geq" => Tok::Rel(Rel::Ge), + "cdot" | "times" => Tok::Star, + "quad" | "qquad" => return Ok((None, k)), + "mathbb" => { + if k >= bytes.len() || bytes[k] != b'{' { + return Err(syntax( + k, + "expected `{` after `\\mathbb`; write a domain such as `\\mathbb{Z}`", + )); + } + let mut p = k + 1; + if p >= bytes.len() { + return Err(syntax(p, "expected a domain letter after `\\mathbb{`")); + } + let letter = bytes[p]; + if !letter.is_ascii_alphabetic() { + return Err(unsupported( + p, + "the number domain after `\\mathbb{` must be a letter; only `\\mathbb{Z}` is supported", + )); + } + p += 1; + if p >= bytes.len() || bytes[p] != b'}' { + return Err(syntax( + p, + "expected `}` to close the domain; write e.g. `\\mathbb{Z}`", + )); + } + return Ok((Some(Tok::Mathbb(letter as char)), p + 1)); + } + "operatorname" => { + if k >= bytes.len() || bytes[k] != b'{' { + return Err(syntax( + k, + "`\\operatorname` must be followed by a function name in braces, e.g. `\\operatorname{square}(x)`", + )); + } + let mut p = k + 1; + if p >= bytes.len() || !bytes[p].is_ascii_alphabetic() { + return Err(syntax( + p.min(bytes.len()), + "`\\operatorname{...}` requires an ASCII identifier starting with a letter, e.g. `\\operatorname{square}`", + )); + } + let id_start = p; + p += 1; + while p < bytes.len() && (bytes[p].is_ascii_alphanumeric() || bytes[p] == b'_') { + p += 1; + } + let id = text[id_start..p].to_owned(); + if p >= bytes.len() || bytes[p] != b'}' { + return Err(syntax( + p.min(bytes.len()), + "expected `}` to close `\\operatorname{...}`", + )); + } + return Ok((Some(Tok::OperatorName(id)), p + 1)); + } + _ => { + return Err(unsupported( + start, + format!( + "LaTeX command `\\{name}` is not supported by the first-version integer fragment" + ), + )); + } + }; + Ok((Some(token), k)) +} + +/// Tokenize the whole literal. Rejects unknown constructs and enforces the +/// lexical token budget before the parser runs. +fn lex(text: &str) -> FormulaResult> { + let bytes = text.as_bytes(); + let mut tokens: Vec = Vec::new(); + let mut i = 0usize; + while i < bytes.len() { + let b = bytes[i]; + if matches!(b, b' ' | b'\t' | b'\r' | b'\n') { + i += 1; + continue; + } + let start = i; + let token = if b == b'\\' { + let (token, next) = lex_command(text, start)?; + i = next; + match token { + Some(token) => token, + None => continue, + } + } else if b.is_ascii_digit() { + let mut j = i + 1; + while j < bytes.len() && bytes[j].is_ascii_digit() { + j += 1; + } + let digits = &text[i..j]; + if digits == "0" + && j < bytes.len() + && (bytes[j] == b'x' || bytes[j] == b'X') + && (j + 1 >= bytes.len() || bytes[j + 1].is_ascii_hexdigit()) + { + return Err(unsupported( + start, + "hexadecimal literals are not supported; write integers in decimal notation", + )); + } + if digits.len() > limits::MAX_LITERAL_DIGITS { + return Err(budget( + start, + format!( + "integer literal has {} digits, exceeding the limit of {}", + digits.len(), + limits::MAX_LITERAL_DIGITS + ), + )); + } + i = j; + Tok::Nat(digits.to_owned()) + } else if b.is_ascii_alphabetic() { + let mut j = i + 1; + while j < bytes.len() && (bytes[j].is_ascii_alphanumeric() || bytes[j] == b'_') { + j += 1; + } + let id = &text[i..j]; + i = j; + Tok::Id(id.to_owned()) + } else { + i += 1; + match b { + b',' => Tok::Comma, + b'+' => Tok::Plus, + b'-' => Tok::Minus, + b'^' => Tok::Caret, + b'(' => Tok::LParen, + b')' => Tok::RParen, + b'{' => Tok::LBrace, + b'}' => Tok::RBrace, + b'<' => Tok::Rel(Rel::Lt), + b'>' => Tok::Rel(Rel::Gt), + b'=' => Tok::Rel(Rel::Eq), + b'*' => { + return Err(unsupported( + start, + "the `*`/`**` operators are not supported; write `\\cdot` (or `\\times`) for products and `^` for exponentiation", + )); + } + b'/' => { + return Err(unsupported( + start, + "division (`/`, `//`) is not supported by the integer fragment", + )); + } + b'%' => { + return Err(unsupported( + start, + "the remainder operator `%` is not supported by the integer fragment", + )); + } + b'_' => { + return Err(unsupported( + start, + "subscripts are not supported; identifier names may contain `_` but subscripts such as `x_{1}` are not part of the grammar", + )); + } + b'$' => { + return Err(unsupported( + start, + "a `$` delimiter is not part of a display-math payload; exactly one formula literal is expected", + )); + } + b'.' => { + return Err(unsupported( + start, + "decimal points are not supported; only arbitrary-precision integer literals are modelled", + )); + } + _ => { + if b.is_ascii() { + return Err(unsupported( + start, + format!( + "character `{}` (U+{b:04X}) is not supported in a formula", + b as char + ), + )); + } + let ch = match text[start..].chars().next() { + Some(ch) => ch, + None => { + return Err(syntax( + start, + "invalid UTF-8 byte at the end of the formula", + )) + } + }; + return Err(unsupported( + start, + format!( + "non-ASCII character `{ch}` (U+{:04X}) is not supported; the formula fragment is ASCII-only and uses commands such as `\\geq`", + ch as u32 + ), + )); + } + } + }; + tokens.push(Token { + tok: token, + offset: start, + }); + if tokens.len() > limits::MAX_FORMULA_TOKENS { + return Err(budget( + start, + format!( + "formula has more than {} lexical tokens", + limits::MAX_FORMULA_TOKENS + ), + )); + } + } + Ok(tokens) +} + +// --------------------------------------------------------------------------- +// Parser +// --------------------------------------------------------------------------- + +/// Lean/Marqdo words that may not name a bound variable. This prevents Lean +/// keyword injection through binder names and mirrors the documented list. +const RESERVED: &[&str] = &[ + "forall", + "fun", + "let", + "match", + "with", + "in", + "Prop", + "Type", + "Sort", + "Int", + "Nat", + "true", + "false", + "if", + "then", + "else", + "do", + "return", + "axiom", + "theorem", + "def", + "by", + "have", + "show", + "calc", + "from", + "at", + "using", + "open", + "namespace", + "section", + "end", + "variable", + "universe", + "quot", + "sorry", +]; + +/// An integer expression together with its AST depth (used for the depth +/// budget; parentheses do not add nodes). +struct PInt { + expr: IntExpr, + depth: usize, +} + +/// A proposition together with its AST depth. +struct PProp { + expr: PropExpr, + depth: usize, +} + +/// Parser over the token vector. `nest` counts only constructs that recurse +/// (`(`, `\neg`, unary `-`, model-call argument lists and the right operand of +/// `\Rightarrow`), so grammar frames stay bounded while the *AST* depth budget +/// is enforced separately and reports the documented `Budget` kind. +struct Parser<'a> { + literal: &'a str, + tokens: Vec, + pos: usize, + nest: usize, + vars: Vec, +} + +impl<'a> Parser<'a> { + fn new(literal: &'a str, tokens: Vec) -> Parser<'a> { + Parser { + literal, + tokens, + pos: 0, + nest: 0, + vars: Vec::new(), + } + } + + fn peek(&self) -> Option<&Tok> { + self.tokens.get(self.pos).map(|token| &token.tok) + } + + fn tok_offset(&self) -> usize { + self.tokens + .get(self.pos) + .map_or(self.literal.len(), |token| token.offset) + } + + fn at_end(&self) -> bool { + self.pos >= self.tokens.len() + } + + fn bump(&mut self) { + if self.pos < self.tokens.len() { + self.pos += 1; + } + } + + /// Increment the recursive-construct depth. This is the stack-safety guard + /// as well as a budget: deep parentheses/negations are rejected as `Budget` + /// instead of risking a stack overflow. + fn enter_nest(&mut self, offset: usize) -> FormulaResult<()> { + self.nest += 1; + if self.nest > limits::MAX_AST_DEPTH { + return Err(budget( + offset, + format!( + "formula nesting depth exceeds the limit of {}", + limits::MAX_AST_DEPTH + ), + )); + } + Ok(()) + } + + fn leave_nest(&mut self) { + self.nest = self.nest.saturating_sub(1); + } + + /// Check the AST depth budget after building a node. + fn check_depth(&self, depth: usize, offset: usize) -> FormulaResult<()> { + if depth > limits::MAX_AST_DEPTH { + return Err(budget( + offset, + format!( + "formula AST depth exceeds the limit of {}", + limits::MAX_AST_DEPTH + ), + )); + } + Ok(()) + } + + /// True when the binder region (bounded by the first non-binder token) + /// contains `\in`, which distinguishes a missing domain (unsupported) from a + /// merely malformed binder (syntax). + fn binder_has_domain(&self) -> bool { + for token in &self.tokens[self.pos..] { + match &token.tok { + Tok::Id(_) | Tok::Comma | Tok::Mathbb(_) => {} + Tok::In => return true, + _ => return false, + } + } + false + } + + fn parse_goal(mut self, span: Span) -> FormulaResult { + if self.at_end() { + return Err(syntax( + 0, + "the formula is empty; one display-math block must contain exactly one integer proposition", + )); + } + if matches!(self.peek(), Some(Tok::Forall)) { + let forall_offset = self.tok_offset(); + self.bump(); + if !self.binder_has_domain() { + return Err(unsupported( + forall_offset, + "the `\\forall` binder is missing its domain; write `\\forall x\\in\\mathbb{Z}, ...` (only the integer domain `\\mathbb{Z}` is supported)", + )); + } + loop { + let Some(token) = self.peek() else { + return Err(syntax( + self.literal.len(), + "expected a variable name after `\\forall`", + )); + }; + let Tok::Id(name) = token else { + return Err(syntax( + self.tok_offset(), + format!( + "expected a variable name after `\\forall`, found {}", + tok_name(token) + ), + )); + }; + let name = name.clone(); + let offset = self.tok_offset(); + if RESERVED.contains(&name.as_str()) { + return Err(syntax( + offset, + format!( + "`{}` is a reserved Lean/Marqdo word and cannot be used as a bound variable", + excerpt(&name) + ), + )); + } + if self.vars.iter().any(|existing| existing == &name) { + return Err(syntax( + offset, + format!( + "duplicate bound variable `{}`; each `\\forall` variable may be bound only once", + excerpt(&name) + ), + )); + } + self.vars.push(name); + if self.vars.len() > limits::MAX_VARS { + return Err(budget( + offset, + format!("`\\forall` binds more than {} variables", limits::MAX_VARS), + )); + } + self.bump(); + if matches!(self.peek(), Some(Tok::Comma)) { + self.bump(); + continue; + } + break; + } + match self.peek() { + Some(Tok::In) => self.bump(), + Some(token) => { + return Err(syntax( + self.tok_offset(), + format!( + "expected `,` or `\\in` after the quantified variables, found {}", + tok_name(token) + ), + )); + } + None => { + return Err(syntax( + self.literal.len(), + "expected `\\in\\mathbb{Z}` after the quantified variables", + )); + } + } + let (domain, domain_offset) = match self.peek() { + Some(Tok::Mathbb(letter)) => { + let letter = *letter; + let offset = self.tok_offset(); + self.bump(); + (letter, offset) + } + Some(token) => { + return Err(syntax( + self.tok_offset(), + format!( + "expected the integer domain `\\mathbb{{Z}}` after `\\in`, found {}", + tok_name(token) + ), + )); + } + None => { + return Err(syntax( + self.literal.len(), + "expected the integer domain `\\mathbb{Z}` after `\\in`", + )); + } + }; + if domain != 'Z' { + return Err(unsupported(domain_offset, domain_unsupported(domain))); + } + match self.peek() { + Some(Tok::Comma) => self.bump(), + Some(token) => { + return Err(syntax( + self.tok_offset(), + format!( + "expected `,` after the domain `\\mathbb{{Z}}` (write `\\forall x\\in\\mathbb{{Z}}, ...`), found {}", + tok_name(token) + ), + )); + } + None => { + return Err(syntax( + self.literal.len(), + "expected `,` after the domain `\\mathbb{Z}` (write `\\forall x\\in\\mathbb{Z}, ...`)", + )); + } + } + } + if self.at_end() { + if self.vars.is_empty() { + return Err(syntax( + self.literal.len(), + "the formula is empty; one display-math block must contain exactly one integer proposition", + )); + } + return Err(syntax( + self.literal.len(), + "the formula ends after the `\\forall` binder; expected a proposition", + )); + } + let body = self.parse_imp()?; + if let Some(token) = self.peek() { + let offset = self.tok_offset(); + if matches!(token, Tok::Forall) { + return Err(unsupported( + offset, + "only one leading `\\forall` binder is supported; nested or repeated quantifiers are not part of the first-version fragment", + )); + } + return Err(syntax( + offset, + format!( + "unexpected token {} after the end of the formula; the whole display-math payload must be exactly one proposition (implicit multiplication such as `2x` is not supported)", + tok_name(token) + ), + )); + } + Ok(Goal { + vars: self.vars, + body: body.expr, + literal: self.literal.to_owned(), + span, + }) + } + + // -- propositions ------------------------------------------------------ + + fn parse_imp(&mut self) -> FormulaResult { + let lhs = self.parse_or()?; + if matches!(self.peek(), Some(Tok::Imp)) { + let offset = self.tok_offset(); + self.bump(); + self.enter_nest(offset)?; + let rhs = self.parse_imp(); + self.leave_nest(); + let rhs = rhs?; + let depth = 1 + lhs.depth.max(rhs.depth); + self.check_depth(depth, offset)?; + return Ok(PProp { + expr: PropExpr::Imp(Box::new(lhs.expr), Box::new(rhs.expr)), + depth, + }); + } + Ok(lhs) + } + + fn parse_or(&mut self) -> FormulaResult { + let mut lhs = self.parse_and()?; + while matches!(self.peek(), Some(Tok::Or)) { + let offset = self.tok_offset(); + self.bump(); + let rhs = self.parse_and()?; + let depth = 1 + lhs.depth.max(rhs.depth); + self.check_depth(depth, offset)?; + lhs = PProp { + expr: PropExpr::Or(Box::new(lhs.expr), Box::new(rhs.expr)), + depth, + }; + } + Ok(lhs) + } + + fn parse_and(&mut self) -> FormulaResult { + let mut lhs = self.parse_not()?; + while matches!(self.peek(), Some(Tok::And)) { + let offset = self.tok_offset(); + self.bump(); + let rhs = self.parse_not()?; + let depth = 1 + lhs.depth.max(rhs.depth); + self.check_depth(depth, offset)?; + lhs = PProp { + expr: PropExpr::And(Box::new(lhs.expr), Box::new(rhs.expr)), + depth, + }; + } + Ok(lhs) + } + + fn parse_not(&mut self) -> FormulaResult { + if matches!(self.peek(), Some(Tok::Neg)) { + let offset = self.tok_offset(); + self.bump(); + if self.at_end() + || matches!( + self.peek(), + Some(Tok::RParen) + | Some(Tok::And) + | Some(Tok::Or) + | Some(Tok::Imp) + | Some(Tok::Comma) + | Some(Tok::RBrace) + ) + { + return Err(syntax( + offset, + "`\\neg` must be applied to a proposition such as `\\neg (x = 0)`, not to an integer expression", + )); + } + self.enter_nest(offset)?; + let inner = self.parse_not(); + self.leave_nest(); + let inner = match inner { + Ok(inner) => inner, + Err(error) if error.kind == FormulaErrorKind::Syntax => { + return Err(syntax( + error.offset.unwrap_or(offset), + format!( + "`\\neg` requires a proposition after it (for example `\\neg (x = 0)`): {}", + error.message + ), + )); + } + Err(error) => return Err(error), + }; + let depth = 1 + inner.depth; + self.check_depth(depth, offset)?; + return Ok(PProp { + expr: PropExpr::Not(Box::new(inner.expr)), + depth, + }); + } + self.parse_atom_prop() + } + + /// `AtomProp = "(" Imp ")" | Compare`, with bounded backtracking: a leading + /// `(` is first tried as a proposition parenthesis; if that fails with a + /// syntax error it is reinterpreted as the start of an integer comparison + /// (`(x+1) = 0`). Budget/unsupported/free-variable errors are never + /// swallowed by the backtracking. + fn parse_atom_prop(&mut self) -> FormulaResult { + if matches!(self.peek(), Some(Tok::LParen)) { + let save = self.pos; + let offset = self.tok_offset(); + self.bump(); + self.enter_nest(offset)?; + let inner = self.parse_imp(); + self.leave_nest(); + match inner { + Ok(prop) => { + if matches!(self.peek(), Some(Tok::RParen)) { + self.bump(); + return Ok(prop); + } + self.pos = save; + } + Err(error) if error.kind == FormulaErrorKind::Syntax => { + self.pos = save; + } + Err(error) => return Err(error), + } + } + self.parse_compare() + } + + fn parse_compare(&mut self) -> FormulaResult { + let offset = self.tok_offset(); + let lhs = self.parse_sum()?; + let rel = match self.peek() { + Some(Tok::Rel(rel)) => { + let rel = *rel; + self.bump(); + rel + } + Some(Tok::In) => { + return Err(unsupported( + self.tok_offset(), + "set membership `\\in` is supported only in the leading `\\forall ... \\in \\mathbb{Z}` binder", + )); + } + Some(token) => { + if is_integer_term_start(token) { + return Err(syntax( + self.tok_offset(), + "implicit multiplication is not supported; write `\\cdot` or `\\times` between factors (for example `2 \\cdot x`)", + )); + } + return Err(syntax( + self.tok_offset(), + format!( + "expected a comparison operator (`=`, `\\neq`, `<`, `>`, `\\leq`, `\\geq`) after the integer expression, found {}", + tok_name(token) + ), + )); + } + None => { + return Err(syntax( + self.literal.len(), + "expected a comparison operator (`=`, `\\neq`, `<`, `>`, `\\leq`, `\\geq`) but the formula ended; a proposition needs a comparison", + )); + } + }; + let rhs = self.parse_sum()?; + if matches!(self.peek(), Some(Tok::Rel(_))) { + return Err(syntax( + self.tok_offset(), + "comparison operators cannot be chained; write the conjunction explicitly, e.g. `0 < x \\land x < 1` instead of `0 < x < 1`", + )); + } + let depth = 1 + lhs.depth.max(rhs.depth); + self.check_depth(depth, offset)?; + Ok(PProp { + expr: PropExpr::Cmp(rel, lhs.expr, rhs.expr), + depth, + }) + } + + // -- integer expressions ---------------------------------------------- + + fn parse_sum(&mut self) -> FormulaResult { + let mut lhs = self.parse_product()?; + loop { + let op = match self.peek() { + Some(Tok::Plus) => Some(true), + Some(Tok::Minus) => Some(false), + _ => None, + }; + let Some(is_add) = op else { break }; + let offset = self.tok_offset(); + self.bump(); + let rhs = self.parse_product()?; + let depth = 1 + lhs.depth.max(rhs.depth); + self.check_depth(depth, offset)?; + let expr = if is_add { + IntExpr::Add(Box::new(lhs.expr), Box::new(rhs.expr)) + } else { + IntExpr::Sub(Box::new(lhs.expr), Box::new(rhs.expr)) + }; + lhs = PInt { expr, depth }; + } + Ok(lhs) + } + + fn parse_product(&mut self) -> FormulaResult { + let mut lhs = self.parse_signed()?; + while matches!(self.peek(), Some(Tok::Star)) { + let offset = self.tok_offset(); + self.bump(); + let rhs = self.parse_signed()?; + let depth = 1 + lhs.depth.max(rhs.depth); + self.check_depth(depth, offset)?; + lhs = PInt { + expr: IntExpr::Mul(Box::new(lhs.expr), Box::new(rhs.expr)), + depth, + }; + } + Ok(lhs) + } + + fn parse_signed(&mut self) -> FormulaResult { + if matches!(self.peek(), Some(Tok::Minus)) { + let offset = self.tok_offset(); + self.bump(); + self.enter_nest(offset)?; + let inner = self.parse_signed(); + self.leave_nest(); + let inner = inner?; + let depth = 1 + inner.depth; + self.check_depth(depth, offset)?; + return Ok(PInt { + expr: IntExpr::Neg(Box::new(inner.expr)), + depth, + }); + } + self.parse_power() + } + + fn parse_power(&mut self) -> FormulaResult { + let base = self.parse_atom_int()?; + if matches!(self.peek(), Some(Tok::Caret)) { + let caret_offset = self.tok_offset(); + self.bump(); + let exponent = self.parse_exponent(caret_offset)?; + let depth = 1 + base.depth; + self.check_depth(depth, caret_offset)?; + return Ok(PInt { + expr: IntExpr::Pow(Box::new(base.expr), exponent), + depth, + }); + } + Ok(base) + } + + fn parse_exponent(&mut self, caret_offset: usize) -> FormulaResult { + if self.at_end() { + return Err(syntax( + self.literal.len(), + "expected an exponent after `^`; a bare exponent is one digit (`x^2`) and a multi-digit exponent needs braces (`x^{12}`)", + )); + } + match self.peek() { + Some(Tok::Nat(text)) => { + let text = text.clone(); + let offset = self.tok_offset(); + self.bump(); + if text.len() != 1 { + return Err(syntax( + offset, + format!( + "an unbraced exponent must be a single digit; write `x^{{{text}}}` instead of `x^{text}`" + ), + )); + } + let digit = match text.bytes().next() { + Some(digit) => digit, + None => { + return Err(syntax(offset, "expected a single-digit exponent after `^`")) + } + }; + Ok(u32::from(digit - b'0')) + } + Some(Tok::LBrace) => { + self.bump(); + let Some(Tok::Nat(text)) = self.peek() else { + return Err(syntax( + self.tok_offset(), + "expected a natural-number exponent inside `{...}`, e.g. `x^{12}`", + )); + }; + let text = text.clone(); + let offset = self.tok_offset(); + self.bump(); + let value = exponent_value(&text, offset)?; + match self.peek() { + Some(Tok::RBrace) => self.bump(), + Some(token) => { + return Err(syntax( + self.tok_offset(), + format!("expected `}}` to close the exponent, found {}", tok_name(token)), + )); + } + None => { + return Err(syntax( + self.literal.len(), + "expected `}` to close the exponent", + )); + } + } + Ok(value) + } + Some(token) => Err(syntax( + self.tok_offset(), + format!( + "expected an exponent after `^`, found {}; write a single digit or braces such as `x^{{12}}`", + tok_name(token) + ), + )), + None => Err(syntax( + self.literal.len(), + format!( + "expected an exponent after `^` (offset {caret_offset}); write a single digit or braces such as `x^{{12}}`" + ), + )), + } + } + + fn parse_atom_int(&mut self) -> FormulaResult { + let Some(token) = self.peek() else { + return Err(syntax( + self.literal.len(), + "expected an integer expression but the formula ended", + )); + }; + let token = token.clone(); + let offset = self.tok_offset(); + match token { + Tok::Nat(text) => { + self.bump(); + let Some(value) = BigInt::parse_bytes(text.as_bytes(), 10) else { + return Err(syntax(offset, "invalid decimal integer literal")); + }; + Ok(PInt { + expr: IntExpr::Lit(value), + depth: 1, + }) + } + Tok::Id(name) => { + self.bump(); + if matches!(self.peek(), Some(Tok::LBrace)) { + return Err(unsupported( + self.tok_offset(), + "subscripts are not supported; identifiers are plain ASCII names (letters, digits and `_`) without a following `{...}`", + )); + } + let Some(index) = self.vars.iter().position(|bound| bound == &name) else { + return Err(free_variable(offset, &name)); + }; + Ok(PInt { + expr: IntExpr::Var(index), + depth: 1, + }) + } + Tok::LParen => { + self.bump(); + self.enter_nest(offset)?; + let inner = self.parse_sum(); + self.leave_nest(); + let inner = inner?; + match self.peek() { + Some(Tok::RParen) => self.bump(), + Some(token) => { + let found = tok_name(token); + return Err(syntax( + self.tok_offset(), + format!( + "expected `)` to close the integer parenthesis opened at byte {offset}, found {found}" + ), + )); + } + None => { + return Err(syntax( + self.literal.len(), + format!( + "expected `)` to close the integer parenthesis opened at byte {offset}" + ), + )); + } + } + Ok(inner) + } + Tok::OperatorName(alias) => { + self.bump(); + if !matches!(self.peek(), Some(Tok::LParen)) { + return Err(syntax( + self.tok_offset(), + format!( + "`\\operatorname{{{}}}` must be applied to an argument list, e.g. `\\operatorname{{{}}}(x)`", + excerpt(&alias), + excerpt(&alias) + ), + )); + } + self.bump(); + self.enter_nest(offset)?; + let parsed_args = self.parse_call_args(); + self.leave_nest(); + let parsed_args = parsed_args?; + let depth = 1 + parsed_args + .iter() + .map(|arg| arg.depth) + .max() + .unwrap_or(0); + self.check_depth(depth, offset)?; + let args = parsed_args.into_iter().map(|arg| arg.expr).collect(); + Ok(PInt { + expr: IntExpr::ModelCall { alias, args }, + depth, + }) + } + Tok::Forall => Err(unsupported( + offset, + "nested or repeated `\\forall` is not supported; the first version allows only one leading `\\forall` binder", + )), + Tok::Mathbb(letter) => Err(unsupported( + offset, + format!( + "the domain `\\mathbb{{{letter}}}` may appear only in the leading `\\forall ... \\in \\mathbb{{Z}}` binder" + ), + )), + Tok::In => Err(unsupported( + offset, + "set membership `\\in` is supported only in the leading `\\forall ... \\in \\mathbb{Z}` binder", + )), + other => Err(syntax( + offset, + format!( + "expected an integer expression (a number, a bound variable, `( ... )` or a `\\operatorname{{...}}` model call), found {}", + tok_name(&other) + ), + )), + } + } + + fn parse_call_args(&mut self) -> FormulaResult> { + let mut args = Vec::new(); + if matches!(self.peek(), Some(Tok::RParen)) { + self.bump(); + return Ok(args); + } + loop { + let arg = self.parse_sum()?; + args.push(arg); + match self.peek() { + Some(Tok::Comma) => self.bump(), + Some(Tok::RParen) => { + self.bump(); + return Ok(args); + } + Some(token) => { + return Err(syntax( + self.tok_offset(), + format!( + "expected `,` or `)` in the model-call argument list, found {}", + tok_name(token) + ), + )); + } + None => { + return Err(syntax( + self.literal.len(), + "expected `)` to close the model-call argument list", + )); + } + } + } + } +} + +/// Parse a braced exponent decimal string, enforcing the documented exponent +/// bound as an `Unsupported` (never truncating). +fn exponent_value(text: &str, offset: usize) -> FormulaResult { + let significant = text.trim_start_matches('0'); + if significant.len() > 2 { + return Err(unsupported( + offset, + format!( + "exponent `{text}` exceeds the maximum supported exponent {}", + limits::MAX_EXPONENT + ), + )); + } + let value: u32 = if significant.is_empty() { + 0 + } else { + match significant.parse::() { + Ok(value) => value, + Err(_) => { + return Err(unsupported( + offset, + format!( + "exponent `{text}` exceeds the maximum supported exponent {}", + limits::MAX_EXPONENT + ), + )) + } + } + }; + if value > limits::MAX_EXPONENT { + return Err(unsupported( + offset, + format!( + "exponent `{text}` exceeds the maximum supported exponent {}", + limits::MAX_EXPONENT + ), + )); + } + Ok(value) +} + +/// Does this token start an integer term? Used to turn `2x`/`a b` style token +/// sequences into a clear implicit-multiplication syntax error. +fn is_integer_term_start(tok: &Tok) -> bool { + matches!( + tok, + Tok::Nat(_) | Tok::Id(_) | Tok::OperatorName(_) | Tok::LParen + ) +} + +/// Message for an unsupported numeric domain named after `\mathbb{...}`. +fn domain_unsupported(letter: char) -> String { + match letter { + 'R' => "the real-number domain `\\mathbb{R}` is not supported; the first version reasons only about integers `\\mathbb{Z}`".to_owned(), + 'N' => "the natural-number domain `\\mathbb{N}` is not supported; write the integers `\\mathbb{Z}` and any non-negativity premise explicitly".to_owned(), + 'Q' => "the rational-number domain `\\mathbb{Q}` is not supported; the first version reasons only about integers `\\mathbb{Z}`".to_owned(), + 'C' => "the complex-number domain `\\mathbb{C}` is not supported; the first version reasons only about integers `\\mathbb{Z}`".to_owned(), + other => format!("the number domain `\\mathbb{{{other}}}` is not supported; only the integer domain `\\mathbb{{Z}}` is supported"), + } +} + +/// Validate an identifier produced by the parser: ASCII letter then ASCII +/// letters/digits/underscore. +fn is_ascii_id(name: &str) -> bool { + let mut bytes = name.bytes(); + match bytes.next() { + Some(first) if first.is_ascii_alphabetic() => {} + _ => return false, + } + bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_') +} + +/// Validate a Lean definition name supplied through the alias map before it is +/// placed into generated source. The map is internal/trusted, but generated +/// source must stay structured even if a caller passes something odd. +fn is_valid_lean_def_name(name: &str) -> bool { + if name.is_empty() || name == "sorry" || name == "axiom" { + return false; + } + !name + .chars() + .any(|ch| ch.is_whitespace() || ch.is_control() || matches!(ch, '(' | ')' | '"' | '\\')) +} + +// --------------------------------------------------------------------------- +// Normal-form rendering (reports and tests) +// --------------------------------------------------------------------------- + +const PROP_IMP: i32 = 0; +const PROP_OR: i32 = 1; +const PROP_AND: i32 = 2; +const PROP_NOT: i32 = 3; +const PROP_CMP: i32 = 4; + +const INT_SUM: i32 = 1; +const INT_MUL: i32 = 2; +const INT_NEG: i32 = 3; +const INT_POW: i32 = 4; +const INT_ATOM: i32 = 5; + +fn prop_precedence(prop: &PropExpr) -> i32 { + match prop { + PropExpr::Imp(_, _) => PROP_IMP, + PropExpr::Or(_, _) => PROP_OR, + PropExpr::And(_, _) => PROP_AND, + PropExpr::Not(_) => PROP_NOT, + PropExpr::Cmp(_, _, _) => PROP_CMP, + } +} + +fn int_precedence(expr: &IntExpr) -> i32 { + match expr { + IntExpr::Add(_, _) | IntExpr::Sub(_, _) => INT_SUM, + IntExpr::Mul(_, _) => INT_MUL, + IntExpr::Neg(_) => INT_NEG, + IntExpr::Pow(_, _) => INT_POW, + IntExpr::Lit(_) | IntExpr::Var(_) | IntExpr::ModelCall { .. } => INT_ATOM, + } +} + +fn render_prop_normal(prop: &PropExpr, vars: &[String], min_precedence: i32, out: &mut String) { + let precedence = prop_precedence(prop); + let parenthesize = precedence < min_precedence; + if parenthesize { + out.push('('); + } + match prop { + PropExpr::Cmp(rel, lhs, rhs) => { + render_int_normal(lhs, vars, INT_SUM, out); + out.push(' '); + out.push_str(rel.glyph()); + out.push(' '); + render_int_normal(rhs, vars, INT_SUM, out); + } + PropExpr::Not(inner) => { + out.push('¬'); + out.push('('); + render_prop_normal(inner, vars, PROP_IMP, out); + out.push(')'); + } + PropExpr::And(lhs, rhs) => { + render_prop_normal(lhs, vars, PROP_AND, out); + out.push_str(" ∧ "); + render_prop_normal(rhs, vars, PROP_AND, out); + } + PropExpr::Or(lhs, rhs) => { + render_prop_normal(lhs, vars, PROP_OR, out); + out.push_str(" ∨ "); + render_prop_normal(rhs, vars, PROP_OR, out); + } + PropExpr::Imp(lhs, rhs) => { + render_prop_normal(lhs, vars, PROP_NOT + 1, out); + out.push_str(" → "); + render_prop_normal(rhs, vars, PROP_IMP, out); + } + } + if parenthesize { + out.push(')'); + } +} + +fn render_int_normal(expr: &IntExpr, vars: &[String], min_precedence: i32, out: &mut String) { + let precedence = int_precedence(expr); + let parenthesize = precedence < min_precedence; + if parenthesize { + out.push('('); + } + match expr { + IntExpr::Lit(value) => out.push_str(&value.to_string()), + IntExpr::Var(index) => match vars.get(*index) { + Some(name) => out.push_str(name), + None => { + // Defensive: only reachable for hand-built ASTs; never panic. + out.push('m'); + out.push('q'); + out.push('x'); + out.push_str(&index.to_string()); + } + }, + IntExpr::Neg(inner) => { + out.push('-'); + render_int_normal(inner, vars, INT_NEG + 1, out); + } + IntExpr::Add(lhs, rhs) => { + render_int_normal(lhs, vars, INT_SUM, out); + out.push_str(" + "); + render_int_normal(rhs, vars, INT_MUL, out); + } + IntExpr::Sub(lhs, rhs) => { + render_int_normal(lhs, vars, INT_SUM, out); + out.push_str(" - "); + render_int_normal(rhs, vars, INT_MUL, out); + } + IntExpr::Mul(lhs, rhs) => { + render_int_normal(lhs, vars, INT_MUL, out); + out.push_str(" · "); + render_int_normal(rhs, vars, INT_NEG, out); + } + IntExpr::Pow(base, exponent) => { + render_int_normal(base, vars, INT_ATOM, out); + out.push('^'); + out.push_str(&exponent.to_string()); + } + IntExpr::ModelCall { alias, args } => { + out.push_str(alias); + out.push('('); + for (position, arg) in args.iter().enumerate() { + if position > 0 { + out.push_str(", "); + } + render_int_normal(arg, vars, INT_SUM, out); + } + out.push(')'); + } + } + if parenthesize { + out.push(')'); + } +} + +// --------------------------------------------------------------------------- +// Lean rendering +// --------------------------------------------------------------------------- + +fn render_prop_lean( + prop: &PropExpr, + var_count: usize, + aliases: &BTreeMap, + out: &mut String, +) -> FormulaResult<()> { + match prop { + PropExpr::Cmp(rel, lhs, rhs) => { + out.push('('); + render_int_lean(lhs, var_count, aliases, out)?; + out.push(' '); + out.push_str(rel.glyph()); + out.push(' '); + render_int_lean(rhs, var_count, aliases, out)?; + out.push(')'); + } + PropExpr::Not(inner) => { + out.push_str("¬("); + render_prop_lean(inner, var_count, aliases, out)?; + out.push(')'); + } + PropExpr::And(lhs, rhs) => { + out.push('('); + render_prop_lean(lhs, var_count, aliases, out)?; + out.push_str(" ∧ "); + render_prop_lean(rhs, var_count, aliases, out)?; + out.push(')'); + } + PropExpr::Or(lhs, rhs) => { + out.push('('); + render_prop_lean(lhs, var_count, aliases, out)?; + out.push_str(" ∨ "); + render_prop_lean(rhs, var_count, aliases, out)?; + out.push(')'); + } + PropExpr::Imp(lhs, rhs) => { + out.push('('); + render_prop_lean(lhs, var_count, aliases, out)?; + out.push_str(" → "); + render_prop_lean(rhs, var_count, aliases, out)?; + out.push(')'); + } + } + Ok(()) +} + +fn render_int_lean( + expr: &IntExpr, + var_count: usize, + aliases: &BTreeMap, + out: &mut String, +) -> FormulaResult<()> { + match expr { + IntExpr::Lit(value) => { + out.push('('); + out.push_str(&value.to_string()); + out.push_str(" : Int)"); + } + IntExpr::Var(index) => { + if *index >= var_count { + return Err(FormulaError::new( + FormulaErrorKind::Unsupported, + None, + "internal variable index is out of range while rendering the Lean goal", + )); + } + out.push_str("mqx"); + out.push_str(&index.to_string()); + } + IntExpr::Neg(inner) => { + out.push_str("(- "); + render_int_lean(inner, var_count, aliases, out)?; + out.push(')'); + } + IntExpr::Add(lhs, rhs) => { + out.push('('); + render_int_lean(lhs, var_count, aliases, out)?; + out.push_str(" + "); + render_int_lean(rhs, var_count, aliases, out)?; + out.push(')'); + } + IntExpr::Sub(lhs, rhs) => { + out.push('('); + render_int_lean(lhs, var_count, aliases, out)?; + out.push_str(" - "); + render_int_lean(rhs, var_count, aliases, out)?; + out.push(')'); + } + IntExpr::Mul(lhs, rhs) => { + out.push('('); + render_int_lean(lhs, var_count, aliases, out)?; + out.push_str(" * "); + render_int_lean(rhs, var_count, aliases, out)?; + out.push(')'); + } + IntExpr::Pow(base, exponent) => { + out.push('('); + render_int_lean(base, var_count, aliases, out)?; + out.push_str(" ^ ("); + out.push_str(&exponent.to_string()); + out.push_str(" : Nat))"); + } + IntExpr::ModelCall { alias, args } => { + if !is_ascii_id(alias) { + return Err(FormulaError::new( + FormulaErrorKind::Unsupported, + None, + format!( + "model-call name `{}` is not a valid ASCII identifier", + excerpt(alias) + ), + )); + } + let Some(lean_name) = aliases.get(alias) else { + return Err(FormulaError::new( + FormulaErrorKind::Unsupported, + None, + format!( + "model function `{}` is not bound to a Lean definition; declare it in the proof dependency list and pass its exact signature", + excerpt(alias) + ), + )); + }; + if !is_valid_lean_def_name(lean_name) { + return Err(FormulaError::new( + FormulaErrorKind::Unsupported, + None, + format!( + "the Lean definition name bound to model function `{}` is not a safe Lean identifier", + excerpt(alias) + ), + )); + } + out.push('('); + out.push_str(lean_name); + for arg in args { + out.push(' '); + render_int_lean(arg, var_count, aliases, out)?; + } + out.push(')'); + } + } + Ok(()) +} + +// --------------------------------------------------------------------------- +// Alias collection and evaluation +// --------------------------------------------------------------------------- + +fn collect_aliases_int(expr: &IntExpr, aliases: &mut BTreeSet) { + match expr { + IntExpr::Lit(_) | IntExpr::Var(_) => {} + IntExpr::Neg(inner) => collect_aliases_int(inner, aliases), + IntExpr::Add(lhs, rhs) | IntExpr::Sub(lhs, rhs) | IntExpr::Mul(lhs, rhs) => { + collect_aliases_int(lhs, aliases); + collect_aliases_int(rhs, aliases); + } + IntExpr::Pow(base, _) => collect_aliases_int(base, aliases), + IntExpr::ModelCall { alias, args } => { + aliases.insert(alias.clone()); + for arg in args { + collect_aliases_int(arg, aliases); + } + } + } +} + +fn collect_aliases_prop(prop: &PropExpr, aliases: &mut BTreeSet) { + match prop { + PropExpr::Cmp(_, lhs, rhs) => { + collect_aliases_int(lhs, aliases); + collect_aliases_int(rhs, aliases); + } + PropExpr::Not(inner) => collect_aliases_prop(inner, aliases), + PropExpr::And(lhs, rhs) | PropExpr::Or(lhs, rhs) | PropExpr::Imp(lhs, rhs) => { + collect_aliases_prop(lhs, aliases); + collect_aliases_prop(rhs, aliases); + } + } +} + +/// Upper bound on the bit length of any intermediate value during +/// [`Goal::evaluate`]. Values beyond it are absurd artefacts of a pathological +/// instance, not mathematics: returning `None` is preferable to unbounded +/// allocation. +const MAX_EVAL_BITS: u64 = 1_000_000; + +fn eval_int(expr: &IntExpr, values: &[BigInt]) -> Option { + match expr { + IntExpr::Lit(value) => { + if value.bits() > MAX_EVAL_BITS { + return None; + } + Some(value.clone()) + } + IntExpr::Var(index) => { + let value = values.get(*index)?; + if value.bits() > MAX_EVAL_BITS { + return None; + } + Some(value.clone()) + } + IntExpr::Neg(inner) => { + let value = eval_int(inner, values)?; + Some(-value) + } + IntExpr::Add(lhs, rhs) => { + let left = eval_int(lhs, values)?; + let right = eval_int(rhs, values)?; + let value = left + right; + if value.bits() > MAX_EVAL_BITS { + return None; + } + Some(value) + } + IntExpr::Sub(lhs, rhs) => { + let left = eval_int(lhs, values)?; + let right = eval_int(rhs, values)?; + let value = left - right; + if value.bits() > MAX_EVAL_BITS { + return None; + } + Some(value) + } + IntExpr::Mul(lhs, rhs) => { + let left = eval_int(lhs, values)?; + let right = eval_int(rhs, values)?; + if left.bits().saturating_add(right.bits()) > MAX_EVAL_BITS { + return None; + } + let value = left * right; + if value.bits() > MAX_EVAL_BITS { + return None; + } + Some(value) + } + IntExpr::Pow(base, exponent) => { + if *exponent > limits::MAX_EXPONENT { + return None; + } + let base = eval_int(base, values)?; + if base.bits().saturating_mul(u64::from(*exponent)) > MAX_EVAL_BITS { + return None; + } + let value = base.pow(*exponent); + if value.bits() > MAX_EVAL_BITS { + return None; + } + Some(value) + } + IntExpr::ModelCall { .. } => None, + } +} + +fn eval_prop(prop: &PropExpr, values: &[BigInt]) -> Option { + match prop { + PropExpr::Cmp(rel, lhs, rhs) => { + let left = eval_int(lhs, values)?; + let right = eval_int(rhs, values)?; + Some(match rel { + Rel::Eq => left == right, + Rel::Ne => left != right, + Rel::Lt => left < right, + Rel::Gt => left > right, + Rel::Le => left <= right, + Rel::Ge => left >= right, + }) + } + PropExpr::Not(inner) => Some(!eval_prop(inner, values)?), + PropExpr::And(lhs, rhs) => { + let left = eval_prop(lhs, values)?; + let right = eval_prop(rhs, values)?; + Some(left && right) + } + PropExpr::Or(lhs, rhs) => { + let left = eval_prop(lhs, values)?; + let right = eval_prop(rhs, values)?; + Some(left || right) + } + PropExpr::Imp(lhs, rhs) => { + let left = eval_prop(lhs, values)?; + let right = eval_prop(rhs, values)?; + Some(!left || right) + } + } +} + +// --------------------------------------------------------------------------- +// Public entry point and Goal methods +// --------------------------------------------------------------------------- + +/// Parse one display-math payload into a typed [`Goal`]. The entire literal +/// must be consumed; trailing tokens are an error. `span` is the source span of +/// the display-math block, preserved verbatim on the returned goal. +pub fn parse(literal: &str, span: Span) -> std::result::Result { + let tokens = lex(literal)?; + if tokens.is_empty() { + return Err(syntax( + 0, + "the formula is empty; one display-math block must contain exactly one integer proposition", + )); + } + Parser::new(literal, tokens).parse_goal(span) +} + +impl Goal { + /// Names used in `\operatorname{...}` calls, sorted and deduplicated. + pub fn used_aliases(&self) -> BTreeSet { + let mut aliases = BTreeSet::new(); + collect_aliases_prop(&self.body, &mut aliases); + aliases + } + + /// Lean 4 source for the proposition, using only the fixed grammar + /// specified for the backend. + /// + /// Bound variables are renamed to `mqx0`, `mqx1`, ... in binder order, so + /// no user-controlled identifier is ever emitted. Returns an `Unsupported` + /// error when a model-call alias is absent from `aliases`. + pub fn lean_prop( + &self, + aliases: &BTreeMap, + ) -> std::result::Result { + let mut out = String::new(); + if !self.vars.is_empty() { + out.push('∀'); + for index in 0..self.vars.len() { + out.push(' '); + out.push_str("mqx"); + out.push_str(&index.to_string()); + } + out.push_str(" : Int, "); + } + render_prop_lean(&self.body, self.vars.len(), aliases, &mut out)?; + Ok(out) + } + + /// Deterministic, human-readable normalized statement used in reports. + pub fn normal(&self) -> String { + let mut out = String::new(); + if !self.vars.is_empty() { + out.push('∀'); + for name in &self.vars { + out.push(' '); + out.push_str(name); + } + out.push_str(" : ℤ, "); + } + render_prop_normal(&self.body, &self.vars, PROP_IMP, &mut out); + out + } + + /// Top-level antecedents of the closed proposition, in order, rendered with + /// the same surface syntax as [`Goal::normal`]. Display premises only: no + /// logical rewriting takes place. + pub fn premises(&self) -> Vec { + let mut premises = Vec::new(); + let mut current = &self.body; + while let PropExpr::Imp(lhs, rhs) = current { + let mut rendered = String::new(); + render_prop_normal(lhs, &self.vars, PROP_IMP, &mut rendered); + premises.push(rendered); + current = rhs; + } + premises + } + + /// Evaluate the proposition after substituting one integer per bound + /// variable. Returns `None` when a model call remains, when the assignment + /// length does not match, or when an absurd intermediate value is produced. + pub fn evaluate(&self, values: &[BigInt]) -> Option { + if values.len() != self.vars.len() { + return None; + } + eval_prop(&self.body, values) + } + + /// True when the goal has an explicit outer universal binder. + pub fn is_universally_quantified(&self) -> bool { + !self.vars.is_empty() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{codes, Span}; + use std::collections::{BTreeMap, BTreeSet}; + + const FIXTURE_SQUARE: &str = "\\forall x\\in\\mathbb{Z},\\quad x^2\\geq 0"; + const FIXTURE_ADD: &str = + "\\forall a,b\\in\\mathbb{Z},\\quad (a\\geq0\\land b\\geq0)\\Rightarrow a+b\\geq0"; + + fn fixture_span(literal: &str) -> Span { + Span::new(100, 100 + literal.len()) + } + + fn ok(literal: &str) -> Goal { + match parse(literal, fixture_span(literal)) { + Ok(goal) => goal, + Err(error) => panic!( + "expected `{literal}` to parse, got {:?}: {}", + error.kind, error.message + ), + } + } + + fn err(literal: &str) -> FormulaError { + match parse(literal, fixture_span(literal)) { + Ok(goal) => panic!( + "expected `{literal}` to fail, but it parsed as `{}`", + goal.normal() + ), + Err(error) => error, + } + } + + fn err_kind(literal: &str, kind: FormulaErrorKind) -> FormulaError { + let error = err(literal); + assert_eq!( + error.kind, kind, + "literal `{literal}` produced {:?} ({}), expected {:?}", + error.kind, error.message, kind + ); + error + } + + fn aliases(pairs: &[(&str, &str)]) -> BTreeMap { + pairs + .iter() + .map(|(alias, lean)| ((*alias).to_owned(), (*lean).to_owned())) + .collect() + } + + fn no_aliases() -> BTreeMap { + BTreeMap::new() + } + + fn ten_pow(exponent: u32) -> BigInt { + let mut value = BigInt::from(1); + for _ in 0..exponent { + value = value * BigInt::from(10); + } + value + } + + // -- required fixture tests ------------------------------------------- + + #[test] + fn parses_square_fixture() { + let goal = ok(FIXTURE_SQUARE); + assert_eq!(goal.vars, vec!["x".to_owned()]); + assert_eq!( + goal.lean_prop(&no_aliases()).expect("lean_prop"), + "∀ mqx0 : Int, ((mqx0 ^ (2 : Nat)) ≥ (0 : Int))" + ); + assert_eq!(goal.normal(), "∀ x : ℤ, x^2 ≥ 0"); + assert!(goal.premises().is_empty()); + assert!(goal.is_universally_quantified()); + assert_eq!(goal.literal, FIXTURE_SQUARE); + assert_eq!(goal.span, fixture_span(FIXTURE_SQUARE)); + } + + #[test] + fn parses_add_fixture() { + let goal = ok(FIXTURE_ADD); + assert_eq!(goal.vars, vec!["a".to_owned(), "b".to_owned()]); + assert_eq!( + goal.lean_prop(&no_aliases()).expect("lean_prop"), + "∀ mqx0 mqx1 : Int, (((mqx0 ≥ (0 : Int)) ∧ (mqx1 ≥ (0 : Int))) → ((mqx0 + mqx1) ≥ (0 : Int)))" + ); + assert_eq!(goal.normal(), "∀ a b : ℤ, (a ≥ 0 ∧ b ≥ 0) → a + b ≥ 0"); + assert_eq!(goal.premises(), vec!["a ≥ 0 ∧ b ≥ 0".to_owned()]); + assert!(goal.is_universally_quantified()); + } + + #[test] + fn fixture_premises_are_display_only() { + // A conjunction inside an implication has exactly one displayed premise. + let goal = ok(FIXTURE_ADD); + assert_eq!(goal.premises().len(), 1); + // A goal whose body is not an implication has no premises. + assert!(ok(FIXTURE_SQUARE).premises().is_empty()); + // Right-associated implication chain: every antecedent is listed in order. + let chained = ok("1=1\\Rightarrow 2=2\\Rightarrow 3=3"); + assert_eq!( + chained.premises(), + vec!["1 = 1".to_owned(), "2 = 2".to_owned()] + ); + } + + #[test] + fn fixture_spans_and_literals_are_preserved() { + let literal = " \\forall x\\in\\mathbb{Z}, x = 0 "; + let span = Span::new(7, 7 + literal.len()); + let goal = parse(literal, span).expect("parse"); + assert_eq!(goal.span, span); + assert_eq!(goal.literal, literal); + } + + // -- precedence and associativity ------------------------------------- + + #[test] + fn unary_minus_binds_weaker_than_power() { + let goal = ok("\\forall x\\in\\mathbb{Z}, -x^2 \\geq 0"); + assert_eq!( + goal.lean_prop(&no_aliases()).expect("lean_prop"), + "∀ mqx0 : Int, ((- (mqx0 ^ (2 : Nat))) ≥ (0 : Int))" + ); + assert_eq!(goal.normal(), "∀ x : ℤ, -x^2 ≥ 0"); + } + + #[test] + fn parenthesized_negative_base_of_power() { + let goal = ok("\\forall x\\in\\mathbb{Z}, (-x)^2 \\geq 0"); + assert_eq!( + goal.lean_prop(&no_aliases()).expect("lean_prop"), + "∀ mqx0 : Int, (((- mqx0) ^ (2 : Nat)) ≥ (0 : Int))" + ); + assert_eq!(goal.normal(), "∀ x : ℤ, (-x)^2 ≥ 0"); + } + + #[test] + fn subtraction_is_left_associative() { + let goal = ok("\\forall a,b,c\\in\\mathbb{Z}, a-b-c = 0"); + assert_eq!( + goal.lean_prop(&no_aliases()).expect("lean_prop"), + "∀ mqx0 mqx1 mqx2 : Int, (((mqx0 - mqx1) - mqx2) = (0 : Int))" + ); + assert_eq!(goal.normal(), "∀ a b c : ℤ, a - b - c = 0"); + } + + #[test] + fn implication_is_right_associative() { + let goal = ok("1=1\\Rightarrow 2=2\\Rightarrow 3=3"); + assert_eq!( + goal.lean_prop(&no_aliases()).expect("lean_prop"), + "(((1 : Int) = (1 : Int)) → (((2 : Int) = (2 : Int)) → ((3 : Int) = (3 : Int))))" + ); + assert_eq!(goal.normal(), "1 = 1 → 2 = 2 → 3 = 3"); + assert_eq!(goal.vars, Vec::::new()); + } + + #[test] + fn conjunction_binds_tighter_than_disjunction() { + let goal = ok("1=1\\land 2=2\\lor 3=3"); + assert_eq!( + goal.lean_prop(&no_aliases()).expect("lean_prop"), + "((((1 : Int) = (1 : Int)) ∧ ((2 : Int) = (2 : Int))) ∨ ((3 : Int) = (3 : Int)))" + ); + assert_eq!(goal.normal(), "1 = 1 ∧ 2 = 2 ∨ 3 = 3"); + } + + #[test] + fn double_negation() { + let goal = ok("\\neg\\neg 1=1"); + assert_eq!( + goal.lean_prop(&no_aliases()).expect("lean_prop"), + "¬(¬(((1 : Int) = (1 : Int))))" + ); + assert_eq!(goal.normal(), "¬(¬(1 = 1))"); + } + + #[test] + fn negation_of_comparison_with_and_without_parentheses() { + let bare = ok("\\forall x\\in\\mathbb{Z}, \\neg x = 0"); + let wrapped = ok("\\forall x\\in\\mathbb{Z}, \\neg (x = 0)"); + assert_eq!(bare.normal(), "∀ x : ℤ, ¬(x = 0)"); + assert_eq!(bare.normal(), wrapped.normal()); + assert_eq!( + bare.lean_prop(&no_aliases()).expect("lean_prop"), + wrapped.lean_prop(&no_aliases()).expect("lean_prop") + ); + } + + #[test] + fn normal_form_precedence_details() { + let goal = ok("\\forall x\\in\\mathbb{Z}, -(x+1) = -x - 1"); + assert_eq!(goal.normal(), "∀ x : ℤ, -(x + 1) = -x - 1"); + + let product = ok("\\forall x\\in\\mathbb{Z}, x\\cdot(x+2) = 0"); + assert_eq!(product.normal(), "∀ x : ℤ, x · (x + 2) = 0"); + + let nested = ok("\\forall x\\in\\mathbb{Z}, x + (x + 1) = 0"); + assert_eq!(nested.normal(), "∀ x : ℤ, x + (x + 1) = 0"); + } + + // -- exponents --------------------------------------------------------- + + #[test] + fn exponent_forms() { + let braced = ok("\\forall x\\in\\mathbb{Z}, x^{12} = 0"); + assert!( + braced + .lean_prop(&no_aliases()) + .expect("lean_prop") + .contains("(mqx0 ^ (12 : Nat))"), + "braced 12-digit exponent must render as a Nat power" + ); + let single = ok("\\forall x\\in\\mathbb{Z}, x^9 = 0"); + assert!(single + .lean_prop(&no_aliases()) + .expect("lean_prop") + .contains("(mqx0 ^ (9 : Nat))")); + let zero = ok("\\forall x\\in\\mathbb{Z}, x^0 = 0"); + assert!(zero + .lean_prop(&no_aliases()) + .expect("lean_prop") + .contains("(mqx0 ^ (0 : Nat))")); + let max = ok("\\forall x\\in\\mathbb{Z}, x^{16} = 0"); + assert!(max + .lean_prop(&no_aliases()) + .expect("lean_prop") + .contains("(mqx0 ^ (16 : Nat))")); + } + + #[test] + fn exponent_errors() { + let multiline = err_kind( + "\\forall x\\in\\mathbb{Z}, x^12 = 0", + FormulaErrorKind::Syntax, + ); + assert!( + multiline.message.contains("braces") || multiline.message.contains('{'), + "message should explain that multi-digit exponents need braces: {}", + multiline.message + ); + let too_big = err_kind( + "\\forall x\\in\\mathbb{Z}, x^{17} = 0", + FormulaErrorKind::Unsupported, + ); + assert!( + too_big.message.contains("16"), + "message should name the exponent limit: {}", + too_big.message + ); + err_kind( + "\\forall x\\in\\mathbb{Z}, x^{} = 0", + FormulaErrorKind::Syntax, + ); + err_kind( + "\\forall x\\in\\mathbb{Z}, x^{12 = 0", + FormulaErrorKind::Syntax, + ); + err_kind( + "\\forall x\\in\\mathbb{Z}, x^ = 0", + FormulaErrorKind::Syntax, + ); + } + + // -- rejection tests --------------------------------------------------- + + #[test] + fn rejects_free_variables() { + let error = err_kind("x^2\\geq0", FormulaErrorKind::FreeVariable); + assert_eq!(error.code(), codes::FORMULA_FREE_VARIABLE); + assert!(error.hint.is_some()); + assert!(error.message.contains('x')); + err_kind( + "\\forall x\\in\\mathbb{Z}, x + y = 0", + FormulaErrorKind::FreeVariable, + ); + // The `A^2 = I` matrix-looking input is not guessed: it is a free symbol. + err_kind("A^2=I", FormulaErrorKind::FreeVariable); + } + + #[test] + fn rejects_unsupported_domains() { + let real = err_kind( + "\\forall x\\in\\mathbb{R}, x^2\\geq0", + FormulaErrorKind::Unsupported, + ); + assert_eq!(real.code(), codes::FORMULA_UNSUPPORTED); + assert!(real.message.contains("\\mathbb{R}")); + assert!(real.message.contains("integers")); + err_kind( + "\\forall x\\in\\mathbb{N}, x = 0", + FormulaErrorKind::Unsupported, + ); + err_kind( + "\\forall x\\in\\mathbb{Q}, x = 0", + FormulaErrorKind::Unsupported, + ); + err_kind( + "\\forall x\\in\\mathbb{C}, x = 0", + FormulaErrorKind::Unsupported, + ); + let missing = err_kind("\\forall x, x = 0", FormulaErrorKind::Unsupported); + assert!(missing.message.contains("domain")); + err_kind("\\forall x\\in\\mathbb{Z} x>0", FormulaErrorKind::Syntax); + let second = err_kind( + "\\forall x\\in\\mathbb{Z}, \\forall y\\in\\mathbb{Z}, x = y", + FormulaErrorKind::Unsupported, + ); + assert!(second.message.contains("one leading")); + } + + #[test] + fn rejects_unsupported_math() { + err_kind("\\frac{1}{2} = 0", FormulaErrorKind::Unsupported); + err_kind("\\exists x, x = 0", FormulaErrorKind::Unsupported); + err_kind("\\sum x = 0", FormulaErrorKind::Unsupported); + err_kind( + "\\forall x\\in\\mathbb{Z}, x / 2 = 0", + FormulaErrorKind::Unsupported, + ); + err_kind( + "\\forall x\\in\\mathbb{Z}, x // 2 = 0", + FormulaErrorKind::Unsupported, + ); + err_kind( + "\\forall x\\in\\mathbb{Z}, x % 2 = 0", + FormulaErrorKind::Unsupported, + ); + err_kind( + "\\forall x\\in\\mathbb{Z}, x ** 2 = 0", + FormulaErrorKind::Unsupported, + ); + err_kind( + "\\forall x\\in\\mathbb{Z}, x \\geq 0.5", + FormulaErrorKind::Unsupported, + ); + err_kind( + "\\forall x\\in\\mathbb{Z}, x \\geq 0x10", + FormulaErrorKind::Unsupported, + ); + err_kind( + "\\forall x\\in\\mathbb{Z}, x_{1} = 0", + FormulaErrorKind::Unsupported, + ); + err_kind( + "\\forall x\\in\\mathbb{Z}, x ≥ 0", + FormulaErrorKind::Unsupported, + ); + err_kind( + "\\forall x\\in\\mathbb{Z}, \\mathbb{R} = 0", + FormulaErrorKind::Unsupported, + ); + } + + #[test] + fn rejects_implicit_multiplication() { + let implicit = err_kind( + "\\forall x\\in\\mathbb{Z}, 2x\\geq0", + FormulaErrorKind::Syntax, + ); + assert!( + implicit.message.contains("implicit multiplication"), + "message should name implicit multiplication: {}", + implicit.message + ); + err_kind( + "\\forall x\\in\\mathbb{Z}, x y = 0", + FormulaErrorKind::Syntax, + ); + err_kind( + "\\forall x\\in\\mathbb{Z}, 2(x+1) = 0", + FormulaErrorKind::Syntax, + ); + } + + #[test] + fn rejects_chained_comparisons() { + let error = err_kind("\\forall x\\in\\mathbb{Z}, 0 = (0..17u8) + .map(|index| ((b'a' + index) as char).to_string()) + .collect(); + let literal = format!("\\forall {}\\in\\mathbb{{Z}}, a = 0", names.join(",")); + let error = err_kind(&literal, FormulaErrorKind::Budget); + assert_eq!(error.code(), codes::FORMULA_SYNTAX); + let names16: Vec = (0..16u8) + .map(|index| ((b'a' + index) as char).to_string()) + .collect(); + let literal16 = format!("\\forall {}\\in\\mathbb{{Z}}, a = 0", names16.join(",")); + let goal = ok(&literal16); + assert_eq!(goal.vars.len(), 16); + } + + #[test] + fn budget_for_too_many_tokens() { + let literal = "x ".repeat(limits::MAX_FORMULA_TOKENS + 1); + let error = err_kind(&literal, FormulaErrorKind::Budget); + assert!(error.message.contains("tokens")); + } + + #[test] + fn budget_for_literal_digits() { + let literal = format!( + "\\forall x\\in\\mathbb{{Z}}, {} = 0", + "9".repeat(limits::MAX_LITERAL_DIGITS + 1) + ); + let error = err_kind(&literal, FormulaErrorKind::Budget); + assert!(error.message.contains("digits")); + + let accepted = format!( + "\\forall x\\in\\mathbb{{Z}}, {} = 0", + "9".repeat(limits::MAX_LITERAL_DIGITS) + ); + let goal = ok(&accepted); + assert_eq!(goal.vars, vec!["x".to_owned()]); + } + + #[test] + fn budget_for_deep_nesting() { + let literal = format!( + "{}1=1{}", + "(".repeat(limits::MAX_AST_DEPTH + 12), + ")".repeat(limits::MAX_AST_DEPTH + 12) + ); + err_kind(&literal, FormulaErrorKind::Budget); + + let negations = format!( + "\\forall x\\in\\mathbb{{Z}}, {}-x \\geq 0", + "-".repeat(limits::MAX_AST_DEPTH + 12) + ); + err_kind(&negations, FormulaErrorKind::Budget); + + let sums = format!( + "\\forall x\\in\\mathbb{{Z}}, x{} = 0", + " + x".repeat(limits::MAX_AST_DEPTH + 12) + ); + err_kind(&sums, FormulaErrorKind::Budget); + } + + #[test] + fn rejects_negation_without_proposition() { + let error = err_kind( + "\\forall x\\in\\mathbb{Z}, \\neg x", + FormulaErrorKind::Syntax, + ); + assert!(error.message.contains("\\neg"), "{}", error.message); + err_kind("\\neg", FormulaErrorKind::Syntax); + // A negated comparison is valid, including the unparenthesized form. + ok("\\forall x\\in\\mathbb{Z}, \\neg x = 0"); + ok("\\forall x\\in\\mathbb{Z}, \\neg x \\geq 0"); + } + + #[test] + fn rejects_malformed_binders_and_calls() { + err_kind("\\forall x\\in\\mathbb{Z} x>0", FormulaErrorKind::Syntax); + err_kind( + "\\forall x y\\in\\mathbb{Z}, x = y", + FormulaErrorKind::Syntax, + ); + err_kind("\\forall x\\in\\mathbb{Z},", FormulaErrorKind::Syntax); + err_kind("\\forall \\in\\mathbb{Z}, x = 0", FormulaErrorKind::Syntax); + err_kind("\\mathbb{Z} = 0", FormulaErrorKind::Unsupported); + err_kind("\\operatorname{} = 0", FormulaErrorKind::Syntax); + err_kind("\\operatorname{9f}(1) = 0", FormulaErrorKind::Syntax); + err_kind( + "\\forall x\\in\\mathbb{Z}, \\operatorname{f} = 0", + FormulaErrorKind::Syntax, + ); + err_kind( + "\\forall x\\in\\mathbb{Z}, \\operatorname{f}(x = 0", + FormulaErrorKind::Syntax, + ); + } + + // -- parentheses and parsing structure --------------------------------- + + #[test] + fn distinguishes_integer_and_proposition_parentheses() { + let arithmetic = ok("\\forall x\\in\\mathbb{Z}, (x+1) = 0"); + assert_eq!(arithmetic.normal(), "∀ x : ℤ, x + 1 = 0"); + let logic = ok("\\forall x,y\\in\\mathbb{Z}, (x = 0) \\land (y = 0)"); + assert_eq!(logic.normal(), "∀ x y : ℤ, x = 0 ∧ y = 0"); + let nested = ok("\\forall x\\in\\mathbb{Z}, ((x+1)) = 0"); + assert_eq!(nested.normal(), "∀ x : ℤ, x + 1 = 0"); + let negated = ok("\\forall x\\in\\mathbb{Z}, \\neg (x+1) = 0"); + assert_eq!(negated.normal(), "∀ x : ℤ, ¬(x + 1 = 0)"); + } + + #[test] + fn closed_ground_formula() { + let goal = ok("1 + 2 \\cdot 3 = 7"); + assert!(goal.vars.is_empty()); + assert!(!goal.is_universally_quantified()); + assert!(goal.premises().is_empty()); + assert_eq!(goal.normal(), "1 + 2 · 3 = 7"); + assert_eq!( + goal.lean_prop(&no_aliases()).expect("lean_prop"), + "(((1 : Int) + ((2 : Int) * (3 : Int))) = (7 : Int))" + ); + assert_eq!(goal.evaluate(&[]), Some(true)); + } + + #[test] + fn ignores_documented_formatting_commands() { + let goal = ok("\\forall x \\in \\mathbb{Z}, \\quad x \\, + \\; 1 = 1"); + assert_eq!(goal.vars, vec!["x".to_owned()]); + assert_eq!(goal.normal(), "∀ x : ℤ, x + 1 = 1"); + } + + #[test] + fn parses_all_relations() { + let goal = ok( + "\\forall x\\in\\mathbb{Z}, x = 0 \\land x \\neq 1 \\land x < 2 \\land x > -1 \\land x \\leq 3 \\land x \\geq 4", + ); + let normal = goal.normal(); + for glyph in ["=", "≠", "<", ">", "≤", "≥"] { + assert!( + normal.contains(glyph), + "normal form missing {glyph}: {normal}" + ); + } + } + + // -- model calls ------------------------------------------------------- + + #[test] + fn parses_model_call_and_collects_alias() { + let goal = ok("\\forall x\\in\\mathbb{Z},\\quad \\operatorname{square}(x)\\geq0"); + assert_eq!(goal.used_aliases(), BTreeSet::from(["square".to_owned()])); + let lean = goal + .lean_prop(&aliases(&[("square", "marqdoModel_square")])) + .expect("lean_prop"); + assert_eq!( + lean, + "∀ mqx0 : Int, ((marqdoModel_square mqx0) ≥ (0 : Int))" + ); + assert!(!lean.contains("\\operatorname")); + assert!(!lean.contains("square(")); + + let missing = goal.lean_prop(&no_aliases()).expect_err("missing alias"); + assert_eq!(missing.kind, FormulaErrorKind::Unsupported); + assert_eq!(missing.code(), codes::FORMULA_UNSUPPORTED); + assert!(missing.message.contains("square")); + } + + #[test] + fn preserves_model_call_arity() { + let goal = ok("\\forall x\\in\\mathbb{Z}, \\operatorname{add}(x, 1) = 0"); + assert_eq!( + goal.lean_prop(&aliases(&[("add", "marqdoModel_add")])) + .expect("lean_prop"), + "∀ mqx0 : Int, ((marqdoModel_add mqx0 (1 : Int)) = (0 : Int))" + ); + let two = ok("\\forall x\\in\\mathbb{Z}, \\operatorname{add}(x, x) = 0"); + assert_eq!( + two.lean_prop(&aliases(&[("add", "marqdoModel_add")])) + .expect("lean_prop"), + "∀ mqx0 : Int, ((marqdoModel_add mqx0 mqx0) = (0 : Int))" + ); + let zero = ok("\\forall x\\in\\mathbb{Z}, \\operatorname{c}() = x"); + assert_eq!( + zero.lean_prop(&aliases(&[("c", "marqdoModel_c")])) + .expect("lean_prop"), + "∀ mqx0 : Int, ((marqdoModel_c) = mqx0)" + ); + } + + #[test] + fn nested_model_calls_and_alias_sorting() { + let goal = ok( + "\\forall x\\in\\mathbb{Z}, \\operatorname{f}(\\operatorname{g}(x), \\operatorname{h}(1, 2)) = 0", + ); + assert_eq!( + goal.used_aliases(), + BTreeSet::from(["f".to_owned(), "g".to_owned(), "h".to_owned()]) + ); + let map = aliases(&[ + ("f", "marqdoModel_f"), + ("g", "marqdoModel_g"), + ("h", "marqdoModel_h"), + ]); + assert_eq!( + goal.lean_prop(&map).expect("lean_prop"), + "∀ mqx0 : Int, ((marqdoModel_f (marqdoModel_g mqx0) (marqdoModel_h (1 : Int) (2 : Int))) = (0 : Int))" + ); + // Deterministic ordering: the BTreeSet iteration is sorted. + assert_eq!( + goal.used_aliases().into_iter().collect::>(), + vec!["f".to_owned(), "g".to_owned(), "h".to_owned()] + ); + } + + #[test] + fn lean_output_never_contains_user_variable_names() { + let goal = ok("\\forall zzz\\in\\mathbb{Z}, zzz = 0"); + let lean = goal.lean_prop(&no_aliases()).expect("lean_prop"); + assert!(lean.contains("mqx0")); + assert!(!lean.contains("zzz")); + assert!(!lean.contains("sorry")); + assert!(!lean.contains("axiom")); + } + + // -- evaluation -------------------------------------------------------- + + #[test] + fn evaluates_square_nonnegative() { + let goal = ok("\\forall x\\in\\mathbb{Z}, x^2 \\geq 0"); + assert_eq!(goal.evaluate(&[BigInt::from(0)]), Some(true)); + assert_eq!(goal.evaluate(&[BigInt::from(-3)]), Some(true)); + assert_eq!(goal.evaluate(&[ten_pow(200)]), Some(true)); + } + + #[test] + fn evaluates_square_less_than_zero() { + let goal = ok("\\forall x\\in\\mathbb{Z}, x^2 < 0"); + assert_eq!(goal.evaluate(&[BigInt::from(0)]), Some(false)); + assert_eq!(goal.evaluate(&[BigInt::from(1)]), Some(false)); + assert_eq!(goal.evaluate(&[BigInt::from(-2)]), Some(false)); + } + + #[test] + fn evaluates_conditional_product() { + let goal = ok("\\forall a,b\\in\\mathbb{Z}, (a>0\\land b>0)\\Rightarrow a\\cdot b>0"); + assert_eq!( + goal.evaluate(&[BigInt::from(2), BigInt::from(3)]), + Some(true) + ); + // Non-positive inputs make the antecedent false, hence the implication true. + assert_eq!( + goal.evaluate(&[BigInt::from(0), BigInt::from(3)]), + Some(true) + ); + assert_eq!( + goal.evaluate(&[BigInt::from(-2), BigInt::from(-2)]), + Some(true) + ); + } + + #[test] + fn evaluation_returns_none_for_model_calls_and_arity_mismatch() { + let model = ok("\\forall x\\in\\mathbb{Z}, \\operatorname{square}(x)\\geq0"); + assert_eq!(model.evaluate(&[BigInt::from(1)]), None); + + let plain = ok("\\forall x\\in\\mathbb{Z}, x^2 \\geq 0"); + assert_eq!(plain.evaluate(&[]), None); + assert_eq!(plain.evaluate(&[BigInt::from(1), BigInt::from(2)]), None); + } + + #[test] + fn evaluation_handles_logic_combinators() { + let goal = ok("\\forall x\\in\\mathbb{Z}, (x = 0 \\lor x = 1) \\land \\neg (x = 5)"); + assert_eq!(goal.evaluate(&[BigInt::from(0)]), Some(true)); + assert_eq!(goal.evaluate(&[BigInt::from(5)]), Some(false)); + assert_eq!(goal.evaluate(&[BigInt::from(2)]), Some(false)); + } + + // -- diagnostics and robustness --------------------------------------- + + #[test] + fn diagnostic_codes_are_stable() { + assert_eq!( + err("1 + = 2").code(), + codes::FORMULA_SYNTAX, + "syntax errors map to formula.syntax" + ); + assert_eq!( + err_kind("9 ** 2", FormulaErrorKind::Unsupported).code(), + codes::FORMULA_UNSUPPORTED + ); + assert_eq!( + err_kind("x = 0", FormulaErrorKind::FreeVariable).code(), + codes::FORMULA_FREE_VARIABLE + ); + assert_eq!( + err_kind( + &"(".repeat(limits::MAX_AST_DEPTH + 1), + FormulaErrorKind::Budget + ) + .code(), + codes::FORMULA_SYNTAX, + "budget errors share the formula.syntax code" + ); + } + + #[test] + fn parser_is_total_on_adversarial_fragments() { + let fragments = [ + "", + " ", + "\\", + "\\\\", + "(", + ")", + "()", + "(((((((((((", + "\\forall", + "\\forall x", + "\\forall x\\in", + "\\forall x\\in\\mathbb{Z}", + "\\forall x\\in\\mathbb{Z},", + "\\mathbb", + "\\mathbb{", + "\\mathbb{}", + "\\mathbb{Z", + "\\operatorname", + "\\operatorname{", + "\\operatorname{f", + "\\neg", + "\\neg\\neg\\neg", + "x", + "1", + "1=1\\land", + "1=1\\Rightarrow", + "^", + "^{}", + "x^", + "x^{", + "x^{}", + "$x$", + "x=y=z", + "\\frac", + "\\forall x\\in\\mathbb{Z}, \\quad", + "a b c", + "0x10", + ]; + for fragment in fragments { + // The contract is that `parse` returns a structured error, never panics. + let result = parse(fragment, Span::new(0, fragment.len())); + assert!( + result.is_err(), + "adversarial fragment `{fragment}` should not parse" + ); + } + // Random-ish byte prefixes of a valid formula must also be total. + let valid = FIXTURE_ADD; + for end in 0..=valid.len() { + let _ = parse(&valid[..end], Span::new(0, end)); + } + } +} diff --git a/src/lean.rs b/src/lean.rs index 4183f7e..2cd43aa 100644 --- a/src/lean.rs +++ b/src/lean.rs @@ -1 +1,1212 @@ //! Fixed Lean 4 + Mathlib backend invocation and trusted source generation. +//! +//! This module has two strictly separated halves, mirroring the specification: +//! +//! * **search** — generates a small Lean module from the internal typed AST +//! (never from raw document text), runs the fixed bounded tactic template and +//! exports the resulting proof term closure with the stock `leanexport` tool; +//! * **verify** — replays a payload without importing any proof `.olean`: +//! the toolchain's independent checker (`con-leche --verified`) kernel-replays +//! every declaration, the bundled `marqdo-replay` binary checks that the +//! target theorem's type is alpha-equivalent to the *independently +//! regenerated* expected proposition and that the axiom closure stays inside +//! the fixed base axioms. +//! +//! The environment is pinned by `lean/lean-toolchain` and +//! `lean/lake-manifest.json`; there is no floating version, no runtime download +//! and no second proof language. + +use std::collections::BTreeMap; +use std::io::Read; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::time::{Duration, Instant}; + +use serde::Deserialize; + +use crate::certificate::EnvironmentIdentity; +use crate::{codes, sha256_hex, Failure, Result}; + +/// One generated program-model module. +#[derive(Clone, Debug)] +pub struct ModelSource { + /// Lean module name, e.g. `MarqdoProof.Generated.Model_ab12`. + pub module_name: String, + /// Lean declaration name, e.g. `marqdoModel_ab12`. + pub lean_name: String, + /// Full module source (header + imports + `public def`). + pub source: String, + /// Content identity for cache/shape checks. + pub key: String, +} + +/// One proof attempt generated by the orchestration layer. +#[derive(Clone, Debug)] +pub struct ProofAttempt { + /// Content key of the target theorem (20 lowercase hex). + pub key: String, + /// Lean source of the proposition, e.g. `∀ mqx0 : Int, ...`. + pub statement_source: String, + /// Prove the negation instead (counterexample path). + pub refuted: bool, + /// Integer literals for the counterexample (one list entry per variable). + pub witnesses: Vec, + pub model_sources: Vec, + /// Artifact module names to import (verified dependency theorems). + pub imports: Vec, + /// Candidate theorem constants for the link stage. + pub dependency_names: Vec, + /// Ground/unconditional dependency applications for `nlinarith` hints. + pub hint_terms: Vec, + /// Internal variable names `mqx0`, `mqx1`, ... in binder order. + pub variable_names: Vec, +} + +/// Evidence returned by the independent verifier for one payload. +#[derive(Clone, Debug)] +pub struct Evidence { + pub payload: Vec, + pub payload_sha256: String, + pub axioms: Vec, + pub used_project_decls: Vec, + pub project_decls: Vec, +} + +/// Result of one bounded proof attempt. +pub enum Attempt { + /// The payload was produced and passed the independent verifier. + Proved(Evidence), + /// The fixed search strategy exhausted without a proof. Not an error. + Exhausted { detail: String }, +} + +/// Configuration of the fixed backend. +#[derive(Clone, Debug)] +pub struct LeanConfig { + pub lean_root: PathBuf, + pub toolchain_bin: PathBuf, + pub replay_bin: PathBuf, + pub timeout: Duration, +} + +/// Backend bound to one pinned Lean project. +pub struct LeanBackend { + config: LeanConfig, + gen_root: PathBuf, + build_lean_dir: PathBuf, + identity: EnvironmentIdentity, +} + +impl LeanBackend { + /// Discover and validate the fixed backend. + pub fn discover() -> Result { + let lean_root = discover_lean_root()?; + let toolchain_bin = discover_toolchain_bin(&lean_root)?; + let replay_bin = lean_root.join(".lake/build/bin/marqdo-replay"); + for tool in ["lean", "lake", "leanexport", "con-leche"] { + let path = toolchain_bin.join(tool); + if !path.is_file() { + return Err(Failure::new( + codes::BACKEND_UNAVAILABLE, + format!("fixed Lean backend tool `{}` is missing", path.display()), + ) + .with_hint( + "install the pinned Lean toolchain (see README) and set \ + MARQDO_PROVE_LEAN_BIN_DIR", + )); + } + } + for file in ["lean-toolchain", "lake-manifest.json", "lakefile.toml"] { + if !lean_root.join(file).is_file() { + return Err(Failure::new( + codes::BACKEND_UNAVAILABLE, + format!( + "`{}` is not a pinned Lean backend project: `{file}` is missing", + lean_root.display() + ), + )); + } + } + let gen_root = lean_root.join(".marqdo-gen"); + std::fs::create_dir_all(gen_root.join("MarqdoProof/Generated")).map_err(|error| { + Failure::new( + codes::BACKEND_UNAVAILABLE, + format!("cannot create generated-source directory: {error}"), + ) + })?; + let build_lean_dir = lean_root.join(".lake/build/lib/lean"); + std::fs::create_dir_all(build_lean_dir.join("MarqdoProof/Generated")).map_err(|error| { + Failure::new( + codes::BACKEND_UNAVAILABLE, + format!("cannot create Lean build directory: {error}"), + ) + })?; + let mut backend = LeanBackend { + config: LeanConfig { + lean_root, + toolchain_bin, + replay_bin, + timeout: Duration::from_secs(crate::limits::PROOF_WALL_SECS), + }, + gen_root, + build_lean_dir, + identity: empty_environment_identity(), + }; + backend.ensure_replay_binary()?; + backend.identity = backend.compute_identity()?; + Ok(backend) + } + + pub fn config(&self) -> &LeanConfig { + &self.config + } + + pub fn identity(&self) -> &EnvironmentIdentity { + &self.identity + } + + /// Build the fixed verifier executable once if it is not built yet. + fn ensure_replay_binary(&mut self) -> Result<()> { + if self.config.replay_bin.is_file() { + return Ok(()); + } + let mut command = self.lake_command()?; + command.args(["build", "marqdo-replay"]); + let output = self.run(command, Duration::from_secs(900), "lake build marqdo-replay")?; + if !output.status_success { + return Err(Failure::new( + codes::BACKEND_UNAVAILABLE, + format!( + "cannot build the fixed verifier: {}", + tail(&output.stderr) + ), + )); + } + if !self.config.replay_bin.is_file() { + return Err(Failure::new( + codes::BACKEND_UNAVAILABLE, + "`lake build marqdo-replay` succeeded but produced no verifier binary", + )); + } + Ok(()) + } + + fn compute_identity(&self) -> Result { + let lean_root = &self.config.lean_root; + let toolchain = std::fs::read_to_string(lean_root.join("lean-toolchain")).map_err(|error| { + Failure::new( + codes::BACKEND_UNAVAILABLE, + format!("cannot read lean-toolchain: {error}"), + ) + })?; + let manifest_bytes = std::fs::read(lean_root.join("lake-manifest.json")).map_err(|error| { + Failure::new( + codes::BACKEND_UNAVAILABLE, + format!("cannot read lake-manifest.json: {error}"), + ) + })?; + let manifest: LakeManifest = serde_json::from_slice(&manifest_bytes).map_err(|error| { + Failure::new( + codes::BACKEND_UNAVAILABLE, + format!("lake-manifest.json is not the expected pinned shape: {error}"), + ) + })?; + let mathlib_rev = manifest + .packages + .iter() + .find(|package| package.name == "mathlib") + .map(|package| package.rev.clone()) + .unwrap_or_default(); + let version = self.run_capture( + { + let mut command = Command::new(self.config.toolchain_bin.join("lean")); + command.arg("--version"); + command + }, + Duration::from_secs(30), + )?; + let lean_version = parse_lean_version(&version.stdout).ok_or_else(|| { + Failure::new( + codes::BACKEND_UNAVAILABLE, + format!("unexpected `lean --version` output: {}", tail(&version.stdout)), + ) + })?; + let replay_digest = sha256_file(&self.config.replay_bin)?; + let con_leche = self.config.toolchain_bin.join("con-leche"); + let con_leche_digest = sha256_file(&con_leche)?; + let lean_digest = sha256_file(&self.config.toolchain_bin.join("lean"))?; + let mut identity = EnvironmentIdentity { + lean_toolchain: toolchain.trim().to_string(), + lean_version, + mathlib_rev, + lake_manifest_digest: sha256_hex(&manifest_bytes), + replay_verifier_digest: replay_digest, + con_leche_version: format!("con-leche-{}", &con_leche_digest[..16]), + formula_compiler: format!("{}-{}", crate::TOOL_NAME, env!("CARGO_PKG_VERSION")), + semantic_mapping: "marqdo-int-exact-v1".to_string(), + environment_id: String::new(), + }; + let material = format!( + "{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}", + identity.lean_toolchain, + identity.lean_version, + identity.mathlib_rev, + identity.lake_manifest_digest, + identity.replay_verifier_digest, + identity.con_leche_version, + identity.formula_compiler, + identity.semantic_mapping, + lean_digest + ); + identity.environment_id = sha256_hex(material.as_bytes()); + Ok(identity) + } + + /// Compile one generated model module (content addressed by module name). + pub fn ensure_model_module(&self, model: &ModelSource) -> Result<()> { + let olean = self.olean_path(&model.module_name); + if olean.is_file() { + return Ok(()); + } + let source = self.write_generated(&model.module_name, &model.source)?; + self.compile_generated(&model.module_name, &source) + } + + /// Run one bounded proof attempt through search + independent verification. + pub fn attempt_proof(&self, attempt: &ProofAttempt) -> Result { + for model in &attempt.model_sources { + self.ensure_model_module(model)?; + } + let target_module = format!( + "MarqdoProof.Generated.{}_{}", + if attempt.refuted { "Refute" } else { "Target" }, + attempt.key + ); + let expected_module = format!("MarqdoProof.Generated.Expected_{}", attempt.key); + let theorem_name = format!("marqdoTarget_{}", attempt.key); + let expected_name = format!("marqdoExpected_{}", attempt.key); + let target_source = render_target_module( + &target_module, + &theorem_name, + &attempt.statement_source, + attempt, + ); + let expected_source = render_expected_module( + &expected_module, + &expected_name, + &attempt.statement_source, + attempt, + ); + // Step 1: independently elaborate the expected proposition first. This + // module contains no proof and never comes from the search process. If + // it does not compile, the trusted frontend (or a model definition) is + // broken: that is an engineering error, not an exhausted search. + let expected_path = self.write_generated(&expected_module, &expected_source)?; + if let Err(failure) = self.compile_generated(&expected_module, &expected_path) { + let _ = std::fs::remove_file(&expected_path); + return Err(failure); + } + let _ = std::fs::remove_file(&expected_path); + // Step 2: elaborate the search module. The statement is known to be + // well-formed, so a failure here is the bounded strategy exhausting. + let target_path = self.write_generated(&target_module, &target_source)?; + let compile = self.compile_generated_raw(&target_module, &target_path); + if let Err(failure) = compile { + let detail = failure.message.clone(); + if std::env::var_os("MARQDO_PROVE_KEEP_GENERATED").is_some() { + eprintln!("marqdo-prove: kept failed generated module {}", target_path.display()); + } else { + let _ = std::fs::remove_file(&target_path); + } + return Ok(Attempt::Exhausted { + detail: strategy_detail(&detail), + }); + } + let _ = std::fs::remove_file(&target_path); + // Step 3: export the proof term closure and the expected proposition. + let payload = self.export_module(&target_module, &theorem_name)?; + let expected = self.export_module(&expected_module, &expected_name)?; + // Step 4: independent kernel replay of the payload. + let work = self.config.lean_root.join(".marqdo-gen/work"); + std::fs::create_dir_all(&work).map_err(|error| { + Failure::new( + codes::BACKEND_UNAVAILABLE, + format!("cannot create verifier work directory: {error}"), + ) + })?; + let unique = format!("{}-{}", std::process::id(), attempt.key); + let payload_path = work.join(format!("{unique}.proof.ndjson")); + let expected_path = work.join(format!("{unique}.expected.ndjson")); + std::fs::write(&payload_path, &payload).map_err(|error| { + Failure::new( + codes::BACKEND_UNAVAILABLE, + format!("cannot stage proof payload: {error}"), + ) + })?; + std::fs::write(&expected_path, &expected).map_err(|error| { + Failure::new( + codes::BACKEND_UNAVAILABLE, + format!("cannot stage expected proposition: {error}"), + ) + })?; + let verified = self.verify_staged(&payload_path, &expected_path, &theorem_name, &expected_name); + let _ = std::fs::remove_file(&payload_path); + let _ = std::fs::remove_file(&expected_path); + let evidence = verified?; + Ok(Attempt::Proved(Evidence { + payload, + payload_sha256: sha256_hex(&evidence.payload), + axioms: evidence.axioms, + used_project_decls: evidence.used_project_decls, + project_decls: evidence.project_decls, + })) + } + + /// Verify a payload against a freshly regenerated expected proposition. + /// + /// This is the replay path: it never runs proof search, never imports the + /// payload's `.olean`, and accepts only a kernel-replayed proof whose type + /// matches the expected proposition. + pub fn verify_payload( + &self, + key: &str, + statement_source: &str, + refuted: bool, + model_sources: &[ModelSource], + payload: &[u8], + theorem_name: &str, + expected_name: &str, + ) -> Result { + for model in model_sources { + self.ensure_model_module(model)?; + } + let mut imports = Vec::new(); + for model in model_sources { + imports.push(model.module_name.clone()); + } + let attempt = ProofAttempt { + key: key.to_string(), + statement_source: statement_source.to_string(), + refuted, + witnesses: Vec::new(), + model_sources: model_sources.to_vec(), + imports, + dependency_names: Vec::new(), + hint_terms: Vec::new(), + variable_names: Vec::new(), + }; + let expected_module = format!("MarqdoProof.Generated.Expected_{}", key); + let expected_source = + render_expected_module(&expected_module, expected_name, statement_source, &attempt); + let expected_path = self.write_generated(&expected_module, &expected_source)?; + if let Err(failure) = self.compile_generated(&expected_module, &expected_path) { + let _ = std::fs::remove_file(&expected_path); + return Err(failure); + } + let _ = std::fs::remove_file(&expected_path); + let expected = self.export_module(&expected_module, expected_name)?; + let work = self.config.lean_root.join(".marqdo-gen/work"); + std::fs::create_dir_all(&work).map_err(|error| { + Failure::new( + codes::BACKEND_UNAVAILABLE, + format!("cannot create verifier work directory: {error}"), + ) + })?; + let unique = format!("{}-{}-replay", std::process::id(), key); + let payload_path = work.join(format!("{unique}.proof.ndjson")); + let expected_path = work.join(format!("{unique}.expected.ndjson")); + std::fs::write(&payload_path, payload).map_err(|error| { + Failure::new( + codes::BACKEND_UNAVAILABLE, + format!("cannot stage proof payload: {error}"), + ) + })?; + std::fs::write(&expected_path, &expected).map_err(|error| { + Failure::new( + codes::BACKEND_UNAVAILABLE, + format!("cannot stage expected proposition: {error}"), + ) + })?; + let evidence = self.verify_staged(&payload_path, &expected_path, theorem_name, expected_name); + let _ = std::fs::remove_file(&payload_path); + let _ = std::fs::remove_file(&expected_path); + let evidence = evidence?; + Ok(Evidence { + payload_sha256: sha256_hex(payload), + payload: payload.to_vec(), + axioms: evidence.axioms, + used_project_decls: evidence.used_project_decls, + project_decls: evidence.project_decls, + }) + } + + fn verify_staged( + &self, + payload_path: &Path, + expected_path: &Path, + theorem_name: &str, + expected_name: &str, + ) -> Result { + // Independent checker: kernel-replays every declaration of the closure. + let mut checker = Command::new(self.config.toolchain_bin.join("con-leche")); + checker + .arg("--verified") + .arg(payload_path) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .env_clear(); + copy_path_env(&mut checker); + configure_process_group(&mut checker); + let output = self.run(checker, Duration::from_secs(180), "con-leche replay")?; + if !output.status_success { + return Err(Failure::new( + codes::PROOF_REPLAY_FAILED, + format!("independent kernel replay rejected the payload: {}", tail(&output.stderr)), + )); + } + // Statement/axiom verifier. + let mut replay = Command::new(&self.config.replay_bin); + replay + .arg(payload_path) + .arg(expected_path) + .arg(theorem_name) + .arg(expected_name) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .env_clear(); + copy_path_env(&mut replay); + configure_process_group(&mut replay); + let output = self.run(replay, Duration::from_secs(120), "marqdo-replay")?; + if !output.status_success { + return Err(Failure::new( + codes::PROOF_TARGET_MISMATCH, + format!( + "independent statement/axiom verification rejected the payload: {}", + tail(&output.stderr) + ), + )); + } + let report_text = String::from_utf8_lossy(&output.stdout).trim().to_string(); + let report: ReplayReport = serde_json::from_str(&report_text).map_err(|error| { + Failure::new( + codes::PROOF_REPLAY_FAILED, + format!("verifier produced an unreadable report: {error}: {}", tail(&output.stdout)), + ) + })?; + if !report.ok { + return Err(Failure::new( + codes::PROOF_TARGET_MISMATCH, + format!("verifier rejected the payload: {}", report.reason), + )); + } + let mut axioms = report.axioms; + axioms.sort(); + axioms.dedup(); + for axiom in &axioms { + if !crate::certificate::ALLOWED_AXIOMS.contains(&axiom.as_str()) { + return Err(Failure::new( + codes::PROOF_UNTRUSTED_AXIOM, + format!("payload depends on untrusted axiom `{axiom}`"), + )); + } + } + let mut used = report.used; + used.sort(); + used.dedup(); + let mut project = report.project_decls; + project.sort(); + project.dedup(); + Ok(Evidence { + payload: std::fs::read(payload_path).map_err(|error| { + Failure::new( + codes::PROOF_REPLAY_FAILED, + format!("cannot read staged payload: {error}"), + ) + })?, + payload_sha256: String::new(), + axioms, + used_project_decls: used, + project_decls: project, + }) + } + + /// Path of a compiled artifact module inside the pinned build directory. + pub fn build_olean_path(&self, module_name: &str) -> PathBuf { + self.olean_path(module_name) + } + + /// Copy a cached artifact `.olean` into the pinned build directory so a + /// later search can import the already verified theorem. + pub fn install_olean(&self, module_name: &str, bytes: &[u8]) -> Result<()> { + let path = self.olean_path(module_name); + if path.is_file() { + return Ok(()); + } + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).map_err(|error| { + Failure::new( + codes::BACKEND_UNAVAILABLE, + format!("cannot create artifact directory: {error}"), + ) + })?; + } + std::fs::write(&path, bytes).map_err(|error| { + Failure::new( + codes::BACKEND_UNAVAILABLE, + format!("cannot install cached artifact olean: {error}"), + ) + }) + } + + /// Read a compiled artifact `.olean` produced by the last search. + pub fn read_olean(&self, module_name: &str) -> Result> { + std::fs::read(self.olean_path(module_name)).map_err(|error| { + Failure::new( + codes::BACKEND_UNAVAILABLE, + format!("cannot read compiled artifact `{module_name}`: {error}"), + ) + }) + } + + fn olean_path(&self, module_name: &str) -> PathBuf { + let relative = module_name.replace('.', "/"); + self.build_lean_dir.join(format!("{relative}.olean")) + } + + fn write_generated(&self, module_name: &str, source: &str) -> Result { + let relative = module_name.replace('.', "/"); + let path = self.gen_root.join(format!("{relative}.lean")); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).map_err(|error| { + Failure::new( + codes::BACKEND_UNAVAILABLE, + format!("cannot create generated-source directory: {error}"), + ) + })?; + } + std::fs::write(&path, source).map_err(|error| { + Failure::new( + codes::BACKEND_UNAVAILABLE, + format!("cannot write generated Lean source `{}`: {error}", path.display()), + ) + })?; + Ok(path) + } + + fn compile_generated(&self, module_name: &str, source_path: &Path) -> Result<()> { + let olean = self.olean_path(module_name); + let mut command = self.lake_env_command()?; + command + .arg("lean") + .arg("-R") + .arg(&self.gen_root) + .arg("-o") + .arg(&olean) + .arg(source_path); + let output = self.run(command, self.config.timeout, "lean compile")?; + if !output.status_success { + return Err(Failure::new( + codes::BACKEND_UNAVAILABLE, + format!( + "Lean elaboration failed for generated module `{module_name}`: {}", + tail(&output.stderr) + ), + )); + } + Ok(()) + } + + /// Compile and return the raw failure on strategy exhaustion so the caller + /// can distinguish `MARQDO_SEARCH_FAILED` from backend errors. + fn compile_generated_raw(&self, module_name: &str, source_path: &Path) -> Result<()> { + self.compile_generated(module_name, source_path) + } + + fn export_module(&self, module_name: &str, constant: &str) -> Result> { + let mut command = self.lake_env_command()?; + command + .arg("leanexport") + .arg(module_name) + .arg("--") + .arg(constant); + let output = self.run(command, Duration::from_secs(120), "leanexport")?; + if !output.status_success { + return Err(Failure::new( + codes::BACKEND_UNAVAILABLE, + format!( + "toolchain proof export failed for `{module_name}`: {}", + tail(&output.stderr) + ), + )); + } + if output.stdout.is_empty() { + return Err(Failure::new( + codes::BACKEND_UNAVAILABLE, + "toolchain proof export produced an empty payload", + )); + } + if output.stdout.len() as u64 > crate::limits::MAX_PROOF_BYTES { + return Err(Failure::new( + codes::PROOF_BUDGET, + format!( + "proof export is {} bytes, above the {} byte limit", + output.stdout.len(), + crate::limits::MAX_PROOF_BYTES + ), + )); + } + Ok(output.stdout) + } + + fn lake_command(&self) -> Result { + let mut command = Command::new(self.config.toolchain_bin.join("lake")); + command + .current_dir(&self.config.lean_root) + .stdin(Stdio::null()) + .env_clear(); + self.apply_environment(&mut command); + Ok(command) + } + + fn lake_env_command(&self) -> Result { + let mut command = Command::new(self.config.toolchain_bin.join("lake")); + command + .arg("env") + .current_dir(&self.config.lean_root) + .stdin(Stdio::null()) + .env_clear(); + self.apply_environment(&mut command); + Ok(command) + } + + fn apply_environment(&self, command: &mut Command) { + let mut path = self.config.toolchain_bin.display().to_string(); + if let Some(existing) = std::env::var_os("PATH") { + path.push(':'); + path.push_str(&existing.to_string_lossy()); + } + command.env("PATH", path); + command.env("LANG", "C.UTF-8"); + command.env("LC_ALL", "C.UTF-8"); + command.env("HOME", self.config.lean_root.join(".marqdo-gen/home")); + let _ = std::fs::create_dir_all(self.config.lean_root.join(".marqdo-gen/home")); + } + + fn run(&self, mut command: Command, timeout: Duration, label: &str) -> Result { + command + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + configure_process_group(&mut command); + let mut child = command.spawn().map_err(|error| { + Failure::new( + codes::BACKEND_UNAVAILABLE, + format!("cannot spawn `{label}`: {error}"), + ) + })?; + let stdout_reader = spawn_pipe_reader(child.stdout.take()); + let stderr_reader = spawn_pipe_reader(child.stderr.take()); + let deadline = Instant::now() + timeout; + let status = loop { + match child.try_wait() { + Ok(Some(status)) => break status, + Ok(None) => { + if Instant::now() >= deadline { + kill_process_group(child.id()); + let _ = child.kill(); + let _ = child.wait(); + return Err(Failure::new( + codes::PROOF_BUDGET, + format!("`{label}` exceeded its {}s budget", timeout.as_secs()), + )); + } + std::thread::sleep(Duration::from_millis(5)); + } + Err(error) => { + return Err(Failure::new( + codes::BACKEND_UNAVAILABLE, + format!("cannot wait for `{label}`: {error}"), + )) + } + } + }; + Ok(OutputStreams { + status_success: status.success(), + status: status.to_string(), + stdout: join_pipe_reader(stdout_reader), + stderr: join_pipe_reader(stderr_reader), + }) + } + + fn run_capture(&self, mut command: Command, timeout: Duration) -> Result { + command + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .env_clear(); + let mut owned = command.spawn().map_err(|error| { + Failure::new( + codes::BACKEND_UNAVAILABLE, + format!("cannot spawn backend probe: {error}"), + ) + })?; + let stdout_reader = spawn_pipe_reader(owned.stdout.take()); + let stderr_reader = spawn_pipe_reader(owned.stderr.take()); + let deadline = Instant::now() + timeout; + let status = loop { + match owned.try_wait() { + Ok(Some(status)) => break status, + Ok(None) => { + if Instant::now() >= deadline { + let _ = owned.kill(); + let _ = owned.wait(); + return Err(Failure::new( + codes::BACKEND_UNAVAILABLE, + "backend probe timed out", + )); + } + std::thread::sleep(Duration::from_millis(5)); + } + Err(error) => { + return Err(Failure::new( + codes::BACKEND_UNAVAILABLE, + format!("cannot wait for backend probe: {error}"), + )) + } + } + }; + Ok(OutputStreams { + status_success: status.success(), + status: status.to_string(), + stdout: join_pipe_reader(stdout_reader), + stderr: join_pipe_reader(stderr_reader), + }) + } +} + +struct OutputStreams { + status_success: bool, + #[allow(dead_code)] + status: String, + stdout: Vec, + #[allow(dead_code)] + stderr: Vec, +} + +#[derive(Deserialize)] +struct LakeManifest { + packages: Vec, +} + +#[derive(Deserialize)] +struct LakePackage { + name: String, + rev: String, +} + +#[derive(Deserialize)] +struct ReplayReport { + #[serde(default)] + ok: bool, + #[serde(default)] + reason: String, + #[serde(default)] + axioms: Vec, + #[serde(default)] + used: Vec, + #[serde(default)] + project_decls: Vec, +} + +fn empty_environment_identity() -> EnvironmentIdentity { + EnvironmentIdentity { + lean_toolchain: String::new(), + lean_version: String::new(), + mathlib_rev: String::new(), + lake_manifest_digest: String::new(), + replay_verifier_digest: String::new(), + con_leche_version: String::new(), + formula_compiler: String::new(), + semantic_mapping: String::new(), + environment_id: String::new(), + } +} + +fn render_target_module( + module_name: &str, + theorem_name: &str, + statement: &str, + attempt: &ProofAttempt, +) -> String { + let mut source = String::new(); + source.push_str("module\n\npublic import MarqdoProof.Basic\n"); + for model in &attempt.model_sources { + source.push_str(&format!("public import {}\n", model.module_name)); + } + for import in &attempt.imports { + source.push_str(&format!("public import {import}\n")); + } + source.push_str("\nset_option maxHeartbeats 1600000\n"); + source.push_str("set_option linter.unusedTactic false\n"); + source.push_str("set_option linter.unreachableTactic false\n\n"); + if attempt.refuted { + source.push_str(&format!( + "public theorem {theorem_name} : ¬ ({statement}) := by\n" + )); + source.push_str(" intro hypothesis\n"); + if !attempt.witnesses.is_empty() { + source.push_str(&format!( + " have counterexample := hypothesis {}\n", + attempt + .witnesses + .iter() + .map(|witness| format!("({witness} : Int)")) + .collect::>() + .join(" ") + )); + if !attempt.model_sources.is_empty() { + source.push_str(&format!( + " simp only [{}] at counterexample ⊢\n", + model_names(attempt).join(", ") + )); + } + source.push_str(" exact absurd counterexample (by decide)\n"); + } else { + if !attempt.model_sources.is_empty() { + source.push_str(&format!( + " simp only [{}] at hypothesis ⊢\n", + model_names(attempt).join(", ") + )); + } + source.push_str(" exact absurd hypothesis (by decide)\n"); + } + } else { + source.push_str(&format!("public theorem {theorem_name} : {statement} := by\n")); + if !attempt.variable_names.is_empty() { + source.push_str(&format!( + " intros {}\n", + attempt.variable_names.join(" ") + )); + } + source.push_str(" intros\n"); + if !attempt.model_sources.is_empty() { + source.push_str(&format!(" unfold {}\n", model_names(attempt).join(" "))); + } + source.push_str(" first\n"); + if !attempt.dependency_names.is_empty() { + source.push_str(&format!( + " | solve_by_elim [{}]\n", + attempt.dependency_names.join(", ") + )); + } + source.push_str(" | omega\n"); + source.push_str(" | positivity\n"); + source.push_str(" | decide\n"); + if attempt.hint_terms.is_empty() { + source.push_str(" | nlinarith\n"); + } else { + source.push_str(&format!( + " | nlinarith [{}]\n", + attempt.hint_terms.join(", ") + )); + } + } + let _ = module_name; + source +} + +fn render_expected_module( + module_name: &str, + expected_name: &str, + statement: &str, + attempt: &ProofAttempt, +) -> String { + let mut source = String::new(); + source.push_str("module\n\npublic import MarqdoProof.Basic\n"); + for model in &attempt.model_sources { + source.push_str(&format!("public import {}\n", model.module_name)); + } + source.push('\n'); + if attempt.refuted { + source.push_str(&format!( + "public def {expected_name} : Prop := ¬ ({statement})\n" + )); + } else { + source.push_str(&format!("public def {expected_name} : Prop := {statement}\n")); + } + let _ = module_name; + source +} + +fn model_names(attempt: &ProofAttempt) -> Vec { + attempt + .model_sources + .iter() + .map(|model| model.lean_name.clone()) + .collect() +} + +fn discover_lean_root() -> Result { + let mut candidates: Vec = Vec::new(); + if let Some(value) = std::env::var_os("MARQDO_PROVE_LEAN_ROOT") { + candidates.push(PathBuf::from(value)); + } + if let Ok(exe) = std::env::current_exe() { + if let Some(directory) = exe.parent() { + candidates.push(directory.join("../lean")); + candidates.push(directory.join("lean")); + } + } + candidates.push(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("lean")); + candidates.push(PathBuf::from("lean")); + for candidate in candidates { + if let Ok(canonical) = std::fs::canonicalize(&candidate) { + if canonical.join("lakefile.toml").is_file() { + return Ok(canonical); + } + } + } + Err(Failure::new( + codes::BACKEND_UNAVAILABLE, + "cannot locate the pinned Lean backend project", + ) + .with_hint( + "run the repository setup (see README) or set MARQDO_PROVE_LEAN_ROOT to the `lean/` \ + project directory", + )) +} + +fn discover_toolchain_bin(lean_root: &Path) -> Result { + let mut candidates: Vec = Vec::new(); + if let Some(value) = std::env::var_os("MARQDO_PROVE_LEAN_BIN_DIR") { + candidates.push(PathBuf::from(value)); + } + if let Ok(exe) = std::env::current_exe() { + if let Some(directory) = exe.parent() { + candidates.push(directory.join("../backend/bin")); + candidates.push(directory.join("../lean-toolchain/bin")); + } + } + if let Some(parent) = lean_root.parent() { + candidates.push(parent.join(".tool/lean/bin")); + } + candidates.push(lean_root.join(".tool/lean/bin")); + for candidate in candidates { + if candidate.join("lean").is_file() && candidate.join("lake").is_file() { + return Ok(candidate); + } + } + Err(Failure::new( + codes::BACKEND_UNAVAILABLE, + "cannot locate the pinned Lean toolchain binaries", + ) + .with_hint( + "install the pinned toolchain and set MARQDO_PROVE_LEAN_BIN_DIR to its `bin` directory; \ + no runtime download is attempted", + )) +} + +fn parse_lean_version(stdout: &[u8]) -> Option { + let text = String::from_utf8_lossy(stdout); + let version = text.split_whitespace().nth(3).unwrap_or_default(); + if version.is_empty() { + None + } else { + Some(version.trim_matches(|c: char| !c.is_ascii_digit() && c != '.').to_string()) + } +} + +fn sha256_file(path: &Path) -> Result { + let bytes = std::fs::read(path).map_err(|error| { + Failure::new( + codes::BACKEND_UNAVAILABLE, + format!("cannot read backend file `{}`: {error}", path.display()), + ) + })?; + Ok(sha256_hex(&bytes)) +} + +type PipeReader = std::thread::JoinHandle>; + +fn spawn_pipe_reader(pipe: Option) -> Option { + pipe.map(|mut pipe| { + std::thread::spawn(move || { + let mut buffer = Vec::new(); + let _ = pipe.by_ref().take(64 * 1024 * 1024).read_to_end(&mut buffer); + buffer + }) + }) +} + +fn join_pipe_reader(reader: Option) -> Vec { + match reader { + Some(handle) => handle.join().unwrap_or_default(), + None => Vec::new(), + } +} + +fn copy_path_env(command: &mut Command) { + if let Some(path) = std::env::var_os("PATH") { + command.env("PATH", path); + } + command.env("LANG", "C.UTF-8").env("LC_ALL", "C.UTF-8"); +} + +fn configure_process_group(command: &mut Command) { + #[cfg(unix)] + { + use std::os::unix::process::CommandExt; + unsafe { + command.pre_exec(|| { + libc::setsid(); + // Address-space caps are not usable with this backend: Lean + // maps the pinned Mathlib olean closure and spawns worker + // threads, and a low `RLIMIT_AS` fails before elaboration (6 GiB + // and 9 GiB were measured failing, 12 GiB succeeded). Resource + // bounding is therefore the wall-clock budget below plus the + // fixed CPU cap; docs/STATUS.md records this measured limit. + let cpu = libc::rlimit { + rlim_cur: 300, + rlim_max: 300, + }; + libc::setrlimit(libc::RLIMIT_CPU, &cpu); + Ok(()) + }); + } + } + let _ = command; +} + +fn kill_process_group(pid: u32) { + #[cfg(unix)] + unsafe { + libc::kill(-(pid as i32), libc::SIGKILL); + } + let _ = pid; +} + +fn tail(bytes: &[u8]) -> String { + let text = String::from_utf8_lossy(bytes); + let trimmed = text.trim(); + let take = trimmed + .char_indices() + .rev() + .nth(1500) + .map(|(index, _)| index) + .unwrap_or(0); + trimmed[take..].to_string() +} + +fn strategy_detail(text: &str) -> String { + let mut detail = String::new(); + for line in text.lines().filter(|line| !line.trim().is_empty()).take(8) { + if !detail.is_empty() { + detail.push_str(" | "); + } + detail.push_str(line.trim()); + } + if detail.is_empty() { + detail = "bounded proof strategy failed".to_string(); + } + format!("bounded proof strategy exhausted: {detail}") +} + +/// Deterministic Lean integer literal source for a counterexample value. +pub fn lean_int_literal(value: &num_bigint::BigInt) -> String { + value.to_string() +} + +/// Order-independent helper for report rendering. +pub fn sorted_map_keys(map: &BTreeMap) -> Vec { + map.keys().cloned().collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn generated_verified_module_has_fixed_template() { + let attempt = ProofAttempt { + key: "abc".to_string(), + statement_source: "∀ mqx0 : Int, (mqx0 ^ (2 : Nat)) ≥ (0 : Int)".to_string(), + refuted: false, + witnesses: vec![], + model_sources: vec![], + imports: vec!["MarqdoProof.Generated.Target_dep".to_string()], + dependency_names: vec!["marqdoTarget_dep".to_string()], + hint_terms: vec!["sq_nonneg mqx0".to_string()], + variable_names: vec!["mqx0".to_string()], + }; + let source = render_target_module("m", "marqdoTarget_abc", &attempt.statement_source, &attempt); + assert!(source.contains("public theorem marqdoTarget_abc : ∀ mqx0 : Int,")); + assert!(source.contains("public import MarqdoProof.Generated.Target_dep")); + assert!(source.contains("intros mqx0")); + assert!(source.contains("first\n")); + assert!(source.contains("solve_by_elim [marqdoTarget_dep]")); + assert!(source.contains("nlinarith [sq_nonneg mqx0]")); + assert!(!source.contains("sorry")); + assert!(!source.contains("axiom")); + } + + #[test] + fn generated_refuted_module_uses_concrete_witness() { + let attempt = ProofAttempt { + key: "abc".to_string(), + statement_source: "∀ mqx0 : Int, ...".to_string(), + refuted: true, + witnesses: vec!["0".to_string(), "-1".to_string()], + model_sources: vec![], + imports: vec![], + dependency_names: vec![], + hint_terms: vec![], + variable_names: vec!["mqx0".to_string(), "mqx1".to_string()], + }; + let source = render_target_module("m", "marqdoTarget_abc", &attempt.statement_source, &attempt); + assert!(source.contains("¬ (∀ mqx0 : Int, ...)")); + assert!(source.contains("have counterexample := hypothesis (0 : Int) (-1 : Int)")); + assert!(source.contains("exact absurd counterexample (by decide)")); + } + + #[test] + fn expected_module_has_no_proof() { + let attempt = ProofAttempt { + key: "abc".to_string(), + statement_source: "∀ mqx0 : Int, (mqx0 ^ (2 : Nat)) ≥ (0 : Int)".to_string(), + refuted: false, + witnesses: vec![], + model_sources: vec![], + imports: vec![], + dependency_names: vec![], + hint_terms: vec![], + variable_names: vec![], + }; + let source = render_expected_module("m", "marqdoExpected_abc", &attempt.statement_source, &attempt); + assert!(source.contains("public def marqdoExpected_abc : Prop :=")); + assert!(!source.contains("theorem")); + assert!(!source.contains("by ")); + } + + #[test] + fn model_names_are_extracted_from_generated_sources() { + let attempt = ProofAttempt { + key: "abc".to_string(), + statement_source: "True".to_string(), + refuted: false, + witnesses: vec![], + model_sources: vec![ModelSource { + module_name: "MarqdoProof.Generated.Model_x".to_string(), + lean_name: "marqdoModel_x".to_string(), + source: "module\n\npublic import MarqdoProof.Basic\n\npublic def marqdoModel_x (mqp0 : Int) : Int := mqp0\n".to_string(), + key: "x".to_string(), + }], + imports: vec![], + dependency_names: vec![], + hint_terms: vec![], + variable_names: vec![], + }; + assert_eq!(model_names(&attempt), vec!["marqdoModel_x".to_string()]); + } +} diff --git a/src/linker.rs b/src/linker.rs index 25a79fe..0578de9 100644 --- a/src/linker.rs +++ b/src/linker.rs @@ -1 +1,864 @@ //! Controlled multi-entry catalog, exact link resolution and dependency DAG. +//! +//! The linker is the only component that decides *which* local documents are +//! read besides the entry: every dependency link must resolve to a selected +//! Knowledge H2 (a theorem) or to an Exec H2 declaring a function (a program +//! model). It never guesses from names, never follows a link to an arbitrary +//! file, never leaves the explicit root, and never reads raw Markdown itself — +//! each new document is loaded through the real CLI's Analysis. +//! +//! Depth, breadth, file count and total source size are bounded. Cycles are +//! detected with the exact reference chain. + +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use crate::analysis::{ + AnalysisBackend, FragmentResolution, Function, ModuleData, Snapshot, Unit, +}; +use crate::document::{self, DependencyLink, Extraction, ProofUnit}; +use crate::{codes, Diagnostic, Failure, Span}; + +/// A selected dependency target. +#[derive(Clone)] +pub enum DependencyTarget { + /// Another selected Knowledge H2 that must itself be verified. + Theorem { + snapshot: Arc, + unit_id: String, + proof_unit: Box, + }, + /// An Exec H2 declaring a function used by formula model calls. + Model { + snapshot: Arc, + unit_id: String, + function: Box, + }, +} + +impl DependencyTarget { + pub fn kind_name(&self) -> &'static str { + match self { + DependencyTarget::Theorem { .. } => "theorem", + DependencyTarget::Model { .. } => "model", + } + } + + pub fn snapshot(&self) -> &Arc { + match self { + DependencyTarget::Theorem { snapshot, .. } | DependencyTarget::Model { snapshot, .. } => { + snapshot + } + } + } + + pub fn unit_id(&self) -> &str { + match self { + DependencyTarget::Theorem { unit_id, .. } | DependencyTarget::Model { unit_id, .. } => { + unit_id + } + } + } + + /// Portable locator: `relative_path#fragment-of-unit`. + pub fn locator(&self) -> String { + let fragment = match self { + DependencyTarget::Theorem { snapshot, unit_id, .. } + | DependencyTarget::Model { snapshot, unit_id, .. } => snapshot + .modules + .values() + .find_map(|module| module.unit(unit_id).map(|unit| (module, unit))) + .map(|(module, unit)| format!("{}#{}", module.relative_path, unit.name)) + .unwrap_or_else(|| unit_id.clone()), + }; + fragment + } +} + +/// One dependency link resolved to its exact target. +#[derive(Clone)] +pub struct ResolvedDependency { + pub link: DependencyLink, + pub target: DependencyTarget, +} + +/// One proof unit together with its document and resolved dependencies. +#[derive(Clone)] +pub struct LoadedUnit { + pub snapshot: Arc, + pub module: Arc, + pub proof_unit: ProofUnit, + pub dependencies: Vec, + /// Diagnostics raised while resolving this unit's declared links. A unit + /// with any diagnostic is never a candidate for verification. + pub diagnostics: Vec, +} + +impl LoadedUnit { + /// Stable in-run key: canonical physical path plus unit id. + pub fn internal_key(&self) -> (PathBuf, String) { + (self.snapshot.canonical_path.clone(), self.proof_unit.unit_id.clone()) + } +} + +/// The loaded dependency closure of one entry selection. +pub struct Closure { + pub root: PathBuf, + /// Units in dependency-first (topological) order. + pub units: Vec, + pub documents: BTreeMap>, + pub diagnostics: Vec, + /// Cycles as concrete reference chains. + pub cycles: Vec>, +} + +impl Closure { + pub fn unit(&self, path: &Path, unit_id: &str) -> Option<&LoadedUnit> { + self.units + .iter() + .find(|unit| unit.snapshot.canonical_path == path && unit.proof_unit.unit_id == unit_id) + } +} + +/// Multi-entry catalog bound to one controlled local root. +pub struct Linker { + backend: AnalysisBackend, + root: PathBuf, + documents: BTreeMap>, + extraction_cache: BTreeMap>, + stats: CatalogStats, +} + +#[derive(Default)] +struct CatalogStats { + documents: usize, + source_bytes: u64, +} + +/// Limits for one catalog walk. +#[derive(Clone, Copy, Debug)] +pub struct CatalogLimits { + pub documents: usize, + pub units: usize, + pub depth: usize, + pub source_bytes: u64, +} + +impl Default for CatalogLimits { + fn default() -> Self { + Self { + documents: crate::limits::MAX_DOCUMENTS, + units: crate::limits::MAX_UNITS, + depth: crate::limits::MAX_DEPTH, + source_bytes: crate::limits::MAX_SOURCE_BYTES, + } + } +} + +impl Linker { + pub fn new(backend: AnalysisBackend, root: PathBuf) -> Result { + let root = std::fs::canonicalize(&root).map_err(|error| { + Failure::new( + codes::LINK_OUTSIDE_ROOT, + format!("cannot canonicalize the controlled root `{}`: {error}", root.display()), + ) + })?; + Ok(Self { + backend, + root, + documents: BTreeMap::new(), + extraction_cache: BTreeMap::new(), + stats: CatalogStats::default(), + }) + } + + pub fn root(&self) -> &Path { + &self.root + } + + pub fn backend(&self) -> &AnalysisBackend { + &self.backend + } + + /// Load the entry document (or `--root`-bounded path). + pub fn load_document(&mut self, path: &Path) -> Result, Failure> { + let canonical = std::fs::canonicalize(path).map_err(|error| { + Failure::new( + codes::LINK_MISSING, + format!("cannot resolve document `{}`: {error}", path.display()), + ) + })?; + if !canonical.starts_with(&self.root) { + return Err(Failure::new( + codes::LINK_OUTSIDE_ROOT, + format!( + "document `{}` is outside the controlled root `{}`", + canonical.display(), + self.root.display() + ), + )); + } + if let Some(existing) = self.documents.get(&canonical) { + return Ok(existing.clone()); + } + let snapshot = self.backend.load(&canonical, &self.root)?; + self.stats.documents += 1; + self.stats.source_bytes += snapshot + .modules + .values() + .map(|module| module.source.len() as u64) + .sum::(); + if self.stats.documents > CatalogLimits::default().documents { + return Err(Failure::new( + codes::LINK_MISSING, + format!( + "catalog loaded more than {} documents", + CatalogLimits::default().documents + ), + )); + } + if self.stats.source_bytes > CatalogLimits::default().source_bytes { + return Err(Failure::new( + codes::LINK_MISSING, + format!( + "catalog source bytes exceed the {} byte budget", + CatalogLimits::default().source_bytes + ), + )); + } + self.documents.insert(canonical, snapshot.clone()); + Ok(snapshot) + } + + /// Extract proof units for one entry snapshot (public frontend for the + /// orchestration layer; results include invalid candidates). + pub fn extract_units(&mut self, snapshot: &Arc) -> Vec { + let path = snapshot.canonical_path.clone(); + let module = snapshot.entry().clone(); + document::extract(&module) + .into_iter() + .map(|extraction| { + if let Extraction::Invalid(diagnostic) = &extraction { + self.extraction_cache + .entry(path.clone()) + .or_default() + .insert(format!("invalid@{}", diagnostic.span.map(|s| s.start).unwrap_or(0)), extraction.clone()); + } + extraction + }) + .collect() + } + + /// Extract proof units for one loaded module, cached per document. + fn extraction(&mut self, module: &ModuleData, path: &Path) -> BTreeMap { + if let Some(cached) = self.extraction_cache.get(path) { + return cached.clone(); + } + let mut map = BTreeMap::new(); + for extraction in document::extract(module) { + let unit_id = match &extraction { + Extraction::Unit(unit) => unit.unit_id.clone(), + Extraction::Invalid(_) => continue, + }; + map.insert(unit_id, extraction); + } + self.extraction_cache.insert(path.to_path_buf(), map.clone()); + map + } + + /// Resolve the transitive dependency closure for the selected entry units. + /// + /// `selection` is the explicit list of entry unit ids (empty = every + /// extracted proof unit). Returns units in dependency-first order. + pub fn resolve_closure( + &mut self, + entry: &Arc, + selection: &[String], + ) -> Result { + let entry_path = entry.canonical_path.clone(); + let extraction = self.extraction(&entry.entry(), &entry_path); + let mut diagnostics: Vec = Vec::new(); + + // Selected entry units. + let mut roots: Vec = Vec::new(); + if selection.is_empty() { + for (unit_id, extraction) in &extraction { + match extraction { + Extraction::Unit(_) => roots.push(unit_id.clone()), + Extraction::Invalid(diagnostic) => diagnostics.push(diagnostic.clone()), + } + } + } else { + let available: BTreeSet<&String> = extraction.keys().collect(); + for unit_id in selection { + if available.contains(unit_id) { + roots.push(unit_id.clone()); + } else { + diagnostics.push(Diagnostic::error( + codes::DOCUMENT_UNIT, + format!("selected unit `{unit_id}` is not a valid proof unit of the entry"), + )); + } + } + } + + let mut loader = ClosureLoader { + linker: self, + documents: BTreeMap::new(), + units: HashMap::new(), + diagnostics, + depth: 0, + }; + loader.documents.insert(entry_path.clone(), entry.clone()); + for unit_id in roots { + loader.load_unit(entry.clone(), &unit_id, 0)?; + } + let ClosureLoader { + documents, + units, + mut diagnostics, + .. + } = loader; + let mut closure = Closure { + root: self.root.clone(), + units: Vec::new(), + documents, + diagnostics: Vec::new(), + cycles: Vec::new(), + }; + // Topological order with three-colour DFS over theorem dependencies. + let mut order: Vec<(PathBuf, String)> = Vec::new(); + let mut state: HashMap<(PathBuf, String), u8> = HashMap::new(); + let mut stack: Vec<(PathBuf, String)> = Vec::new(); + let keys: Vec<(PathBuf, String)> = units.keys().cloned().collect(); + // Deterministic start order: document path, then unit id. + let mut keys = keys; + keys.sort(); + for key in keys { + visit( + &units, + &key, + &mut state, + &mut order, + &mut stack, + &mut closure.cycles, + ); + } + let mut loaded: Vec = Vec::new(); + for key in order { + if let Some(unit) = units.get(&key) { + loaded.push(unit.clone()); + } + } + // Any unit not reached by the DFS (should not happen) is appended in a + // deterministic order rather than silently dropped. + let mut remaining: Vec<(PathBuf, String)> = units.keys().cloned().collect(); + remaining.sort(); + for key in remaining { + if !loaded.iter().any(|unit| unit.internal_key() == key) { + if let Some(unit) = units.get(&key) { + loaded.push(unit.clone()); + } + } + } + diagnostics.extend(std::mem::take(&mut closure.cycles).into_iter().map(|cycle| { + Diagnostic::error( + codes::LINK_CYCLE, + format!("dependency cycle: {}", cycle.join(" -> ")), + ) + .with_hint( + "remove the cycle; first-release knowledge is a DAG, mathematical induction is \ + not expressed through file dependencies", + ) + })); + closure.diagnostics.extend(diagnostics); + closure.units = loaded; + Ok(closure) + } + + /// Resolve one link in one loaded module. + fn resolve_link( + &mut self, + source_path: &Path, + source: &Arc, + module: &Arc, + link: &DependencyLink, + ) -> std::result::Result { + let reference = module + .references + .iter() + .find(|reference| reference.span == link.link_span) + .ok_or_else(|| { + Diagnostic::error( + codes::LINK_INVALID, + format!( + "link `{}` has no matching reference record in the current Analysis", + link.url + ), + ) + .at(link.link_span) + })?; + match reference.state.as_str() { + "resolved" => { + let target_module_id = reference.target_module.clone().ok_or_else(|| { + link_error(link, codes::LINK_INVALID, "resolved link has no target module") + })?; + let target_module = source.modules.get(&target_module_id).cloned().ok_or_else(|| { + link_error( + link, + codes::LINK_CONTEXT_CONFLICT, + format!("link target module `{target_module_id}` is not in the loaded snapshot"), + ) + })?; + let Some(target_unit_id) = reference.target_unit.clone() else { + return Err(link_error( + link, + codes::LINK_INVALID, + "dependency link must address a Knowledge H2 or Exec H2, not the document root", + )); + }; + let target = self.classify_target( + source.clone(), + target_module, + &target_unit_id, + link, + source_path, + )?; + Ok(ResolvedDependency { + link: link.clone(), + target, + }) + } + "not_loaded" => { + let candidate_path = reference.candidate_path.clone().ok_or_else(|| { + link_error(link, codes::LINK_INVALID, "local link has no package-relative path") + })?; + validate_relative_path(&candidate_path) + .map_err(|message| link_error(link, codes::LINK_INVALID, message))?; + if reference.candidate_package_instance_id.as_deref() + != Some(module.package_instance_id.as_str()) + { + return Err(link_error( + link, + codes::LINK_INVALID, + "cross-package dependency links are not supported in the first release; \ + provide a local document inside the controlled root", + )); + } + let physical = self.root.join(&candidate_path); + let snapshot = self.load_document(&physical).map_err(|failure| { + link_error(link, failure.code, failure.message) + })?; + let target_module = snapshot + .module_by_relative_path(&candidate_path) + .cloned() + .or_else(|| { + snapshot + .modules + .values() + .find(|candidate| candidate.relative_path == candidate_path) + .cloned() + }) + .ok_or_else(|| { + link_error( + link, + codes::LINK_CONTEXT_CONFLICT, + format!("loaded document `{candidate_path}` does not expose that module path"), + ) + })?; + // Verify context compatibility (same root, same lock/manifest). + if snapshot.project.identity_kind != source.project.identity_kind + || snapshot.project.lock_digest != source.project.lock_digest + || snapshot.project.manifest_digest != source.project.manifest_digest + { + return Err(link_error( + link, + codes::LINK_CONTEXT_CONFLICT, + format!( + "document `{candidate_path}` has an incompatible project context" + ), + )); + } + let fragment = reference.fragment.clone().unwrap_or_default(); + let target_unit_id = match target_module.resolve_fragment(&fragment) { + FragmentResolution::Unit(unit_id) => unit_id, + FragmentResolution::DocumentRoot => { + return Err(link_error( + link, + codes::LINK_INVALID, + "dependency link must include a non-empty heading fragment", + )) + } + FragmentResolution::Missing => { + return Err(link_error( + link, + codes::LINK_MISSING, + format!( + "`{candidate_path}` has no anchor or exact heading name `{fragment}`" + ), + )) + } + FragmentResolution::Ambiguous(candidates) => { + return Err(link_error( + link, + codes::LINK_AMBIGUOUS, + format!( + "fragment `{fragment}` in `{candidate_path}` matches multiple units: {}", + candidates.join(", ") + ), + )) + } + }; + let target_path = snapshot.canonical_path.clone(); + let target = self.classify_target( + snapshot, + target_module, + &target_unit_id, + link, + &target_path, + )?; + Ok(ResolvedDependency { + link: link.clone(), + target, + }) + } + "missing" => Err(link_error( + link, + codes::LINK_MISSING, + format!("dependency target `{}` does not exist", link.url), + )), + "ambiguous" => Err(link_error( + link, + codes::LINK_AMBIGUOUS, + format!( + "dependency target `{}` matches multiple exact headings: {}", + link.url, + reference.candidates.join(", ") + ), + )), + "outside_scope" => Err(link_error( + link, + codes::LINK_OUTSIDE_ROOT, + format!("dependency link `{}` escapes the controlled root", link.url), + )), + "invalid" => Err(link_error( + link, + codes::LINK_INVALID, + format!("dependency link `{}` is not a valid local document link", link.url), + )), + "external" => Err(link_error( + link, + codes::LINK_INVALID, + format!( + "dependency link `{}` is external; Prove never fetches remote knowledge", + link.url + ), + )), + other => Err(link_error( + link, + codes::LINK_INVALID, + format!("link has unknown Analysis state `{other}`"), + )), + } + } + + fn classify_target( + &mut self, + snapshot: Arc, + module: Arc, + target_unit_id: &str, + link: &DependencyLink, + target_path: &Path, + ) -> std::result::Result { + let unit = module.unit(target_unit_id).ok_or_else(|| { + link_error( + link, + codes::LINK_CONTEXT_CONFLICT, + format!("resolved target unit `{target_unit_id}` is not in the target module"), + ) + })?; + if unit.kind == "function" { + if unit.mode != "exec" || unit.level != 2 { + return Err(link_error( + link, + codes::LINK_INVALID, + format!("`{}` is an Exec section but not a function declaration", link.url), + )); + } + let function = module + .functions + .iter() + .find(|function| function.unit_id == unit.id) + .ok_or_else(|| { + link_error( + link, + codes::LINK_CONTEXT_CONFLICT, + format!("Exec H2 `{}` has no function record", link.url), + ) + })?; + return Ok(DependencyTarget::Model { + snapshot, + unit_id: unit.id.clone(), + function: Box::new(function.clone()), + }); + } + if unit.kind != "knowledge" || unit.level != 2 { + return Err(link_error( + link, + codes::LINK_INVALID, + format!( + "dependency link `{}` must select a Knowledge H2 (theorem) or an Exec H2 \ + (program model), not `{}`", + link.url, + unit.kind + ), + )); + } + let extraction = self.extraction(&module, target_path); + match extraction.get(&unit.id) { + Some(Extraction::Unit(proof_unit)) => Ok(DependencyTarget::Theorem { + snapshot, + unit_id: unit.id.clone(), + proof_unit: Box::new(proof_unit.clone()), + }), + Some(Extraction::Invalid(diagnostic)) => Err(Diagnostic { + severity: crate::Severity::Error, + code: diagnostic.code, + message: format!( + "dependency target `{}` is not a valid proof unit: {}", + link.url, diagnostic.message + ), + span: Some(link.link_span), + hint: diagnostic.hint.clone(), + }), + None => Err(link_error( + link, + codes::LINK_INVALID, + format!( + "dependency target `{}` is a Knowledge H2 without a direct `证明依赖` heading; \ + it is not a selected theorem", + link.url + ), + )), + } + } +} + +struct ClosureLoader<'a> { + linker: &'a mut Linker, + documents: BTreeMap>, + units: HashMap<(PathBuf, String), LoadedUnit>, + diagnostics: Vec, + depth: usize, +} + +impl<'a> ClosureLoader<'a> { + fn load_unit( + &mut self, + snapshot: Arc, + unit_id: &str, + depth: usize, + ) -> Result<(), Failure> { + let key = (snapshot.canonical_path.clone(), unit_id.to_string()); + if self.units.contains_key(&key) { + return Ok(()); + } + let limits = CatalogLimits::default(); + if depth > limits.depth { + self.diagnostics.push(Diagnostic::error( + codes::PROOF_BUDGET, + format!("dependency chain is deeper than {} levels", limits.depth), + )); + return Ok(()); + } + if self.units.len() >= limits.units { + self.diagnostics.push(Diagnostic::error( + codes::PROOF_BUDGET, + format!("catalog contains more than {} proof units", limits.units), + )); + return Ok(()); + } + let path = snapshot.canonical_path.clone(); + let module = snapshot.entry().clone(); + let extraction = self.linker.extraction(&module, &path); + let proof_unit = match extraction.get(unit_id) { + Some(Extraction::Unit(unit)) => unit.clone(), + Some(Extraction::Invalid(diagnostic)) => { + self.diagnostics.push(diagnostic.clone()); + return Ok(()); + } + None => { + self.diagnostics.push(Diagnostic::error( + codes::DOCUMENT_UNIT, + format!( + "unit `{unit_id}` is not a proof unit in `{}`", + module.relative_path + ), + )); + return Ok(()); + } + }; + // Reserve the slot before recursing so cycles terminate. + self.units.insert( + key.clone(), + LoadedUnit { + snapshot: snapshot.clone(), + module: module.clone(), + proof_unit: proof_unit.clone(), + dependencies: Vec::new(), + diagnostics: Vec::new(), + }, + ); + self.documents.insert(path.clone(), snapshot.clone()); + let mut resolved = Vec::new(); + let mut unit_diagnostics = Vec::new(); + for link in &proof_unit.dependencies.links { + match self + .linker + .resolve_link(&path, &snapshot, &module, link) + { + Ok(dependency) => { + let dependency_key = dependency.target.snapshot().canonical_path.clone(); + self.documents + .insert(dependency_key.clone(), dependency.target.snapshot().clone()); + let recurse = match &dependency.target { + DependencyTarget::Theorem { + snapshot: target_snapshot, + unit_id: target_unit_id, + .. + } => Some((target_snapshot.clone(), target_unit_id.clone())), + DependencyTarget::Model { .. } => None, + }; + resolved.push(dependency); + if let Some((target_snapshot, target_unit_id)) = recurse { + self.load_unit(target_snapshot, &target_unit_id, depth + 1)?; + } + } + Err(diagnostic) => { + self.diagnostics.push(diagnostic.clone()); + unit_diagnostics.push(diagnostic); + } + } + } + if let Some(entry) = self.units.get_mut(&key) { + entry.dependencies = resolved; + entry.diagnostics = unit_diagnostics; + } + Ok(()) + } +} + +fn visit( + units: &HashMap<(PathBuf, String), LoadedUnit>, + key: &(PathBuf, String), + state: &mut HashMap<(PathBuf, String), u8>, + order: &mut Vec<(PathBuf, String)>, + stack: &mut Vec<(PathBuf, String)>, + cycles: &mut Vec>, +) { + match state.get(key) { + Some(2) => return, + Some(1) => { + // Cycle: report the concrete chain from the first occurrence. + if let Some(position) = stack.iter().position(|candidate| candidate == key) { + let mut chain: Vec = stack[position..] + .iter() + .map(|(_, unit_id)| unit_id.clone()) + .collect(); + chain.push(key.1.clone()); + if !cycles.contains(&chain) { + cycles.push(chain); + } + } + return; + } + _ => {} + } + state.insert(key.clone(), 1); + stack.push(key.clone()); + if let Some(unit) = units.get(key) { + for dependency in &unit.dependencies { + if let DependencyTarget::Theorem { snapshot, unit_id, .. } = &dependency.target { + let child = (snapshot.canonical_path.clone(), unit_id.clone()); + visit(units, &child, state, order, stack, cycles); + } + } + } + stack.pop(); + state.insert(key.clone(), 2); + order.push(key.clone()); +} + +fn link_error(link: &DependencyLink, code: &'static str, message: impl Into) -> Diagnostic { + Diagnostic::error(code, message) + .at(link.link_span) + .with_hint("fix the dependency link so it points at exactly one selected unit inside the root") +} + +/// Validate one package-relative candidate path from an Analysis reference. +pub fn validate_relative_path(path: &str) -> std::result::Result<(), String> { + if path.is_empty() { + return Err("link target path is empty".to_string()); + } + if path.starts_with('/') || path.starts_with('\\') || path.contains('\\') { + return Err(format!("link target path `{path}` is absolute or uses a platform separator")); + } + if let Some((before, _)) = path.split_once(':') { + let scheme = before; + if !scheme.contains('/') + && (scheme.len() == 1 + || scheme + .chars() + .next() + .is_some_and(|first| first.is_ascii_alphabetic())) + { + return Err(format!( + "link target path `{path}` uses an absolute, drive or URI prefix" + )); + } + } + if path.len() > 4096 { + return Err("link target path is too long".to_string()); + } + if path.contains('\0') { + return Err("link target path contains a NUL byte".to_string()); + } + for segment in path.split('/') { + if segment.is_empty() || segment == "." || segment == ".." { + return Err(format!( + "link target path `{path}` contains an empty or traversal segment" + )); + } + } + Ok(()) +} + +/// Human-readable reference to a unit for diagnostics/reports. +pub fn display_unit(snapshot: &Snapshot, unit: &Unit) -> String { + format!("{}#{}", snapshot.relative_path, unit.path.join("/")) +} + +/// Source span of a unit's heading for diagnostics. +pub fn unit_span(unit: &Unit) -> Span { + unit.heading_span.unwrap_or(unit.span) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn relative_path_validation_rejects_unsafe_candidates() { + assert!(validate_relative_path("algebra.mq.md").is_ok()); + assert!(validate_relative_path("sub/notes.mq.md").is_ok()); + assert!(validate_relative_path("../outside.mq.md").is_err()); + assert!(validate_relative_path("sub/../x.mq.md").is_err()); + assert!(validate_relative_path("./x.mq.md").is_err()); + assert!(validate_relative_path("a//b.mq.md").is_err()); + assert!(validate_relative_path("/etc/passwd").is_err()); + assert!(validate_relative_path("C:/x.mq.md").is_err()); + assert!(validate_relative_path("x\\y.mq.md").is_err()); + assert!(validate_relative_path("x\u{0}y").is_err()); + } +} diff --git a/src/main.rs b/src/main.rs index c7ab35a..7497dfe 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,193 @@ //! `marqdo-prove` executable: argument handling, presentation and exit codes. +//! +//! Two business commands only: `check` and `replay`. `--help` / `--version` are +//! ordinary CLI metadata. No other sub-commands, compatibility flags or legacy +//! protocols exist. -fn main() { - std::process::exit(2); +use std::path::PathBuf; +use std::process::ExitCode; + +use marqdo_prove::prove::{self, CheckOptions, Invocation, ReplayOptions}; + +const USAGE: &str = "\ +marqdo-prove — static, link-driven mathematical proof checking for Marqdo documents + +USAGE: + marqdo-prove check ENTRY [--unit FRAGMENT] [--root DIR] [--out PATH] [--json] + marqdo-prove replay ENTRY BUNDLE [--root DIR] [--json] + marqdo-prove --version + marqdo-prove --help + +CHECK + Extract every selected Knowledge H2 proof unit of ENTRY, load declared + local theorem/program-model dependencies, prove the bounded integer + propositions on the fixed Lean 4 + Mathlib backend, verify through an + independent replay path and publish content-addressed proof bundles. + + --unit FRAGMENT only the exact anchor/heading name FRAGMENT of ENTRY + --root DIR explicit controlled local document root (must contain ENTRY) + --out PATH export a verified proof bundle to PATH + --json machine-readable single JSON object on stdout + +REPLAY + Re-verify a saved proof bundle against the current sources and the fixed + environment without running proof search, without network access and + without trusting any stored `.olean`. + +EXIT CODES + 0 every requested target was verified (or there was no target) + 1 at least one requested target was not verified (refuted/unknown/ + unsupported/invalid/blocked/stale) + 2 engineering failure, command line error, upstream contract or backend + unavailable +"; + +fn main() -> ExitCode { + let args: Vec = std::env::args().skip(1).collect(); + let exit = match run(&args) { + Ok(code) => code, + Err(message) => { + eprintln!("error: {message}"); + eprintln!(); + eprintln!("{USAGE}"); + return ExitCode::from(2); + } + }; + ExitCode::from(exit) +} + +fn run(args: &[String]) -> Result { + let Some(command) = args.first() else { + return Err("missing command".to_string()); + }; + match command.as_str() { + "--version" | "-V" => { + println!("{} {}", marqdo_prove::TOOL_NAME, env!("CARGO_PKG_VERSION")); + Ok(0) + } + "--help" | "-h" | "help" => { + print!("{USAGE}"); + Ok(0) + } + "check" => { + let options = parse_check(&args[1..])?; + let json = options.json; + let report = prove::run(Invocation::Check(options)); + Ok(emit(report, json)) + } + "replay" => { + let options = parse_replay(&args[1..])?; + let json = options.json; + let report = prove::run(Invocation::Replay(options)); + Ok(emit(report, json)) + } + other => Err(format!("unknown command `{other}`")), + } +} + +fn emit(report: prove::Report, json: bool) -> u8 { + let status = report.status(); + if json { + match serde_json::to_string(&report) { + Ok(text) => println!("{text}"), + Err(error) => { + eprintln!("error: cannot serialize the result report: {error}"); + return 2; + } + } + } else { + print!("{}", report.render_text()); + // Diagnostics are already part of the textual rendering; progress and + // engineering detail stay on stderr without polluting JSON stdout. + for diagnostic in &report.diagnostics { + eprintln!( + "{} [{}] {}", + diagnostic.severity, diagnostic.code, diagnostic.message + ); + } + } + status.exit_code() as u8 +} + +fn parse_check(args: &[String]) -> Result { + let mut entry: Option = None; + let mut unit = None; + let mut root = None; + let mut out = None; + let mut json = false; + let mut index = 0; + while index < args.len() { + let arg = &args[index]; + match arg.as_str() { + "--unit" => { + index += 1; + unit = Some(require_value(args, index, "--unit")?); + } + "--root" => { + index += 1; + root = Some(PathBuf::from(require_value(args, index, "--root")?)); + } + "--out" => { + index += 1; + out = Some(PathBuf::from(require_value(args, index, "--out")?)); + } + "--json" => json = true, + flag if flag.starts_with('-') => { + return Err(format!("unknown check option `{flag}`")); + } + value => { + if entry.is_some() { + return Err(format!("unexpected extra argument `{value}`")); + } + entry = Some(PathBuf::from(value)); + } + } + index += 1; + } + let entry = entry.ok_or_else(|| "check requires an ENTRY document".to_string())?; + Ok(CheckOptions { + entry, + unit, + root, + out, + json, + }) +} + +fn parse_replay(args: &[String]) -> Result { + let mut positional: Vec = Vec::new(); + let mut root = None; + let mut json = false; + let mut index = 0; + while index < args.len() { + let arg = &args[index]; + match arg.as_str() { + "--root" => { + index += 1; + root = Some(PathBuf::from(require_value(args, index, "--root")?)); + } + "--json" => json = true, + flag if flag.starts_with('-') => { + return Err(format!("unknown replay option `{flag}`")); + } + value => positional.push(value.to_string()), + } + index += 1; + } + if positional.len() != 2 { + return Err("replay requires ENTRY and BUNDLE positional arguments".to_string()); + } + Ok(ReplayOptions { + entry: PathBuf::from(&positional[0]), + bundle: PathBuf::from(&positional[1]), + root, + json, + }) +} + +fn require_value(args: &[String], index: usize, flag: &str) -> Result { + args.get(index) + .filter(|value| !value.starts_with('-') || value.as_str() == "-") + .cloned() + .ok_or_else(|| format!("{flag} requires a value")) } diff --git a/src/model.rs b/src/model.rs index 0187715..3ff3c1b 100644 --- a/src/model.rs +++ b/src/model.rs @@ -1 +1,829 @@ //! Finite exact-integer program model mapping (docs/DEVELOPMENT.md §7). +//! +//! The program bridge is intentionally tiny. Given the Analysis typed IR of one +//! Exec H2, this module either validates the *complete* function against the +//! whitelist subset below, or rejects it. There is no partial acceptance, no +//! regex/raw-Markdown parsing, no execution of the function, and no inference +//! of a general property from examples: +//! +//! * explicit signature, every parameter required, typed `Int`, no defaults; +//! * body = any number of plain local assignments followed by exactly one final +//! `return`, all expressions built from Int literals, variables, unary minus +//! and `+`, `-`, `*`; +//! * one static single frame; a rebind creates a new immutable slot. +//! +//! The deterministic Lean mapping is a `public def marqdoModel_` whose +//! parameters are renamed `mqp0...` and whose assignments become nested `let`s +//! over fresh slots `mql0...`. Original identifiers never reach generated Lean. + +use std::collections::HashMap; + +use num_bigint::BigInt; + +use crate::analysis::{Expression, Function, ModuleData, Place, Statement}; +use crate::{codes, sha256_hex, Diagnostic, Severity, Span}; + +/// One validated model plus its deterministic Lean identity. +#[derive(Clone, Debug)] +pub struct ModelDef { + /// Canonical Analysis FunctionId of the modeled function. + pub function_id: String, + /// Canonical unit id of the Exec H2 that owns the function. + pub unit_id: String, + /// Module logical locator (module.relative_path) that declares it. + pub locator: String, + /// Stable content key: 20 lowercase hex chars derived from the function + /// identity and the validated IR. + pub key: String, + /// Lean declaration name: `marqdoModel_`. + pub lean_name: String, + /// Lean-safe parameter names in declaration order (`mqp0`, `mqp1`, ...). + pub params: Vec, + /// SHA-256 of the deterministic canonical dump of the validated model. + pub digest: String, + /// Human-readable one-line summary for reports. + pub source_summary: String, + /// Supported semantic note; fixed text. + pub semantics: String, + /// Internal normalized program slots, used by `lean_definition`. + slots: Vec, + /// Rendered final return expression over slots. + return_render: String, +} + +#[derive(Clone, Debug)] +struct LeanSlot { + slot: String, + render: String, +} + +/// Lean module name that contains this model definition. +pub fn lean_module_name(model: &ModelDef) -> String { + format!("MarqdoProof.Generated.Model_{}", model.key) +} + +/// Fixed semantic scope note used in reports and manifests. +pub const SEMANTICS: &str = + "exact integer single-frame straight-line model returning Int; not a runtime refinement"; + +impl ModelDef { + /// Lean 4 source of the model declaration (no module header/imports). + pub fn lean_definition(&self) -> String { + let mut out = String::new(); + out.push_str("@[expose] public def "); + out.push_str(&self.lean_name); + for parameter in &self.params { + out.push_str(&format!(" ({parameter} : Int)")); + } + out.push_str(" : Int"); + if self.slots.is_empty() { + out.push_str(&format!(" := {}\n", self.return_render)); + return out; + } + out.push_str(" :=\n"); + for slot in &self.slots { + out.push_str(&format!(" let {} := {};\n", slot.slot, slot.render)); + } + out.push_str(&format!(" {}\n", self.return_render)); + out + } +} + +/// Validate one Analysis function against the supported subset. +/// +/// `Ok` is returned only when every parameter, statement, expression and span +/// is inside the whitelist. The first violation produces a `model.unsupported` +/// diagnostic owned by the offending span. +pub fn build_model( + function: &Function, + module: &ModuleData, +) -> std::result::Result { + validate_span(module, function.span, "function")?; + if function.signature.kind != "explicit" { + return Err(unsupported( + function.heading_span, + format!( + "function `{}` uses an inferred parameter signature; the program bridge only \ + supports explicit typed parameters", + function.local_name + ), + )); + } + let mut parameter_names: Vec = Vec::new(); + for parameter in &function.signature.params { + validate_span(module, parameter.span, "parameter")?; + if !parameter.required { + return Err(unsupported( + parameter.span, + format!( + "parameter `{}` of `{}` is optional; the program bridge requires every \ + parameter to be required", + parameter.name, function.local_name + ), + )); + } + if parameter.default.is_some() { + return Err(unsupported( + parameter.span, + format!( + "parameter `{}` of `{}` has a default value, which the program bridge does \ + not support", + parameter.name, function.local_name + ), + )); + } + if parameter.ty.as_deref() != Some("Int") { + return Err(unsupported( + parameter.span, + format!( + "parameter `{}` of `{}` has type `{}`; every program-model parameter must be \ + exactly `Int`", + parameter.name, + function.local_name, + parameter.ty.as_deref().unwrap_or("") + ), + )); + } + if parameter_names.contains(¶meter.name) { + return Err(unsupported( + parameter.span, + format!("duplicate parameter name `{}`", parameter.name), + )); + } + parameter_names.push(parameter.name.clone()); + } + + // Validate the straight-line body shape: assignments..., one final return. + let mut statements = function.body.iter(); + let mut assignments: Vec<(&str, &Expression)> = Vec::new(); + let mut returned: Option<&Expression> = None; + let mut index = 0usize; + while let Some(statement) = statements.next() { + validate_span(module, statement.span(), "statement")?; + if returned.is_some() { + return Err(unsupported( + statement.span(), + format!( + "function `{}` has a statement after `return`; the program bridge requires \ + exactly one final return", + function.local_name + ), + )); + } + match statement { + Statement::Assign { target, value, .. } => { + let Place::Local(name) = target else { + return Err(unsupported( + statement.span(), + format!( + "function `{}` assigns to a memory/index place; only local \ + rebinding is supported", + function.local_name + ), + )); + }; + if name.is_empty() { + return Err(unsupported(statement.span(), "empty local assignment target")); + } + assignments.push((name.as_str(), value)); + } + Statement::Return { value, .. } => returned = Some(value), + Statement::Expression { .. } => { + return Err(unsupported( + statement.span(), + format!( + "function `{}` has an expression statement; only local assignments and \ + one final return are supported", + function.local_name + ), + )) + } + Statement::Branch { .. } => { + return Err(unsupported( + statement.span(), + format!( + "function `{}` uses a branch; the first release does not model branching", + function.local_name + ), + )) + } + Statement::Loop { .. } => { + return Err(unsupported( + statement.span(), + format!( + "function `{}` uses a loop; the first release does not model loops", + function.local_name + ), + )) + } + Statement::Break { .. } => { + return Err(unsupported( + statement.span(), + format!("function `{}` uses `break` outside a supported loop", function.local_name), + )) + } + Statement::Continue { .. } => { + return Err(unsupported( + statement.span(), + format!( + "function `{}` uses `continue` outside a supported loop", + function.local_name + ), + )) + } + } + index += 1; + if index > 4096 { + return Err(unsupported( + function.span, + "function body is too large for the program bridge".to_string(), + )); + } + } + let Some(return_expression) = returned else { + return Err(unsupported( + function.span, + format!( + "function `{}` has no final `return`; the program bridge requires exactly one \ + final Int return", + function.local_name + ), + )); + }; + + // Build the slot environment. Parameters occupy mqp0..; assignments create + // fresh mql slots in statement order. + let params: Vec = (0..parameter_names.len()) + .map(|index| format!("mqp{index}")) + .collect(); + let mut environment: HashMap = HashMap::new(); + for (index, name) in parameter_names.iter().enumerate() { + environment.insert(name.clone(), params[index].clone()); + } + let mut slots: Vec = Vec::new(); + let mut canonical = String::new(); + canonical.push_str("marqdo-prove/model-dump/v1\n"); + canonical.push_str(&function.id); + canonical.push('\n'); + canonical.push_str(&format!("params:{}\n", parameter_names.join(","))); + for (name, value) in &assignments { + let render = render_lean(value, &environment, module, function)?; + canonical.push_str(&format!( + "assign:{name}={}\n", + render_original(value, &environment, module, function)? + )); + let slot = format!("mql{}", slots.len()); + slots.push(LeanSlot { + slot: slot.clone(), + render, + }); + environment.insert((*name).to_string(), slot); + } + let return_render = render_lean(return_expression, &environment, module, function)?; + canonical.push_str(&format!( + "return:{}\n", + render_original(return_expression, &environment, module, function)? + )); + let digest = sha256_hex(canonical.as_bytes()); + let key = model_key(&function.id, &module.relative_path, &digest); + let lean_name = format!("marqdoModel_{key}"); + let summary_def = format!( + "def {}({}) : Int := {}", + function.local_name, + parameter_names + .iter() + .map(|name| format!("{name}: Int")) + .collect::>() + .join(", "), + render_summary(return_expression, &assignments, &environment, module, function)? + ); + Ok(ModelDef { + function_id: function.id.clone(), + unit_id: function.unit_id.clone(), + locator: module.relative_path.clone(), + key, + lean_name, + params, + digest, + source_summary: summary_def, + semantics: SEMANTICS.to_string(), + slots, + return_render, + }) +} + +/// Stable key of a model definition (20 lowercase hex). +fn model_key(function_id: &str, locator: &str, digest: &str) -> String { + let material = format!("marqdo-prove/model/v2\u{0}{function_id}\u{0}{locator}\u{0}{digest}"); + sha256_hex(material.as_bytes())[..20].to_string() +} + +fn render_lean( + expression: &Expression, + environment: &HashMap, + module: &ModuleData, + function: &Function, +) -> std::result::Result { + validate_span(module, expression.span(), "expression")?; + match expression { + Expression::Literal { ty, value, span } => { + if ty != "int" { + return Err(unsupported( + *span, + format!( + "function `{}` uses a `{ty}` literal; only Int literals are supported", + function.local_name + ), + )); + } + let Some(serde_json::Value::String(text)) = value else { + return Err(unsupported(*span, "integer literal has a non-string Analysis value")); + }; + if text.len() > crate::limits::MAX_LITERAL_DIGITS { + return Err(unsupported( + *span, + format!( + "integer literal exceeds the {} digit budget", + crate::limits::MAX_LITERAL_DIGITS + ), + )); + } + let normalized = normalize_integer_literal(text).ok_or_else(|| { + unsupported( + *span, + format!("`{text}` is not a canonical decimal integer literal"), + ) + })?; + Ok(render_int_literal(&normalized)) + } + Expression::Variable { name, span } => match environment.get(name) { + Some(slot) => Ok(slot.clone()), + None => Err(unsupported( + *span, + format!( + "function `{}` reads local `{name}` before it is defined; the program bridge \ + has no defaults or ambient values", + function.local_name + ), + )), + }, + Expression::Unary { op, operand, span } => { + if op != "neg" { + return Err(unsupported( + *span, + format!( + "function `{}` uses unsupported unary operator `{op}`; only integer \ + negation is supported", + function.local_name + ), + )); + } + let inner = render_lean(operand, environment, module, function)?; + Ok(format!("(- {inner})")) + } + Expression::Binary { + op, + left, + right, + span, + } => { + let operator = match op.as_str() { + "add" => "+", + "sub" => "-", + "mul" => "*", + other => { + return Err(unsupported( + *span, + format!( + "function `{}` uses unsupported binary operator `{other}`; the \ + program bridge supports only `+`, `-`, `*`", + function.local_name + ), + )) + } + }; + let left = render_lean(left, environment, module, function)?; + let right = render_lean(right, environment, module, function)?; + Ok(format!("({left} {operator} {right})")) + } + Expression::List { span, .. } + | Expression::Record { span, .. } + | Expression::Member { span, .. } + | Expression::Index { span, .. } + | Expression::Call { span, .. } => Err(unsupported( + *span, + format!( + "function `{}` uses an unsupported expression form `{}`", + function.local_name, + expression_kind(expression) + ), + )), + } +} + +fn render_original( + expression: &Expression, + environment: &HashMap, + module: &ModuleData, + function: &Function, +) -> std::result::Result { + let _ = environment; + render_pretty(expression, module, function) +} + +fn render_pretty( + expression: &Expression, + module: &ModuleData, + function: &Function, +) -> std::result::Result { + match expression { + Expression::Literal { ty, value, .. } => { + let Some(serde_json::Value::String(text)) = value else { + return Err(unsupported(expression.span(), "non-string integer literal")); + }; + let normalized = normalize_integer_literal(text).ok_or_else(|| { + unsupported(expression.span(), "invalid integer literal") + })?; + Ok(normalized) + } + Expression::Variable { name, .. } => Ok(name.clone()), + Expression::Unary { operand, .. } => Ok(format!( + "-{}", + render_pretty(operand, module, function)? + )), + Expression::Binary { + op, left, right, .. + } => { + let operator = match op.as_str() { + "add" => "+", + "sub" => "-", + "mul" => "*", + other => { + return Err(unsupported( + expression.span(), + format!("unsupported operator `{other}`"), + )) + } + }; + Ok(format!( + "({} {operator} {})", + render_pretty(left, module, function)?, + render_pretty(right, module, function)? + )) + } + other => Err(unsupported( + other.span(), + format!( + "function `{}` uses an unsupported expression form `{}`", + function.local_name, + expression_kind(other) + ), + )), + } +} + +fn render_summary( + return_expression: &Expression, + assignments: &[(&str, &Expression)], + environment: &HashMap, + module: &ModuleData, + function: &Function, +) -> std::result::Result { + let returned = render_original(return_expression, environment, module, function)?; + if assignments.is_empty() { + return Ok(returned); + } + let mut parts = Vec::new(); + for (name, value) in assignments { + parts.push(format!( + "let {name} = {}", + render_original(value, environment, module, function)? + )); + } + parts.push(returned); + Ok(parts.join("; ")) +} + +fn normalize_integer_literal(text: &str) -> Option { + if text.is_empty() { + return None; + } + let digits = text.strip_prefix('-').unwrap_or(text); + if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) { + return None; + } + if digits.len() > crate::limits::MAX_LITERAL_DIGITS { + return None; + } + let value: BigInt = text.parse().ok()?; + Some(value.to_string()) +} + +fn render_int_literal(normalized: &str) -> String { + if let Some(rest) = normalized.strip_prefix('-') { + format!("(- {rest} : Int)") + } else { + format!("({normalized} : Int)") + } +} + +fn expression_kind(expression: &Expression) -> &'static str { + match expression { + Expression::Literal { .. } => "literal", + Expression::Variable { .. } => "variable", + Expression::List { .. } => "list", + Expression::Record { .. } => "record", + Expression::Unary { .. } => "unary", + Expression::Binary { .. } => "binary", + Expression::Member { .. } => "member", + Expression::Index { .. } => "index", + Expression::Call { .. } => "call", + } +} + +fn validate_span( + module: &ModuleData, + span: Span, + owner: &str, +) -> std::result::Result<(), Diagnostic> { + if span.is_valid_in(&module.source) { + Ok(()) + } else { + Err(unsupported( + span, + format!("{owner} span is outside the module source"), + )) + } +} + +fn unsupported(span: Span, message: impl Into) -> Diagnostic { + Diagnostic { + severity: Severity::Error, + code: codes::MODEL_UNSUPPORTED, + message: message.into(), + span: Some(span), + hint: Some( + "the program-model bridge supports only explicit Int parameters, local `+ - *` \ + assignments and a final Int return; keep the rest of the knowledge document as \ + ordinary readable knowledge" + .to_string(), + ), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::analysis::ModuleData; + use std::collections::{BTreeMap, HashMap}; + + fn module(source_len: usize) -> ModuleData { + ModuleData { + id: "root:t::arith.mq.md".to_string(), + package_instance_id: "root:t".to_string(), + relative_path: "arith.mq.md".to_string(), + source: " ".repeat(source_len), + source_digest: sha256_hex(b"x"), + document: crate::analysis::Node::default(), + units: vec![], + anchors: BTreeMap::new(), + functions: vec![], + references: vec![], + resources: vec![], + unit_by_id: HashMap::new(), + } + } + + fn expression(json: serde_json::Value) -> Expression { + serde_json::from_value(json).expect("expression fixture") + } + + fn function_fixture(body: serde_json::Value, params: serde_json::Value, kind: &str) -> Function { + serde_json::from_value(serde_json::json!({ + "id": "root:t::arith.mq.md::整数计算.square", + "unit_id": "root:t::arith.mq.md#整数计算/square", + "local_name": "square", + "namespace": "整数计算", + "span": {"start": 0, "end": 100}, + "heading_span": {"start": 0, "end": 20}, + "signature": {"kind": kind, "params": params}, + "effects": ["unknown"], + "body": body + })) + .expect("function fixture") + } + + fn int_param(name: &str, span_start: usize, span_end: usize) -> serde_json::Value { + serde_json::json!({ + "name": name, + "required": true, + "type": "Int", + "default": null, + "span": {"start": span_start, "end": span_end} + }) + } + + fn variable(name: &str) -> serde_json::Value { + serde_json::json!({"kind": "variable", "name": name, "span": {"start": 0, "end": 10}}) + } + + fn int_literal(value: &str) -> serde_json::Value { + serde_json::json!({"kind": "literal", "type": "int", "value": value, "span": {"start": 0, "end": 10}}) + } + + fn binary(op: &str, left: serde_json::Value, right: serde_json::Value) -> serde_json::Value { + serde_json::json!({"kind": "binary", "op": op, "left": left, "right": right, + "span": {"start": 0, "end": 30}}) + } + + fn return_stmt(value: serde_json::Value) -> serde_json::Value { + serde_json::json!({"kind": "return", "value": value, "span": {"start": 50, "end": 80}}) + } + + fn assign(target: &str, value: serde_json::Value) -> serde_json::Value { + serde_json::json!({"kind": "assign", "target": target, "value": value, + "span": {"start": 20, "end": 45}}) + } + + #[test] + fn square_model_maps_to_exact_lean_definition() { + let function = function_fixture(serde_json::json!([return_stmt(binary("mul", variable("x"), variable("x")))]), + serde_json::json!([int_param("x", 20, 30)]), + "explicit", + ); + let model = build_model(&function, &module(200)).expect("square model"); + assert_eq!(model.params, vec!["mqp0".to_string()]); + assert_eq!(model.key.len(), 20); + assert!(model.lean_name.starts_with("marqdoModel_")); + assert_eq!( + model.lean_definition(), + "@[expose] public def marqdoModel_".to_string() + &model.key + " (mqp0 : Int) : Int := (mqp0 * mqp0)\n" + ); + assert_eq!(model.digest.len(), 64); + assert!(model.source_summary.starts_with("def square(x: Int) : Int := (x * x)")); + assert_eq!(lean_module_name(&model), format!("MarqdoProof.Generated.Model_{}", model.key)); + // deterministic + let again = build_model(&function, &module(200)).expect("square model"); + assert_eq!(model.key, again.key); + assert_eq!(model.digest, again.digest); + } + + #[test] + fn zero_parameter_constant_model() { + let function = function_fixture(serde_json::json!([return_stmt(int_literal("42"))]), + serde_json::json!([]), + "explicit", + ); + let model = build_model(&function, &module(200)).expect("constant model"); + assert!(model.lean_definition().contains("(42 : Int)")); + assert!(!model.lean_definition().contains("let ")); + } + + #[test] + fn rebinding_creates_fresh_slots() { + let function = function_fixture(serde_json::json!([ + assign("y", binary("add", variable("x"), int_literal("1"))), + assign("y", binary("mul", variable("y"), variable("y"))), + return_stmt(variable("y")) + ]), + serde_json::json!([int_param("x", 20, 30)]), + "explicit", + ); + let model = build_model(&function, &module(400)).expect("rebinding model"); + let definition = model.lean_definition(); + assert!(definition.contains("let mql0 := (mqp0 + (1 : Int));")); + assert!(definition.contains("let mql1 := (mql0 * mql0);")); + assert!(definition.contains(" mql1\n")); + } + + #[test] + fn negative_literals_and_unary_minus_render_exactly() { + let function = function_fixture(serde_json::json!([return_stmt(serde_json::json!({ + "kind": "unary", "op": "neg", "operand": int_literal("-7"), + "span": {"start": 0, "end": 20} + }))]), + serde_json::json!([]), + "explicit", + ); + let model = build_model(&function, &module(200)).expect("neg model"); + assert!( + model.lean_definition().contains("(- (- 7 : Int))"), + "{}", + model.lean_definition() + ); + } + + #[test] + fn rejects_unsupported_shapes() { + let cases: Vec<(Function, &str)> = vec![ + ( + function_fixture(serde_json::json!([return_stmt(variable("x"))]), + serde_json::json!([int_param("x", 20, 30)]), + "inferred", + ), + "inferred", + ), + ( + function_fixture(serde_json::json!([return_stmt(variable("x"))]), + serde_json::json!([{ + "name": "x", "required": true, "type": "Float", + "default": null, "span": {"start": 20, "end": 30} + }]), + "explicit", + ), + "type", + ), + ( + function_fixture(serde_json::json!([return_stmt(int_literal("1.5"))]), + serde_json::json!([]), + "explicit", + ), + "literal", + ), + ( + function_fixture(serde_json::json!([return_stmt(binary("div", variable("x"), int_literal("2")))]), + serde_json::json!([int_param("x", 20, 30)]), + "explicit", + ), + "operator", + ), + ( + function_fixture(serde_json::json!([return_stmt(variable("y"))]), + serde_json::json!([int_param("x", 20, 30)]), + "explicit", + ), + "before it is defined", + ), + ( + function_fixture(serde_json::json!([assign("x", int_literal("1"))]), + serde_json::json!([]), + "explicit", + ), + "return", + ), + ( + function_fixture(serde_json::json!([ + return_stmt(int_literal("1")), + assign("x", int_literal("2")) + ]), + serde_json::json!([]), + "explicit", + ), + "after", + ), + ( + function_fixture(serde_json::json!([{ + "kind": "branch", + "arms": [{"condition": int_literal("1"), "condition_span": {"start": 0, "end": 1}, + "body": [], "span": {"start": 0, "end": 1}}], + "span": {"start": 0, "end": 10} + }]), + serde_json::json!([]), + "explicit", + ), + "branch", + ), + ]; + for (function, needle) in cases { + let error = build_model(&function, &module(400)).expect_err(needle); + assert_eq!(error.code, codes::MODEL_UNSUPPORTED); + let whole = format!("{error:?}"); + assert!( + whole.contains(needle), + "expected {needle:?} in {whole:?}" + ); + } + } + + #[test] + fn huge_literal_is_rejected_and_leading_zeros_normalized() { + let huge = "9".repeat(5000); + let function = function_fixture(serde_json::json!([return_stmt(int_literal(&huge))]), + serde_json::json!([]), + "explicit", + ); + assert!(build_model(&function, &module(200)).is_err()); + let function = function_fixture(serde_json::json!([return_stmt(int_literal("00042"))]), + serde_json::json!([]), + "explicit", + ); + let model = build_model(&function, &module(200)).expect("literal"); + assert!(model.lean_definition().contains("(42 : Int)")); + } + + #[test] + fn index_place_assignment_is_rejected() { + let function = function_fixture(serde_json::json!([{ + "kind": "assign", + "target": {"kind": "index", "base": variable("x"), + "index": int_literal("0"), "span": {"start": 0, "end": 10}}, + "value": int_literal("1"), + "span": {"start": 0, "end": 20} + }, return_stmt(int_literal("1"))]), + serde_json::json!([int_param("x", 20, 30)]), + "explicit", + ); + let error = build_model(&function, &module(300)).expect_err("index"); + assert!(format!("{error:?}").contains("index")); + } +} diff --git a/src/prove.rs b/src/prove.rs index f22e06a..f317753 100644 --- a/src/prove.rs +++ b/src/prove.rs @@ -1 +1,1992 @@ -//! Single orchestration of `check` and `replay`. +//! Single orchestration of `check` and `replay` (docs/DEVELOPMENT.md §9–§10). +//! +//! This is the only place that orders the workflow: Analysis snapshot, proof +//! unit extraction, link closure and topological order, formula/model +//! preparation, cache lookup and independent replay, bounded search, refutation +//! attempt, proof bundle publication and report assembly. + +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Instant; + +use num_bigint::BigInt; +use serde::Serialize; + +use crate::analysis::{AnalysisBackend, Snapshot}; +use crate::certificate::{ + Bundle, BundleManifest, CacheIdentity, CacheStore, DeclaredDependency, ModelBinding, + ProofPayload, SourceBinding, TargetIdentity, ToolIdentity, ALLOWED_AXIOMS, PAYLOAD_FILE, +}; +use crate::document::{self, Extraction, ProofUnit}; +use crate::formula::{self, FormulaError, Goal}; +use crate::lean::{Attempt, Evidence, LeanBackend, ModelSource, ProofAttempt}; +use crate::linker::{Closure, DependencyTarget, Linker, LoadedUnit}; +use crate::model::{self, ModelDef}; +use crate::{ + codes, sha256_hex, Diagnostic, Freshness, Outcome, Result, RunStatus, Scope, Severity, Span, +}; + +pub const RESULT_SCHEMA: &str = "marqdo.prove.result"; +pub const RESULT_SCHEMA_VERSION: u64 = 1; + +#[derive(Clone, Debug)] +pub struct CheckOptions { + pub entry: PathBuf, + pub unit: Option, + pub root: Option, + pub out: Option, + pub json: bool, +} + +#[derive(Clone, Debug)] +pub struct ReplayOptions { + pub entry: PathBuf, + pub bundle: PathBuf, + pub root: Option, + pub json: bool, +} + +#[derive(Clone, Debug)] +pub enum Invocation { + Check(CheckOptions), + Replay(ReplayOptions), +} + +// --------------------------------------------------------------------------- +// Report types (the JSON projection of the same internal result object) +// --------------------------------------------------------------------------- + +#[derive(Clone, Debug, Serialize)] +pub struct DiagnosticReport { + pub code: String, + pub severity: String, + pub message: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub span: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub hint: Option, +} + +impl From<&Diagnostic> for DiagnosticReport { + fn from(diagnostic: &Diagnostic) -> Self { + Self { + code: diagnostic.code.to_string(), + severity: diagnostic.severity.as_str().to_string(), + message: diagnostic.message.clone(), + span: diagnostic.span, + hint: diagnostic.hint.clone(), + } + } +} + +#[derive(Clone, Debug, Serialize)] +pub struct StatementReport { + pub literal: String, + pub normalized: String, + pub lean: String, +} + +#[derive(Clone, Debug, Serialize)] +pub struct SourceReport { + pub module_id: String, + pub locator: String, + pub unit_id: String, + pub section_span: Span, + pub goal_span: Span, + #[serde(skip_serializing_if = "Option::is_none")] + pub goal_payload_span: Option, +} + +#[derive(Clone, Debug, Serialize)] +pub struct DependencyReport { + pub kind: String, + pub link_text: String, + pub locator: String, + pub unit_id: String, + pub binding: String, +} + +#[derive(Clone, Debug, Serialize)] +pub struct CertificateReport { + pub cache_key: String, + pub directory: String, + pub payload_sha256: String, + pub outcome: String, +} + +#[derive(Clone, Debug, Serialize)] +pub struct TargetReport { + pub unit_id: String, + pub locator: String, + pub title: String, + pub outcome: String, + pub scope: String, + pub freshness: String, + pub statement: StatementReport, + pub source: SourceReport, + pub premises: Vec, + pub declared_dependencies: Vec, + pub used_dependencies: Vec, + pub transitive_dependencies: Vec, + pub axioms: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + pub certificate: Option, + pub diagnostics: Vec, +} + +#[derive(Clone, Debug, Serialize)] +pub struct Report { + pub schema: String, + pub schema_version: u64, + pub command: String, + pub entry: String, + pub root: String, + pub status: String, + pub targets: Vec, + pub diagnostics: Vec, +} + +impl Report { + pub fn status(&self) -> RunStatus { + if self.status == "failure" { + RunStatus::Failure + } else { + match self.targets.as_slice() { + [] => RunStatus::Success, + targets => { + if targets.iter().all(|target| target.outcome == "verified") { + RunStatus::Success + } else { + RunStatus::Unverified + } + } + } + } + } + + pub fn render_text(&self) -> String { + let mut out = String::new(); + out.push_str(&format!("entry: {}\n", self.entry)); + out.push_str(&format!("root: {}\n", self.root)); + if self.targets.is_empty() { + out.push_str("no targets: no selected Knowledge H2 with a `证明依赖` heading\n"); + } + for target in &self.targets { + out.push_str(&format!( + "\n{} {} ({}, {})\n", + target.outcome, target.title, target.scope, target.freshness + )); + out.push_str(&format!( + " source: {}# {}\n", + target.source.locator, target.source.unit_id + )); + out.push_str(&format!(" statement: {}\n", target.statement.normalized)); + if !target.premises.is_empty() { + out.push_str(&format!( + " premises: {} (non-emptiness not proven)\n", + target.premises.join("; ") + )); + } + if target.declared_dependencies.is_empty() { + out.push_str(" declared dependencies: none\n"); + } else { + out.push_str(" declared dependencies:\n"); + for dependency in &target.declared_dependencies { + out.push_str(&format!( + " - {} {} ({})\n", + dependency.kind, dependency.locator, dependency.link_text + )); + } + } + if !target.used_dependencies.is_empty() { + out.push_str(&format!( + " used dependencies: {}\n", + target.used_dependencies.join(", ") + )); + let unused: Vec<&str> = target + .declared_dependencies + .iter() + .map(|dependency| dependency.unit_id.as_str()) + .filter(|unit_id| !target.used_dependencies.iter().any(|used| used == unit_id)) + .collect(); + if !unused.is_empty() { + out.push_str(&format!(" declared but not used: {}\n", unused.join(", "))); + } + } + if !target.axioms.is_empty() { + out.push_str(&format!(" axioms: {}\n", target.axioms.join(", "))); + } + if let Some(certificate) = &target.certificate { + out.push_str(&format!( + " certificate: {} ({})\n", + certificate.cache_key, certificate.directory + )); + } + for diagnostic in &target.diagnostics { + out.push_str(&format!( + " {} [{}] {}\n", + diagnostic.severity, diagnostic.code, diagnostic.message + )); + } + } + let verified = self + .targets + .iter() + .filter(|target| target.outcome == "verified") + .count(); + out.push_str(&format!( + "\nsummary: {} target(s), {} verified\n", + self.targets.len(), + verified + )); + for diagnostic in &self.diagnostics { + out.push_str(&format!( + "{} [{}] {}\n", + diagnostic.severity, diagnostic.code, diagnostic.message + )); + } + out + } +} + +fn failure_report(command: &str, entry: &Path, root: &Path, failure: &crate::Failure) -> Report { + Report { + schema: RESULT_SCHEMA.to_string(), + schema_version: RESULT_SCHEMA_VERSION, + command: command.to_string(), + entry: entry.display().to_string(), + root: root.display().to_string(), + status: "failure".to_string(), + targets: Vec::new(), + diagnostics: vec![DiagnosticReport { + code: failure.code.to_string(), + severity: "error".to_string(), + message: failure.message.clone(), + span: None, + hint: failure.hint.clone(), + }], + } +} + +// --------------------------------------------------------------------------- +// Public entry points +// --------------------------------------------------------------------------- + +pub fn run(invocation: Invocation) -> Report { + match invocation { + Invocation::Check(options) => run_check(options), + Invocation::Replay(options) => run_replay(options), + } +} + +fn marqdo_bin() -> Result { + let bin = std::env::var_os("MARQDO_BIN").map(PathBuf::from).unwrap_or_else(|| { + // Tool installs always inject an absolute MARQDO_BIN; a developer build + // may rely on PATH, which we resolve explicitly here. + PathBuf::from("marqdo") + }); + if bin.is_absolute() { + return Ok(bin); + } + if let Some(path) = std::env::var_os("PATH") { + for directory in std::env::split_paths(&path) { + let candidate = directory.join(&bin); + if candidate.is_file() { + return Ok(candidate); + } + } + } + Err(crate::Failure::new( + codes::BACKEND_UNAVAILABLE, + "cannot find the real `marqdo` CLI; set MARQDO_BIN to its absolute path", + )) +} + +struct Context { + root: PathBuf, + linker: Linker, + cache: CacheStore, + lean: Option>, + task_started: Instant, +} + +impl Context { + fn lean(&mut self) -> Result> { + if self.lean.is_none() { + self.lean = Some(Arc::new(LeanBackend::discover()?)); + } + Ok(self + .lean + .as_ref() + .expect("just initialized") + .clone()) + } + + fn work_dir(&self) -> PathBuf { + self.cache.work_dir() + } +} + +fn open_context(entry: &Path, explicit_root: Option<&Path>) -> Result { + let bin = marqdo_bin()?; + let root = AnalysisBackend::discover_root(entry, explicit_root)?; + let cache = CacheStore::new(&root); + std::fs::create_dir_all(cache.work_dir()).map_err(|error| { + crate::Failure::new( + codes::BACKEND_UNAVAILABLE, + format!("cannot create private work directory: {error}"), + ) + })?; + let backend = AnalysisBackend::new(bin, cache.work_dir().join("analysis"))?; + let linker = Linker::new(backend, root.clone())?; + Ok(Context { + root, + linker, + cache, + lean: None, + task_started: Instant::now(), + }) +} + +// --------------------------------------------------------------------------- +// check +// --------------------------------------------------------------------------- + +fn run_check(options: CheckOptions) -> Report { + let mut context = match open_context(&options.entry, options.root.as_deref()) { + Ok(context) => context, + Err(failure) => { + return failure_report( + "check", + &options.entry, + options.root.as_deref().unwrap_or(Path::new(".")), + &failure, + ) + } + }; + let root = context.root.clone(); + match check_inner(&mut context, &options) { + Ok(report) => report, + Err(failure) => failure_report("check", &options.entry, &root, &failure), + } +} + +fn check_inner(context: &mut Context, options: &CheckOptions) -> Result { + let entry = context.linker.load_document(&options.entry)?; + let extraction = context.linker.extract_units(&entry); + let mut diagnostics: Vec = Vec::new(); + // Selection. + let mut selected: Vec<(String, ProofUnit)> = Vec::new(); + if let Some(fragment) = &options.unit { + match document::resolve_selection(entry.entry(), fragment) { + Ok(unit_id) => { + let mut found = false; + for candidate in &extraction { + match candidate { + Extraction::Unit(unit) if unit.unit_id == unit_id => { + selected.push((unit.unit_id.clone(), unit.clone())); + found = true; + } + Extraction::Invalid(diagnostic) => { + if diagnostic.code == codes::DOCUMENT_DEPENDENCIES_SHAPE + || diagnostic.code == codes::DOCUMENT_GOAL_COUNT + { + diagnostics.push(diagnostic.clone()); + } + } + _ => {} + } + } + if !found { + diagnostics.push(Diagnostic::error( + codes::DOCUMENT_UNIT, + format!("`--unit {fragment}` did not select a proof target"), + )); + return Ok(empty_report( + context, + "check", + &entry, + RunStatus::Unverified, + diagnostics, + )); + } + } + Err(diagnostic) => { + diagnostics.push(diagnostic); + return Ok(empty_report( + context, + "check", + &entry, + RunStatus::Unverified, + diagnostics, + )); + } + } + } else { + for candidate in &extraction { + match candidate { + Extraction::Unit(unit) => selected.push((unit.unit_id.clone(), unit.clone())), + Extraction::Invalid(diagnostic) => diagnostics.push(diagnostic.clone()), + } + } + } + if selected.is_empty() { + return Ok(empty_report(context, "check", &entry, RunStatus::Success, diagnostics)); + } + // Dependency closure. + let selection: Vec = selected.iter().map(|(unit_id, _)| unit_id.clone()).collect(); + let closure = context.linker.resolve_closure(&entry, &selection)?; + diagnostics.extend(closure.diagnostics.iter().cloned()); + + // Prepare every closure unit (formula + program model validation). + let mut nodes = prepare_closure(&closure, &mut diagnostics); + // Process in dependency-first order. + let mut outcomes: HashMap = HashMap::new(); + let indices: Vec = (0..nodes.len()).collect(); + for index in indices { + let result = process_node(context, &mut nodes, &mut outcomes, index); + outcomes.insert(index, result); + } + // Report selected entry units in document order. + let mut targets = Vec::new(); + for (unit_id, _) in &selected { + let Some(index) = nodes.iter().position(|node| { + node.loaded.snapshot.canonical_path == entry.canonical_path + && node.loaded.proof_unit.unit_id == *unit_id + }) else { + continue; + }; + let Some(result) = outcomes.get(&index) else { + continue; + }; + targets.push(build_target_report(context, &nodes[index], result)); + } + // Export requested bundles. + if let Some(out) = &options.out { + export_bundles(context, &nodes, &outcomes, out, &targets)?; + } + let status = if targets.iter().all(|target| target.outcome == "verified") { + RunStatus::Success + } else { + RunStatus::Unverified + }; + let report = Report { + schema: RESULT_SCHEMA.to_string(), + schema_version: RESULT_SCHEMA_VERSION, + command: "check".to_string(), + entry: entry.canonical_path.display().to_string(), + root: context.root.display().to_string(), + status: match status { + RunStatus::Success => "success", + _ => "unverified", + } + .to_string(), + targets, + diagnostics: diagnostics.iter().map(DiagnosticReport::from).collect(), + }; + Ok(report) +} + +fn empty_report( + context: &mut Context, + command: &str, + entry: &Arc, + status: RunStatus, + diagnostics: Vec, +) -> Report { + Report { + schema: RESULT_SCHEMA.to_string(), + schema_version: RESULT_SCHEMA_VERSION, + command: command.to_string(), + entry: entry.canonical_path.display().to_string(), + root: context.root.display().to_string(), + status: match status { + RunStatus::Success => "success", + RunStatus::Unverified => "unverified", + RunStatus::Failure => "failure", + } + .to_string(), + targets: Vec::new(), + diagnostics: diagnostics.iter().map(DiagnosticReport::from).collect(), + } +} + +// --------------------------------------------------------------------------- +// closure preparation +// --------------------------------------------------------------------------- + +struct PreparedModel { + definition: ModelDef, + link_text: String, + source: ModelSource, +} + +struct PreparedNode { + loaded: LoadedUnit, + goal: Option, + formula_error: Option, + models: Vec, + alias_map: BTreeMap, + statement_source: String, + theorem_key: String, + scope: Scope, + theorem_dependencies: Vec, + model_documents: Vec, + prepared_error: Option, +} + +struct UnitResult { + outcome: Outcome, + freshness: Freshness, + scope: Scope, + evidence: Option, + manifest: Option, + diagnostics: Vec, + used: Vec, + transitive: Vec, + axioms: Vec, + certificate: Option, +} + +fn prepare_closure(closure: &Closure, diagnostics: &mut Vec) -> Vec { + let mut nodes: Vec = closure + .units + .iter() + .map(|loaded| { + let unit = &loaded.proof_unit; + let theorem_key = theorem_key( + &loaded.snapshot.relative_path, + &unit.path, + &unit.goal.digest, + ); + PreparedNode { + loaded: loaded.clone(), + goal: None, + formula_error: None, + models: Vec::new(), + alias_map: BTreeMap::new(), + statement_source: String::new(), + theorem_key, + scope: Scope::Mathematical, + theorem_dependencies: Vec::new(), + model_documents: Vec::new(), + prepared_error: None, + } + }) + .collect(); + let index_of: HashMap<(PathBuf, String), usize> = nodes + .iter() + .enumerate() + .map(|(index, node)| { + ( + ( + node.loaded.snapshot.canonical_path.clone(), + node.loaded.proof_unit.unit_id.clone(), + ), + index, + ) + }) + .collect(); + for node in nodes.iter_mut() { + if let Some(diagnostic) = node.loaded.diagnostics.first() { + node.prepared_error = Some(diagnostic.clone()); + continue; + } + let loaded = node.loaded.clone(); + let goal_span = loaded + .proof_unit + .goal + .payload_span + .unwrap_or(loaded.proof_unit.goal.block_span); + match formula::parse(&loaded.proof_unit.goal.literal, goal_span) { + Ok(goal) => node.goal = Some(goal), + Err(error) => { + let diagnostic = formula_diagnostic(&loaded, &error); + diagnostics.push(diagnostic.clone()); + node.formula_error = Some(diagnostic); + continue; + } + } + // Resolve theorem dependency indices and program model definitions. + for dependency in &loaded.dependencies { + match &dependency.target { + DependencyTarget::Theorem { + snapshot, + unit_id, + .. + } => { + let key = (snapshot.canonical_path.clone(), unit_id.clone()); + match index_of.get(&key) { + Some(index) => node.theorem_dependencies.push(*index), + None => { + node.prepared_error = Some(Diagnostic::error( + codes::LINK_INVALID, + format!( + "dependency `{}` was not part of the resolved closure", + dependency.link.url + ), + ) + .at(dependency.link.link_span)); + break; + } + } + } + DependencyTarget::Model { + snapshot, + function, + .. + } => { + let module = snapshot + .modules + .values() + .find(|module| module.function(&function.id).is_some()); + let Some(module) = module else { + node.prepared_error = Some(Diagnostic::error( + codes::LINK_CONTEXT_CONFLICT, + format!("program model target `{}` is not in its module", dependency.link.url), + ) + .at(dependency.link.link_span)); + break; + }; + match model::build_model(function, module) { + Ok(definition) => { + let module_name = model::lean_module_name(&definition); + let source = ModelSource { + module_name: module_name.clone(), + lean_name: definition.lean_name.clone(), + source: format!( + "module\n\npublic import MarqdoProof.Basic\n\n{}\n", + definition.lean_definition() + ), + key: definition.key.clone(), + }; + if !node.alias_map.contains_key(&dependency.link.text) { + node.alias_map.insert( + dependency.link.text.clone(), + definition.lean_name.clone(), + ); + } + node.models.push(PreparedModel { + definition, + link_text: dependency.link.text.clone(), + source, + }); + } + Err(diagnostic) => { + node.prepared_error = Some(Diagnostic { + severity: Severity::Error, + code: diagnostic.code, + message: format!( + "program model `{}` is unsupported: {}", + dependency.link.url, diagnostic.message + ), + span: Some(dependency.link.link_span), + hint: diagnostic.hint, + }); + break; + } + } + node.model_documents.push(snapshot.relative_path.clone()); + } + } + } + if node.prepared_error.is_some() { + continue; + } + // Math alias validation: every model link must be used exactly as the + // formula's `\operatorname{...}` alias and every alias must be bound. + if let Some(goal) = &node.goal { + let used = goal.used_aliases(); + for alias in &used { + if !node.alias_map.contains_key(alias) { + node.prepared_error = Some(Diagnostic::error( + codes::MODEL_UNBOUND_ALIAS, + format!( + "formula calls `\\operatorname{{{alias}}}(...)` but no dependency link is \ + bound to a program model with that alias" + ), + ) + .at(goal.span) + .with_hint( + "add `- [alias](doc.mq.md#exec-heading)` whose link text is exactly the \ + ASCII function alias", + )); + break; + } + } + if node.prepared_error.is_none() { + for model in &node.models { + if !used.contains(&model.link_text) { + node.prepared_error = Some(Diagnostic::error( + codes::MODEL_UNBOUND_ALIAS, + format!( + "program model link `{}` is declared but the formula never calls \ + `\\operatorname{{{}}}(...)`", + model.link_text, model.link_text + ), + ) + .at(node.loaded.proof_unit.goal.block_span)); + break; + } + } + let mut aliases = BTreeMap::new(); + for model in &node.models { + aliases.insert(model.link_text.clone(), model.definition.lean_name.clone()); + } + match goal.lean_prop(&aliases) { + Ok(source) => { + node.statement_source = source; + node.scope = if node.models.is_empty() { + Scope::Mathematical + } else { + Scope::ProgramModel + }; + } + Err(error) => { + node.prepared_error = Some(formula_diagnostic(&node.loaded, &error)); + } + } + } + } + } + nodes +} + +fn formula_diagnostic(loaded: &LoadedUnit, error: &FormulaError) -> Diagnostic { + let span = error.offset.and_then(|offset| { + let goal = &loaded.proof_unit.goal; + goal.payload_span.and_then(|payload| { + let start = payload.start + offset; + if start <= payload.end && start <= loaded.module.source.len() { + Some(Span::new(start, start.min(payload.end))) + } else { + Some(goal.block_span) + } + }) + }); + let span = span.unwrap_or(loaded.proof_unit.goal.block_span); + let severity = Severity::Error; + let mut diagnostic = Diagnostic { + severity, + code: error.code(), + message: error.message.clone(), + span: Some(span), + hint: error.hint.clone(), + }; + if diagnostic.message.is_empty() { + diagnostic.message = "invalid goal formula".to_string(); + } + diagnostic +} + +// --------------------------------------------------------------------------- +// node processing: cache, search, refutation +// --------------------------------------------------------------------------- + +fn process_node( + context: &mut Context, + nodes: &mut [PreparedNode], + outcomes: &mut HashMap, + index: usize, +) -> UnitResult { + let (theorem_key, scope) = { + let node = &nodes[index]; + (node.theorem_key.clone(), node.scope) + }; + if let Some(diagnostic) = nodes[index].prepared_error.clone() { + return simple_result( + Outcome::Invalid, + scope, + vec![diagnostic], + ); + } + // Blocked dependencies: every declared theorem dependency must be verified. + let mut blocked: Vec = Vec::new(); + for dependency in &nodes[index].loaded.dependencies { + if let DependencyTarget::Theorem { + snapshot, + unit_id, + .. + } = &dependency.target + { + let found = nodes.iter().position(|node| { + node.loaded.snapshot.canonical_path == snapshot.canonical_path + && node.loaded.proof_unit.unit_id == *unit_id + }); + match found.and_then(|found| outcomes.get(&found)) { + Some(result) if result.outcome == Outcome::Verified => {} + Some(result) => blocked.push(Diagnostic::error( + codes::LINK_MISSING, + format!( + "dependency `{}` has outcome `{}`; it cannot be used as an axiom", + dependency.link.url, + result.outcome.as_str() + ), + ) + .at(dependency.link.link_span)), + None => blocked.push(Diagnostic::error( + codes::LINK_MISSING, + format!("dependency `{}` was not verified in this run", dependency.link.url), + ) + .at(dependency.link.link_span)), + } + } + } + if !blocked.is_empty() { + let mut result = simple_result(Outcome::Blocked, scope, blocked); + result.freshness = Freshness::Unavailable; + return result; + } + // The backend identity is part of the cache identity; discover it first. + let lean = match context.lean() { + Ok(lean) => lean, + Err(failure) => { + return simple_result( + Outcome::Invalid, + scope, + vec![Diagnostic::error(failure.code, failure.message)], + ) + } + }; + let environment_id = lean.identity().environment_id.clone(); + // Cache identity over current sources, dependencies and environment. + let cache_key = match compute_cache_key(nodes, index, &environment_id) { + Ok(key) => key, + Err(diagnostic) => return simple_result(Outcome::Invalid, scope, vec![diagnostic]), + }; + let theorem_name = format!("marqdoTarget_{theorem_key}"); + let expected_name = format!("marqdoExpected_{theorem_key}"); + let model_sources: Vec = nodes[index] + .models + .iter() + .map(|model| model.source.clone()) + .collect(); + // Cache hit: still replay independently, never trust the stored flag. + if let Some(bundle) = context.cache.lookup(&cache_key) { + return replay_cached( + context, + nodes, + index, + &bundle, + &theorem_name, + &expected_name, + &model_sources, + scope, + ); + } + // Fresh proof search. + let dependency_names: Vec = nodes[index] + .theorem_dependencies + .iter() + .map(|dependency| format!("marqdoTarget_{}", nodes[*dependency].theorem_key)) + .collect(); + let imports: Vec = nodes[index] + .theorem_dependencies + .iter() + .map(|dependency| { + format!("MarqdoProof.Generated.Target_{}", nodes[*dependency].theorem_key) + }) + .collect(); + // Ensure every dependency artifact is importable. + for dependency in &nodes[index].theorem_dependencies { + let module = format!("MarqdoProof.Generated.Target_{}", nodes[*dependency].theorem_key); + if !lean.build_olean_path(&module).is_file() { + let artifact = context + .cache + .artifacts_dir() + .join(format!("{module}.olean")); + match std::fs::read(&artifact) { + Ok(bytes) => { + if let Err(failure) = lean.install_olean(&module, &bytes) { + return simple_result( + Outcome::Invalid, + scope, + vec![Diagnostic::error(failure.code, failure.message)], + ); + } + } + Err(_) => { + return simple_result( + Outcome::Invalid, + scope, + vec![Diagnostic::error( + codes::BACKEND_UNAVAILABLE, + format!( + "cached dependency artifact `{module}` is missing; delete \ + `.marqdo/prove` and re-run `check`" + ), + )], + ); + } + } + } + } + let variable_names: Vec = (0..nodes[index] + .goal + .as_ref() + .map(|goal| goal.vars.len()) + .unwrap_or(0)) + .map(|index| format!("mqx{index}")) + .collect(); + let hint_terms = build_hint_terms(nodes, index, &variable_names); + let attempt = ProofAttempt { + key: theorem_key.clone(), + statement_source: nodes[index].statement_source.clone(), + refuted: false, + witnesses: Vec::new(), + model_sources: model_sources.clone(), + imports, + dependency_names, + hint_terms, + variable_names: variable_names.clone(), + }; + match lean.attempt_proof(&attempt) { + Ok(Attempt::Proved(evidence)) => publish_success( + context, + nodes, + index, + scope, + Outcome::Verified, + evidence, + &theorem_key, + &theorem_name, + &expected_name, + &cache_key, + ), + Ok(Attempt::Exhausted { detail }) => { + // Sound refutation path: find a bounded counterexample candidate and + // let Lean prove the negation. + let candidates = counterexample_candidates(nodes[index].goal.as_ref()); + let mut exhausted = false; + for (trial, witnesses) in candidates.into_iter().enumerate() { + let _ = trial; + let refute = ProofAttempt { + key: theorem_key.clone(), + statement_source: nodes[index].statement_source.clone(), + refuted: true, + witnesses: witnesses + .iter() + .map(|value| value.to_string()) + .collect(), + model_sources: model_sources.clone(), + imports: Vec::new(), + dependency_names: Vec::new(), + hint_terms: Vec::new(), + variable_names: variable_names.clone(), + }; + match lean.attempt_proof(&refute) { + Ok(Attempt::Proved(evidence)) => { + return publish_success( + context, + nodes, + index, + scope, + Outcome::Refuted, + evidence, + &theorem_key, + &theorem_name, + &expected_name, + &cache_key, + ) + } + Ok(Attempt::Exhausted { .. }) => exhausted = true, + Err(failure) => { + return simple_result( + Outcome::Invalid, + scope, + vec![Diagnostic::error(failure.code, failure.message)], + ) + } + } + } + let _ = exhausted; + simple_result( + Outcome::Unknown, + scope, + vec![Diagnostic::error( + codes::PROOF_BUDGET, + format!("bounded proof strategy could not decide the goal: {detail}"), + ) + .at(nodes[index].loaded.proof_unit.goal.block_span) + .with_hint( + "add a verified theorem dependency or split the target into a smaller explicit \ + proposition; `unknown` is not a refutation", + )], + ) + } + Err(failure) => simple_result( + Outcome::Invalid, + scope, + vec![Diagnostic::error(failure.code, failure.message)], + ), + } +} + +fn replay_cached( + context: &mut Context, + nodes: &[PreparedNode], + index: usize, + bundle: &Bundle, + theorem_name: &str, + expected_name: &str, + model_sources: &[ModelSource], + scope: Scope, +) -> UnitResult { + let lean = match context.lean() { + Ok(lean) => lean, + Err(failure) => { + return simple_result( + Outcome::Invalid, + scope, + vec![Diagnostic::error(failure.code, failure.message)], + ) + } + }; + let refuted = bundle.manifest.target.outcome == "refuted"; + let result = lean.verify_payload( + &nodes[index].theorem_key, + &nodes[index].statement_source, + refuted, + model_sources, + &bundle.payload, + theorem_name, + expected_name, + ); + match result { + Ok(evidence) => { + // Install the artifact so later searches can import this theorem. + let module = format!("MarqdoProof.Generated.Target_{}", nodes[index].theorem_key); + let artifact = context.cache.artifacts_dir().join(format!("{module}.olean")); + if let Ok(bytes) = std::fs::read(&artifact) { + let _ = lean.install_olean(&module, &bytes); + } + let mut diagnostics = Vec::new(); + if bundle.manifest.target.statement_literal + != nodes[index].loaded.proof_unit.goal.literal + { + diagnostics.push(Diagnostic::error( + codes::CERTIFICATE_INVALID, + "cached bundle statement does not match the current source formula", + )); + return simple_result(Outcome::Invalid, scope, diagnostics); + } + let outcome = if refuted { + Outcome::Refuted + } else { + Outcome::Verified + }; + UnitResult { + outcome, + freshness: Freshness::Current, + scope, + used: map_project_decls(context, nodes, &evidence.used_project_decls), + transitive: map_project_decls(context, nodes, &evidence.project_decls), + axioms: evidence.axioms.clone(), + certificate: Some(CertificateReport { + cache_key: bundle.manifest.cache_key.clone(), + directory: bundle.directory.display().to_string(), + payload_sha256: bundle.manifest.proof.sha256.clone(), + outcome: bundle.manifest.target.outcome.clone(), + }), + evidence: Some(evidence), + manifest: Some(bundle.manifest.clone()), + diagnostics, + } + } + Err(failure) => simple_result( + Outcome::Invalid, + scope, + vec![Diagnostic::error(failure.code, failure.message).with_hint( + "the cached proof no longer replays against the current sources/environment; \ + delete `.marqdo/prove` and re-run `check`", + )], + ), + } +} + +#[allow(clippy::too_many_arguments)] +fn publish_success( + context: &mut Context, + nodes: &[PreparedNode], + index: usize, + scope: Scope, + outcome: Outcome, + evidence: Evidence, + theorem_key: &str, + theorem_name: &str, + expected_name: &str, + cache_key: &str, +) -> UnitResult { + let node = &nodes[index]; + let manifest = match build_manifest( + context, + nodes, + index, + scope, + outcome, + &evidence, + theorem_key, + theorem_name, + expected_name, + cache_key, + ) { + Ok(manifest) => manifest, + Err(failure) => { + return simple_result( + Outcome::Invalid, + scope, + vec![Diagnostic::error(failure.code, failure.message)], + ) + } + }; + if let Err(failure) = context.cache.publish(&manifest, &evidence.payload) { + return simple_result( + Outcome::Invalid, + scope, + vec![Diagnostic::error(failure.code, failure.message)], + ); + } + // Persist the compiled `.olean` as a local rebuild-free cache so dependent + // searches can import the verified theorem without re-running its search. + if let Ok(lean) = context.lean() { + let module = format!( + "MarqdoProof.Generated.{}_{}", + if outcome == Outcome::Refuted { "Refute" } else { "Target" }, + theorem_key + ); + if let Ok(bytes) = lean.read_olean(&module) { + let artifacts = context.cache.artifacts_dir(); + let _ = std::fs::create_dir_all(&artifacts); + let _ = std::fs::write(artifacts.join(format!("{module}.olean")), bytes); + } + } + UnitResult { + outcome, + freshness: Freshness::Current, + scope, + used: map_project_decls(context, nodes, &evidence.used_project_decls), + transitive: map_project_decls(context, nodes, &evidence.project_decls), + axioms: evidence.axioms.clone(), + certificate: Some(CertificateReport { + cache_key: manifest.cache_key.clone(), + directory: context.cache.bundle_dir(&manifest.cache_key).display().to_string(), + payload_sha256: manifest.proof.sha256.clone(), + outcome: manifest.target.outcome.clone(), + }), + evidence: Some(evidence), + manifest: Some(manifest), + diagnostics: Vec::new(), + } +} + +fn simple_result(outcome: Outcome, scope: Scope, diagnostics: Vec) -> UnitResult { + UnitResult { + outcome, + freshness: if outcome == Outcome::Verified { + Freshness::Current + } else { + Freshness::Unavailable + }, + scope, + evidence: None, + manifest: None, + diagnostics, + used: Vec::new(), + transitive: Vec::new(), + axioms: Vec::new(), + certificate: None, + } +} + +// --------------------------------------------------------------------------- +// identity, hints, counterexamples, manifests +// --------------------------------------------------------------------------- + +fn compute_cache_key( + nodes: &[PreparedNode], + index: usize, + environment_id: &str, +) -> std::result::Result { + let mut memo: HashMap = HashMap::new(); + let mut visiting: BTreeSet = BTreeSet::new(); + compute_cache_key_rec(nodes, index, environment_id, &mut memo, &mut visiting) +} + +fn compute_cache_key_rec( + nodes: &[PreparedNode], + index: usize, + environment_id: &str, + memo: &mut HashMap, + visiting: &mut BTreeSet, +) -> std::result::Result { + if let Some(key) = memo.get(&index) { + return Ok(key.clone()); + } + if !visiting.insert(index) { + return Err(Diagnostic::error( + codes::LINK_CYCLE, + "dependency cycle prevents a cache identity", + )); + } + let node = &nodes[index]; + let mut sources = vec![( + node.loaded.snapshot.relative_path.clone(), + node.loaded.module.source_digest.clone(), + node.loaded.snapshot.analysis_digest.clone(), + )]; + let mut declared = Vec::new(); + let mut models = Vec::new(); + for dependency in &node.loaded.dependencies { + match &dependency.target { + DependencyTarget::Theorem { + snapshot, + unit_id, + .. + } => { + let dependency_index = nodes.iter().position(|candidate| { + candidate.loaded.snapshot.canonical_path == snapshot.canonical_path + && candidate.loaded.proof_unit.unit_id == *unit_id + }); + let Some(dependency_index) = dependency_index else { + return Err(Diagnostic::error( + codes::LINK_INVALID, + format!("dependency `{}` is not in the closure", dependency.link.url), + )); + }; + let dependency_key = compute_cache_key_rec( + nodes, + dependency_index, + environment_id, + memo, + visiting, + )?; + sources.push(( + nodes[dependency_index].loaded.snapshot.relative_path.clone(), + nodes[dependency_index].loaded.module.source_digest.clone(), + nodes[dependency_index] + .loaded + .snapshot + .analysis_digest + .clone(), + )); + declared.push(( + "theorem".to_string(), + nodes[dependency_index].loaded.snapshot.relative_path.clone(), + unit_id.clone(), + dependency_key, + )); + } + DependencyTarget::Model { + snapshot, + function, + .. + } => { + if let Some(model) = node + .models + .iter() + .find(|model| model.definition.function_id == function.id) + { + models.push(( + model.definition.function_id.clone(), + model.definition.digest.clone(), + )); + declared.push(( + "model".to_string(), + snapshot.relative_path.clone(), + function.unit_id.clone(), + model.definition.key.clone(), + )); + sources.push(( + snapshot.relative_path.clone(), + snapshot.entry().source_digest.clone(), + snapshot.analysis_digest.clone(), + )); + } + } + } + } + visiting.remove(&index); + let identity = CacheIdentity { + target_locator: node.loaded.snapshot.relative_path.clone(), + target_unit_id: node.loaded.proof_unit.unit_id.clone(), + goal_digest: node.loaded.proof_unit.goal.digest.clone(), + scope: node.scope.as_str().to_string(), + sources, + environment_id: environment_id.to_string(), + declared, + models, + }; + let key = identity.cache_key(); + memo.insert(index, key.clone()); + Ok(key) +} + +fn build_hint_terms( + nodes: &[PreparedNode], + index: usize, + variable_names: &[String], +) -> Vec { + let mut terms: Vec = variable_names + .iter() + .map(|name| format!("sq_nonneg {name}")) + .collect(); + for dependency in &nodes[index].theorem_dependencies { + let dep = &nodes[*dependency]; + let Some(goal) = dep.goal.as_ref() else { + continue; + }; + if !goal.premises().is_empty() { + continue; + } + let arity = goal.vars.len(); + if arity == 0 || arity > variable_names.len() { + continue; + } + let application = format!( + "marqdoTarget_{} {}", + dep.theorem_key, + variable_names[..arity].join(" ") + ); + if !terms.contains(&application) { + terms.push(application); + } + } + terms +} + +fn counterexample_candidates(goal: Option<&Goal>) -> Vec> { + let Some(goal) = goal else { + return Vec::new(); + }; + const VALUES: [i64; 10] = [0, 1, -1, 2, -2, 3, -3, 5, -5, 10]; + let mut candidates = Vec::new(); + if goal.vars.is_empty() { + if let Some(value) = goal.evaluate(&[]) { + if !value { + candidates.push(Vec::new()); + } + } + return candidates; + } + if goal.vars.len() > 2 { + return candidates; + } + let mut budget = 16usize; + for first in VALUES { + for second in VALUES { + if budget == 0 { + break; + } + let values: Vec = if goal.vars.len() == 1 { + vec![BigInt::from(first)] + } else { + vec![BigInt::from(first), BigInt::from(second)] + }; + if goal.vars.len() == 2 && first != 0 && second != 0 { + // Still evaluate; combinations are bounded by the budget. + } + if let Some(false) = goal.evaluate(&values) { + candidates.push(values); + budget -= 1; + } + if goal.vars.len() == 1 { + break; + } + } + if budget == 0 { + break; + } + } + candidates +} + +// --------------------------------------------------------------------------- +// manifest construction +// --------------------------------------------------------------------------- + +#[allow(clippy::too_many_arguments)] +fn build_manifest( + context: &mut Context, + nodes: &[PreparedNode], + index: usize, + scope: Scope, + outcome: Outcome, + evidence: &Evidence, + theorem_key: &str, + theorem_name: &str, + expected_name: &str, + cache_key: &str, +) -> Result { + let node = &nodes[index]; + let lean = context.lean()?; + let environment = lean.identity().clone(); + let mut sources: BTreeMap = BTreeMap::new(); + let mut add_source = |locator: String, + module_id: String, + source_digest: String, + analysis_digest: String| { + sources + .entry(locator.clone()) + .or_insert(SourceBinding { + locator, + module_id, + source_digest, + analysis_digest, + }); + }; + add_source( + node.loaded.snapshot.relative_path.clone(), + node.loaded.module.id.clone(), + node.loaded.module.source_digest.clone(), + node.loaded.snapshot.analysis_digest.clone(), + ); + let mut declared_dependencies = Vec::new(); + for dependency in &node.loaded.dependencies { + match &dependency.target { + DependencyTarget::Theorem { + snapshot, + unit_id, + .. + } => { + let dependency_node = nodes.iter().find(|candidate| { + candidate.loaded.snapshot.canonical_path == snapshot.canonical_path + && candidate.loaded.proof_unit.unit_id == *unit_id + }); + let Some(dependency_node) = dependency_node else { + continue; + }; + add_source( + snapshot.relative_path.clone(), + dependency_node.loaded.module.id.clone(), + dependency_node.loaded.module.source_digest.clone(), + snapshot.analysis_digest.clone(), + ); + declared_dependencies.push(DeclaredDependency { + kind: "theorem".to_string(), + locator: format!( + "{}#{}", + snapshot.relative_path, + dependency_node + .loaded + .proof_unit + .path + .join("/") + ), + unit_id: unit_id.clone(), + link_text: dependency.link.text.clone(), + binding: format!("marqdoTarget_{}", dependency_node.theorem_key), + }); + } + DependencyTarget::Model { + snapshot, + function, + .. + } => { + add_source( + snapshot.relative_path.clone(), + snapshot.entry().id.clone(), + snapshot.entry().source_digest.clone(), + snapshot.analysis_digest.clone(), + ); + let model = node + .models + .iter() + .find(|model| model.definition.function_id == function.id); + if let Some(model) = model { + declared_dependencies.push(DeclaredDependency { + kind: "model".to_string(), + locator: format!("{}#{}", snapshot.relative_path, function.unit_id), + unit_id: function.unit_id.clone(), + link_text: dependency.link.text.clone(), + binding: model.definition.key.clone(), + }); + } + } + } + } + let mut sorted_declared = declared_dependencies; + sorted_declared.sort_by(|left, right| { + (left.kind.clone(), left.locator.clone()).cmp(&(right.kind.clone(), right.locator.clone())) + }); + let model_bindings: Vec = node + .models + .iter() + .map(|model| ModelBinding { + unit_id: model.definition.unit_id.clone(), + locator: model.definition.locator.clone(), + function_id: model.definition.function_id.clone(), + lean_name: model.definition.lean_name.clone(), + digest: model.definition.digest.clone(), + module_name: model.source.module_name.clone(), + semantics: model.definition.semantics.clone(), + }) + .collect(); + let goal = node + .goal + .as_ref() + .ok_or_else(|| crate::Failure::new(codes::DOCUMENT_GOAL_COUNT, "missing parsed goal"))?; + let manifest = BundleManifest { + schema: crate::PROOF_SCHEMA.to_string(), + schema_version: crate::PROOF_SCHEMA_VERSION, + tool: ToolIdentity { + name: crate::TOOL_NAME.to_string(), + version: env!("CARGO_PKG_VERSION").to_string(), + }, + target: TargetIdentity { + unit_id: node.loaded.proof_unit.unit_id.clone(), + unit_path: node.loaded.proof_unit.path.clone(), + locator: node.loaded.snapshot.relative_path.clone(), + scope: scope.as_str().to_string(), + outcome: outcome.as_str().to_string(), + statement_literal: node.loaded.proof_unit.goal.literal.clone(), + statement_normalized: goal.normal(), + statement_lean: node.statement_source.clone(), + goal_span: node.loaded.proof_unit.goal.block_span, + goal_payload_span: node.loaded.proof_unit.goal.payload_span, + goal_digest: node.loaded.proof_unit.goal.digest.clone(), + premises: goal.premises(), + theorem_name: theorem_name.to_string(), + expected_name: expected_name.to_string(), + model_definitions: model_bindings, + }, + sources: sources.into_values().collect(), + environment, + declared_dependencies: sorted_declared, + used_dependencies: map_project_decls(context, nodes, &evidence.used_project_decls), + transitive_dependencies: map_project_decls(context, nodes, &evidence.project_decls), + axioms: evidence.axioms.clone(), + proof: ProofPayload { + file: PAYLOAD_FILE.to_string(), + bytes: evidence.payload.len() as u64, + sha256: sha256_hex(&evidence.payload), + export_format: "lean4export-3.1.0".to_string(), + target_decl: theorem_name.to_string(), + expected_decl: expected_name.to_string(), + }, + cache_key: cache_key.to_string(), + }; + let _ = theorem_key; + Ok(manifest) +} + +/// Map internal Lean declaration names back to portable unit locators. +fn map_project_decls( + context: &mut Context, + nodes: &[PreparedNode], + decls: &[String], +) -> Vec { + let mut mapped = BTreeSet::new(); + let index_by_key: HashMap = nodes + .iter() + .map(|node| (node.theorem_key.clone(), node)) + .collect(); + for decl in decls { + if let Some(key) = decl.strip_prefix("marqdoTarget_") { + if let Some(node) = index_by_key.get(key) { + mapped.insert(format!( + "{}#{}", + node.loaded.snapshot.relative_path, + node.loaded.proof_unit.path.join("/") + )); + } + continue; + } + if let Some(key) = decl.strip_prefix("marqdoModel_") { + for node in nodes { + if let Some(model) = node + .models + .iter() + .find(|model| model.definition.key == key || model.definition.lean_name == *decl) + { + mapped.insert(format!( + "{}#{}", + model.definition.locator, + model.definition.function_id + )); + } + } + } + } + let _ = context; + mapped.into_iter().collect() +} + +// --------------------------------------------------------------------------- +// report assembly + bundle export +// --------------------------------------------------------------------------- + +fn build_target_report( + _context: &mut Context, + node: &PreparedNode, + result: &UnitResult, +) -> TargetReport { + let goal = node.goal.as_ref(); + let certificate = result.certificate.clone(); + let declared_dependencies = node + .loaded + .dependencies + .iter() + .map(|dependency| { + let binding = match &dependency.target { + DependencyTarget::Theorem { + snapshot, + unit_id, + .. + } => node + .theorem_dependencies + .iter() + .find(|index| { + let _ = index; + false + }) + .map(|_| String::new()) + .unwrap_or_else(|| { + let _ = (snapshot, unit_id); + String::new() + }), + DependencyTarget::Model { function, .. } => node + .models + .iter() + .find(|model| model.definition.function_id == function.id) + .map(|model| model.definition.key.clone()) + .unwrap_or_default(), + }; + DependencyReport { + kind: dependency.target.kind_name().to_string(), + link_text: dependency.link.text.clone(), + locator: dependency.target.locator(), + unit_id: dependency.target.unit_id().to_string(), + binding, + } + }) + .collect(); + TargetReport { + unit_id: node.loaded.proof_unit.unit_id.clone(), + locator: node.loaded.snapshot.relative_path.clone(), + title: node.loaded.proof_unit.title.clone(), + outcome: result.outcome.as_str().to_string(), + scope: result.scope.as_str().to_string(), + freshness: result.freshness.as_str().to_string(), + statement: StatementReport { + literal: node.loaded.proof_unit.goal.literal.clone(), + normalized: goal + .map(Goal::normal) + .unwrap_or_else(|| node.loaded.proof_unit.goal.literal.clone()), + lean: node.statement_source.clone(), + }, + source: SourceReport { + module_id: node.loaded.module.id.clone(), + locator: node.loaded.snapshot.relative_path.clone(), + unit_id: node.loaded.proof_unit.unit_id.clone(), + section_span: node.loaded.proof_unit.section_span, + goal_span: node.loaded.proof_unit.goal.block_span, + goal_payload_span: node.loaded.proof_unit.goal.payload_span, + }, + premises: goal.map(Goal::premises).unwrap_or_default(), + declared_dependencies, + used_dependencies: result.used.clone(), + transitive_dependencies: result.transitive.clone(), + axioms: result.axioms.clone(), + certificate, + diagnostics: result.diagnostics.iter().map(DiagnosticReport::from).collect(), + } +} + +fn export_bundles( + context: &mut Context, + nodes: &[PreparedNode], + outcomes: &HashMap, + out: &Path, + targets: &[TargetReport], +) -> Result<()> { + if targets.len() == 1 { + let target = &targets[0]; + if target.outcome != "verified" { + return Err(crate::Failure::new( + codes::CERTIFICATE_INVALID, + "--out requires every requested target to be verified; no bundle was exported", + )); + } + let index = nodes + .iter() + .position(|node| { + node.loaded.snapshot.relative_path == target.locator + && node.loaded.proof_unit.unit_id == target.unit_id + }) + .ok_or_else(|| { + crate::Failure::new(codes::CERTIFICATE_INVALID, "cannot locate the verified target") + })?; + let result = outcomes.get(&index).ok_or_else(|| { + crate::Failure::new(codes::CERTIFICATE_INVALID, "target has no verification result") + })?; + let manifest = result.manifest.as_ref().ok_or_else(|| { + crate::Failure::new(codes::CERTIFICATE_INVALID, "target has no proof manifest") + })?; + let evidence = result.evidence.as_ref().ok_or_else(|| { + crate::Failure::new(codes::CERTIFICATE_INVALID, "target has no proof payload") + })?; + let bundle = Bundle { + directory: context.cache.bundle_dir(&manifest.cache_key), + manifest: manifest.clone(), + payload: evidence.payload.clone(), + }; + return bundle.write_to(out); + } + if targets.iter().any(|target| target.outcome != "verified") { + return Err(crate::Failure::new( + codes::CERTIFICATE_INVALID, + "--out requires every requested target to be verified; no bundle was exported", + )); + } + std::fs::create_dir_all(out).map_err(|error| { + crate::Failure::new( + codes::CERTIFICATE_INVALID, + format!("cannot create --out directory: {error}"), + ) + })?; + for target in targets { + let index = nodes + .iter() + .position(|node| { + node.loaded.snapshot.relative_path == target.locator + && node.loaded.proof_unit.unit_id == target.unit_id + }) + .ok_or_else(|| { + crate::Failure::new(codes::CERTIFICATE_INVALID, "cannot locate the verified target") + })?; + let result = outcomes.get(&index).ok_or_else(|| { + crate::Failure::new(codes::CERTIFICATE_INVALID, "target has no verification result") + })?; + let manifest = result.manifest.as_ref().ok_or_else(|| { + crate::Failure::new(codes::CERTIFICATE_INVALID, "target has no proof manifest") + })?; + let evidence = result.evidence.as_ref().ok_or_else(|| { + crate::Failure::new(codes::CERTIFICATE_INVALID, "target has no proof payload") + })?; + let bundle = Bundle { + directory: context.cache.bundle_dir(&manifest.cache_key), + manifest: manifest.clone(), + payload: evidence.payload.clone(), + }; + let directory = out.join(&manifest.cache_key); + if directory.exists() { + std::fs::remove_dir_all(&directory).map_err(|error| { + crate::Failure::new( + codes::CERTIFICATE_INVALID, + format!("cannot replace exported bundle: {error}"), + ) + })?; + } + bundle.write_to(&directory)?; + } + Ok(()) +} + +// --------------------------------------------------------------------------- +// replay +// --------------------------------------------------------------------------- + +fn run_replay(options: ReplayOptions) -> Report { + let mut context = match open_context(&options.entry, options.root.as_deref()) { + Ok(context) => context, + Err(failure) => { + return failure_report( + "replay", + &options.entry, + options.root.as_deref().unwrap_or(Path::new(".")), + &failure, + ) + } + }; + let root = context.root.clone(); + match replay_inner(&mut context, &options) { + Ok(report) => report, + Err(failure) => failure_report("replay", &options.entry, &root, &failure), + } +} + +fn replay_inner(context: &mut Context, options: &ReplayOptions) -> Result { + let bundle = Bundle::load(&options.bundle)?; + let entry = context.linker.load_document(&options.entry)?; + let extraction = context.linker.extract_units(&entry); + // The bundle target must be a selected unit of the current entry document. + if bundle.manifest.target.locator != entry.relative_path { + return Ok(empty_report( + context, + "replay", + &entry, + RunStatus::Unverified, + vec![Diagnostic::error( + codes::CERTIFICATE_STALE, + format!( + "bundle target `{}` is not the replay entry `{}`", + bundle.manifest.target.locator, entry.relative_path + ), + )], + )); + } + let unit = extraction.iter().find_map(|candidate| match candidate { + Extraction::Unit(unit) if unit.unit_id == bundle.manifest.target.unit_id => Some(unit), + _ => None, + }); + let Some(unit) = unit else { + return Ok(empty_report( + context, + "replay", + &entry, + RunStatus::Unverified, + vec![Diagnostic::error( + codes::DOCUMENT_UNIT, + format!( + "bundle target unit `{}` does not exist in the current entry", + bundle.manifest.target.unit_id + ), + )], + )); + }; + let closure = context + .linker + .resolve_closure(&entry, &[unit.unit_id.clone()])?; + let mut diagnostics = closure.diagnostics.clone(); + let mut nodes = prepare_closure(&closure, &mut diagnostics); + let Some(index) = nodes.iter().position(|node| { + node.loaded.snapshot.relative_path == entry.relative_path + && node.loaded.proof_unit.unit_id == bundle.manifest.target.unit_id + }) else { + return Ok(empty_report( + context, + "replay", + &entry, + RunStatus::Unverified, + vec![Diagnostic::error( + codes::DOCUMENT_UNIT, + "bundle target unit is not part of the current dependency closure", + )], + )); + }; + if let Some(diagnostic) = nodes[index].prepared_error.clone() { + return Ok(empty_report( + context, + "replay", + &entry, + RunStatus::Unverified, + vec![diagnostic], + )); + } + // Recompute the content identity from the current sources/environment. + let lean = context.lean()?; + let environment_id = lean.identity().environment_id.clone(); + let current_key = match compute_cache_key(&nodes, index, &environment_id) { + Ok(key) => key, + Err(diagnostic) => { + return Ok(empty_report( + context, + "replay", + &entry, + RunStatus::Unverified, + vec![diagnostic], + )) + } + }; + if current_key != bundle.manifest.cache_key { + diagnostics.push(Diagnostic::error( + codes::CERTIFICATE_STALE, + format!( + "bundle is stale: expected cache key {}, current sources/environment give {}", + bundle.manifest.cache_key, current_key + ), + )); + let report = Report { + schema: RESULT_SCHEMA.to_string(), + schema_version: RESULT_SCHEMA_VERSION, + command: "replay".to_string(), + entry: entry.canonical_path.display().to_string(), + root: context.root.display().to_string(), + status: "unverified".to_string(), + targets: Vec::new(), + diagnostics: diagnostics.iter().map(DiagnosticReport::from).collect(), + }; + return Ok(report); + } + let model_sources: Vec = nodes[index] + .models + .iter() + .map(|model| model.source.clone()) + .collect(); + let refuted = bundle.manifest.target.outcome == "refuted"; + let theorem_name = format!("marqdoTarget_{}", nodes[index].theorem_key); + let expected_name = format!("marqdoExpected_{}", nodes[index].theorem_key); + let verified = lean.verify_payload( + &nodes[index].theorem_key, + &nodes[index].statement_source, + refuted, + &model_sources, + &bundle.payload, + &theorem_name, + &expected_name, + ); + let result = match verified { + Ok(evidence) => UnitResult { + outcome: if refuted { + Outcome::Refuted + } else { + Outcome::Verified + }, + freshness: Freshness::Current, + scope: nodes[index].scope, + used: map_project_decls(context, &nodes, &evidence.used_project_decls), + transitive: map_project_decls(context, &nodes, &evidence.project_decls), + axioms: evidence.axioms.clone(), + certificate: Some(CertificateReport { + cache_key: bundle.manifest.cache_key.clone(), + directory: bundle.directory.display().to_string(), + payload_sha256: bundle.manifest.proof.sha256.clone(), + outcome: bundle.manifest.target.outcome.clone(), + }), + evidence: Some(evidence), + manifest: Some(bundle.manifest.clone()), + diagnostics: Vec::new(), + }, + Err(failure) => { + diagnostics.push(Diagnostic::error( + codes::PROOF_REPLAY_FAILED, + format!("bundle payload did not replay: {}", failure.message), + )); + simple_result(Outcome::Invalid, nodes[index].scope, Vec::new()) + } + }; + let target = build_target_report(context, &nodes[index], &result); + Ok(Report { + schema: RESULT_SCHEMA.to_string(), + schema_version: RESULT_SCHEMA_VERSION, + command: "replay".to_string(), + entry: entry.canonical_path.display().to_string(), + root: context.root.display().to_string(), + status: if target.outcome == "verified" { + "success" + } else { + "unverified" + } + .to_string(), + targets: vec![target], + diagnostics: diagnostics.iter().map(DiagnosticReport::from).collect(), + }) +} + +/// Content key of one theorem: structured source identity plus goal digest. +pub fn theorem_key(locator: &str, path: &[String], goal_digest: &str) -> String { + let material = format!( + "marqdo-prove/theorem/v1\u{0}{}\u{0}{}\u{0}{}", + locator, + path.join("\u{1f}"), + goal_digest + ); + sha256_hex(material.as_bytes())[..20].to_string() +} + +/// Allowed axioms for reports/tests. +pub fn allowed_axioms() -> &'static [&'static str] { + &ALLOWED_AXIOMS +} + diff --git a/tests/formula_contract.rs b/tests/formula_contract.rs new file mode 100644 index 0000000..db22871 --- /dev/null +++ b/tests/formula_contract.rs @@ -0,0 +1,230 @@ +//! Contract tests for the restricted formula fragment (docs/DEVELOPMENT.md §4). +//! +//! These tests pin the *acceptance behaviour* of the only math parser in the +//! tool: grammar, precedence, bounds, diagnostics for unsupported constructs, +//! exact Lean target wording and exact normalized report wording. + +use std::collections::BTreeMap; + +use num_bigint::BigInt; + +fn int(value: i64) -> BigInt { + BigInt::from(value) +} + +use marqdo_prove::codes; +use marqdo_prove::formula::{self, IntExpr, PropExpr, Rel}; +use marqdo_prove::Span; + +fn parse(literal: &str) -> formula::Goal { + formula::parse(literal, Span::new(0, literal.len())).expect(literal) +} + +fn lean(goal: &formula::Goal) -> String { + goal.lean_prop(&BTreeMap::new()).expect("lean") +} + +#[test] +fn fixture_vector_proposition() { + let goal = parse("\\forall x,y\\in\\mathbb{Z},\\quad x^2+y^2\\geq0\n"); + assert_eq!(goal.vars, vec!["x", "y"]); + assert_eq!( + lean(&goal), + "∀ mqx0 mqx1 : Int, (((mqx0 ^ (2 : Nat)) + (mqx1 ^ (2 : Nat))) ≥ (0 : Int))" + ); + assert_eq!(goal.normal(), "∀ x y : ℤ, x^2 + y^2 ≥ 0"); + assert!(goal.premises().is_empty()); + assert_eq!(goal.evaluate(&[int(3), int(-4)]), Some(true)); +} + +#[test] +fn fixture_nonnegative_addition_preserves_premises() { + let goal = parse("\\forall a,b\\in\\mathbb{Z},\\quad (a\\geq0\\land b\\geq0)\\Rightarrow a+b\\geq0"); + assert_eq!(goal.vars, vec!["a", "b"]); + assert_eq!( + lean(&goal), + "∀ mqx0 mqx1 : Int, (((mqx0 ≥ (0 : Int)) ∧ (mqx1 ≥ (0 : Int))) → \ + ((mqx0 + mqx1) ≥ (0 : Int)))" + ); + assert_eq!( + goal.normal(), + "∀ a b : ℤ, (a ≥ 0 ∧ b ≥ 0) → a + b ≥ 0" + ); + assert_eq!(goal.premises(), vec!["a ≥ 0 ∧ b ≥ 0"]); + assert_eq!(goal.evaluate(&[int(-2), int(1)]), Some(true)); +} + +#[test] +fn precedence_unary_minus_and_power() { + let goal = parse("\\forall x\\in\\mathbb{Z},\\quad -x^2\\leq0"); + assert_eq!( + lean(&goal), + "∀ mqx0 : Int, ((- (mqx0 ^ (2 : Nat))) ≤ (0 : Int))" + ); + let goal = parse("\\forall x\\in\\mathbb{Z},\\quad (-x)^2\\geq0"); + assert_eq!( + lean(&goal), + "∀ mqx0 : Int, (((- mqx0) ^ (2 : Nat)) ≥ (0 : Int))" + ); +} + +#[test] +fn associativity_and_bracing() { + let goal = parse("\\forall a,b,c\\in\\mathbb{Z},\\quad a-b-c=a-(b-c)"); + assert_eq!( + lean(&goal), + "∀ mqx0 mqx1 mqx2 : Int, (((mqx0 - mqx1) - mqx2) = (mqx0 - (mqx1 - mqx2)))" + ); + let goal = parse(r"(1=1)\Rightarrow(2=2)\Rightarrow(3=3)"); + // Right-associative implication: a=1 → (b=2 → c=3). + match &goal.body { + PropExpr::Imp(_, right) => assert!(matches!(**right, PropExpr::Imp(_, _))), + other => panic!("expected implication, got {other:?}"), + } + let goal = parse("\\forall a,b\\in\\mathbb{Z},\\quad (a=1)\\land(b=2)"); + match &goal.body { + PropExpr::And(left, right) => { + assert!(matches!(**left, PropExpr::Cmp(Rel::Eq, _, _))); + assert!(matches!(**right, PropExpr::Cmp(Rel::Eq, _, _))); + } + other => panic!("expected conjunction, got {other:?}"), + } +} + +#[test] +fn exponent_rules() { + let goal = parse("\\forall x\\in\\mathbb{Z},\\quad x^{12}\\geq0"); + assert_eq!( + lean(&goal), + "∀ mqx0 : Int, ((mqx0 ^ (12 : Nat)) ≥ (0 : Int))" + ); + let error = formula::parse("\\forall x\\in\\mathbb{Z},\\quad x^12\\geq0", Span::new(0, 1)) + .unwrap_err(); + assert_eq!(error.code(), codes::FORMULA_SYNTAX, "{error:?}"); + let error = formula::parse("\\forall x\\in\\mathbb{Z},\\quad x^{17}\\geq0", Span::new(0, 1)) + .unwrap_err(); + assert_eq!(error.code(), codes::FORMULA_UNSUPPORTED, "{error:?}"); + let error = formula::parse("\\forall x\\in\\mathbb{Z},\\quad x^{999999999}\\geq0", Span::new(0, 1)) + .unwrap_err(); + assert_eq!(error.code(), codes::FORMULA_UNSUPPORTED, "{error:?}"); +} + +#[test] +fn unsupported_and_invalid_inputs_are_rejected() { + let cases: &[(&str, &str)] = &[ + ("x^2\\geq0", codes::FORMULA_FREE_VARIABLE), + ("\\forall x\\in\\mathbb{R}, x^2\\geq0", codes::FORMULA_UNSUPPORTED), + ("\\forall x\\in\\mathbb{N}, x^2\\geq0", codes::FORMULA_UNSUPPORTED), + ("\\forall x\\in\\mathbb{Z}, 2x\\geq0", codes::FORMULA_SYNTAX), + ("\\forall x\\in\\mathbb{Z}, 0>(), + vec!["square".to_string()] + ); + let mut aliases = BTreeMap::new(); + aliases.insert("square".to_string(), "marqdoModel_ab12".to_string()); + assert_eq!( + goal.lean_prop(&aliases).unwrap(), + "∀ mqx0 : Int, ((marqdoModel_ab12 mqx0) ≥ (0 : Int))" + ); + assert_eq!(goal.normal(), "∀ x : ℤ, square(x) ≥ 0"); + let error = formula::parse( + "\\forall x\\in\\mathbb{Z},\\quad \\operatorname{f}(x,\\operatorname{g}(x))\\geq0", + Span::new(0, 1), + ) + .unwrap(); + assert_eq!(error.used_aliases().len(), 2); + assert!(error.evaluate(&[int(1)]).is_none()); +} + +#[test] +fn evaluate_is_exact_arbitrary_precision() { + let goal = parse("\\forall x\\in\\mathbb{Z},\\quad x\\cdot x\\geq0"); + assert_eq!(goal.evaluate(&[int(0)]), Some(true)); + assert_eq!(goal.evaluate(&[int(-123456789)]), Some(true)); + let goal = parse("\\forall x\\in\\mathbb{Z},\\quad x^2<0"); + assert_eq!(goal.evaluate(&[int(0)]), Some(false)); + assert_eq!(goal.evaluate(&["9".repeat(200).parse().unwrap()]), Some(false)); + let goal = parse("\\forall a,b\\in\\mathbb{Z},\\quad (a>0\\land b>0)\\Rightarrow a\\cdot b>0"); + assert_eq!( + goal.evaluate(&[int(2), int(3)]), + Some(true) + ); + // If the antecedent fails, the conditional proposition is vacuously true; + // this is exactly why reports preserve and display the whole premise. + assert_eq!(goal.evaluate(&[int(0), int(3)]), Some(true)); + let implication = parse("\\forall a\\in\\mathbb{Z},\\quad a>0\\Rightarrow a>10"); + assert_eq!(implication.evaluate(&[int(5)]), Some(false)); + assert_eq!(implication.evaluate(&[int(0)]), Some(true)); + assert_eq!(goal.evaluate(&[int(1)]), None); +} + +#[test] +fn typed_ast_is_public_and_structural() { + let goal = parse("\\forall x\\in\\mathbb{Z},\\quad x\\geq0"); + match &goal.body { + PropExpr::Cmp(Rel::Ge, left, right) => { + assert!(matches!(left, IntExpr::Var(0))); + assert!(matches!(right, IntExpr::Lit(value) if value == &0.into())); + } + other => panic!("unexpected AST {other:?}"), + } + assert!(goal.is_universally_quantified()); +} + +#[test] +fn closed_propositions_are_supported() { + let goal = parse("(2+3)\\cdot4=20"); + assert!(goal.vars.is_empty()); + assert_eq!(lean(&goal), "((((2 : Int) + (3 : Int)) * (4 : Int)) = (20 : Int))"); + assert_eq!(goal.evaluate(&[]), Some(true)); + assert_eq!(goal.normal(), "(2 + 3) · 4 = 20"); +} diff --git a/tool.json b/tool.json new file mode 100644 index 0000000..fe87652 --- /dev/null +++ b/tool.json @@ -0,0 +1,12 @@ +{ + "schema": "marqdo.cli-tool", + "schema_version": 1, + "name": "marqdo.prove", + "version": "0.1.0", + "command": "prove", + "entrypoint": "bin/marqdo-prove", + "requires": { + "api_revision": 1, + "analysis": 3 + } +}