tests+docs: contract fixtures, Lean-backed acceptance suite and executed status
- document_contract: negative path coverage through the real CLI (selection, shape errors, formula unsupported/invalid, missing/external links, cycles, --unit, upstream static failure, root escape) with exit-code assertions - e2e: algebra, vector composition (declared == used), program model scope, refutation, export+replay, cache reuse, tampered payload rejection - report fixes: declared/used locator consistency, diagnostic-only exit status, unsupported vs invalid formula outcomes - clippy -D warnings and cargo fmt clean; docs/STATUS records pinned identities, executed commands, measured backend limits and known gaps
This commit is contained in:
1 parent
4e02da95a4
commit
bd7e46b208
46 files changed
+390180
-460
No files matched your search
@@ -51,6 +51,9 @@ capability.
|
|||||||
payload SHA-256. A cache hit is replayed, never trusted.
|
payload SHA-256. A cache hit is replayed, never trusted.
|
||||||
* **CLI**: `check` and `replay` only. Exit codes: 0 all requested targets
|
* **CLI**: `check` and `replay` only. Exit codes: 0 all requested targets
|
||||||
verified (or no target), 1 at least one not verified, 2 engineering failure.
|
verified (or no target), 1 at least one not verified, 2 engineering failure.
|
||||||
|
`--out` with exactly one requested target makes that directory the bundle;
|
||||||
|
with several targets it writes one self-contained bundle directory per target
|
||||||
|
under `PATH/<cache_key>/`.
|
||||||
|
|
||||||
## What it deliberately does not do
|
## What it deliberately does not do
|
||||||
|
|
||||||
@@ -100,6 +103,12 @@ lake exe cache get
|
|||||||
lake build marqdo-replay
|
lake build marqdo-replay
|
||||||
```
|
```
|
||||||
|
|
||||||
|
The pinned backend needs real address space: on the recorded machine a low
|
||||||
|
`RLIMIT_AS` fails during Mathlib loading (6 GiB and 9 GiB were measured failing,
|
||||||
|
12 GiB succeeds), so Prove bounds Lean by wall-clock/CPU budgets instead of an
|
||||||
|
address-space rlimit. This and the other measured limitations are recorded in
|
||||||
|
[`docs/STATUS.md`](docs/STATUS.md).
|
||||||
|
|
||||||
`marqdo-prove` never downloads anything at runtime. It discovers the backend
|
`marqdo-prove` never downloads anything at runtime. It discovers the backend
|
||||||
via `MARQDO_PROVE_LEAN_ROOT` (the `lean/` directory) and
|
via `MARQDO_PROVE_LEAN_ROOT` (the `lean/` directory) and
|
||||||
`MARQDO_PROVE_LEAN_BIN_DIR` (the toolchain `bin` directory); see
|
`MARQDO_PROVE_LEAN_BIN_DIR` (the toolchain `bin` directory); see
|
||||||
@@ -120,14 +129,16 @@ cargo run --release -- replay examples/vector.mq.md /tmp/vector-proof
|
|||||||
|
|
||||||
```sh
|
```sh
|
||||||
cargo fmt --all -- --check
|
cargo fmt --all -- --check
|
||||||
cargo clippy --workspace --all-targets --locked -- -D warnings
|
cargo clippy --all-targets -- -D warnings
|
||||||
cargo test --workspace --locked
|
cargo test
|
||||||
|
|
||||||
|
# Lean-backed acceptance tests (real CLI + pinned backend, ignored by default)
|
||||||
|
MARQDO_BIN=/path/to/marqdo cargo test --test e2e -- --ignored --test-threads=1
|
||||||
```
|
```
|
||||||
|
|
||||||
Real-CLI tests read `MARQDO_BIN`; they skip (and say so) when it is not set.
|
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
|
Lean-backed end-to-end tests additionally require the backend above; see
|
||||||
marked `#[ignore]` when they need large machinery; see `docs/STATUS.md` for the
|
`docs/STATUS.md` for the exact commands executed and their observed output.
|
||||||
exact commands executed.
|
|
||||||
|
|
||||||
## Exit codes and output
|
## Exit codes and output
|
||||||
|
|
||||||
|
|||||||
+181
@@ -0,0 +1,181 @@
|
|||||||
|
# STATUS: executed evidence for marqdo-prove
|
||||||
|
|
||||||
|
This file records what has actually been executed and observed. It is not a
|
||||||
|
plan, not a test report template, and not a release announcement. Anything not
|
||||||
|
listed here is unverified, regardless of what `docs/DEVELOPMENT.md` describes as
|
||||||
|
the target design.
|
||||||
|
|
||||||
|
## Snapshot
|
||||||
|
|
||||||
|
| Item | Value |
|
||||||
|
| --- | --- |
|
||||||
|
| Repository | `marqdo-prove` (this tree) |
|
||||||
|
| Commit at evidence time | `4e02da9` + reporting/tests working tree (see `git log`) |
|
||||||
|
| Prove version | `0.1.0` |
|
||||||
|
| Tool manifest | `tool.json`: `requires.api_revision: 1`, `requires.analysis: 3` |
|
||||||
|
| Platform | Linux x86_64, 8 vCPU, 14 GiB RAM, no network during checks |
|
||||||
|
| Rust | `rustc 1.100.0` / `cargo 1.100.0` (local toolchain) |
|
||||||
|
| Upstream CLI | Marqdo `3.0.0-rc.4` (`marqdo-cli` commit `4bbefc9`, release binary) |
|
||||||
|
| Analysis contract | `marqdo.analysis` `schema_version: 3` (the merged public Analysis boundary, ADR-0069), consumed only through `check --emit` |
|
||||||
|
|
||||||
|
## Fixed Lean backend
|
||||||
|
|
||||||
|
Pinned in `lean/lean-toolchain` and `lean/lake-manifest.json` (both committed):
|
||||||
|
|
||||||
|
| Item | Value |
|
||||||
|
| --- | --- |
|
||||||
|
| Lean toolchain | `leanprover/lean4:v4.36.0` |
|
||||||
|
| Lean binary | `Lean (version 4.36.0, x86_64-unknown-linux-gnu, commit 611c117bfaf7b7ae1cfcf246ce6fba31e8f509e9, Release)` |
|
||||||
|
| Lake | `5.0.0-src+611c117` |
|
||||||
|
| Mathlib revision | `fc4f59e577feb1a4956671bc04ac18aaaf8cd842` (`mathlib4` tag `v4.36.0`) |
|
||||||
|
| `lake-manifest.json` SHA-256 | `bb82472009ad8aba44b75c1a1095dfe290dd87319421d55039e02fe57f2e0022` |
|
||||||
|
| `marqdo-replay` binary SHA-256 | `02cbc2c8b00dbdac2c5bcf359b25a62f896372b9964f7578caca4d4346d544c1` |
|
||||||
|
| official `con-leche` SHA-256 | `a6380d68b4fb364189821dd4692569c11536de0a1e3aaefea06028c0d67bb193` |
|
||||||
|
| Mathlib oleans | fetched once with `lake exe cache get` (9117 files); no runtime download |
|
||||||
|
|
||||||
|
Backend discovery: `MARQDO_PROVE_LEAN_ROOT` (the `lean/` project) and
|
||||||
|
`MARQDO_PROVE_LEAN_BIN_DIR` (toolchain `bin`); a development checkout falls back
|
||||||
|
to `<repo>/lean` and `<repo>/.tool/lean/bin`. Missing backend or verifier is a
|
||||||
|
`backend.unavailable` engineering failure (exit 2), never silent degradation.
|
||||||
|
|
||||||
|
### Measured backend constraint (important)
|
||||||
|
|
||||||
|
Lean + Mathlib cannot run under a low `RLIMIT_AS` on this machine: 6 GiB fails
|
||||||
|
with `failed to read ... *.olean.private`, 9 GiB fails with
|
||||||
|
`failed to create thread`, 12 GiB succeeds. Prove therefore does **not** apply an
|
||||||
|
address-space rlimit; elaboration is bounded by the 30 s per-attempt wall clock,
|
||||||
|
the 300 s CPU rlimit and the overall task timeout. A true RSS/cgroup cap remains
|
||||||
|
unimplemented and is a known release gap (docs/DEVELOPMENT.md §13.1 asks for
|
||||||
|
2 GiB). This was measured, not assumed.
|
||||||
|
|
||||||
|
## Proof pipeline as executed
|
||||||
|
|
||||||
|
`marqdo prove check examples/vector.mq.md`:
|
||||||
|
|
||||||
|
1. real CLI emits Analysis revision 3 for the entry (and, per link, for each
|
||||||
|
local dependency document, through a second `check --emit`);
|
||||||
|
2. one Knowledge H2 target is selected; two dependency links resolve exactly to
|
||||||
|
the two algebra theorems; the closure is acyclic and dependency-first;
|
||||||
|
3. the goal compiles to
|
||||||
|
`∀ mqx0 mqx1 : Int, ((mqx0 ^ (2 : Nat)) + (mqx1 ^ (2 : Nat)) ≥ (0 : Int))`;
|
||||||
|
4. the bounded fixed template (`solve_by_elim` over the declared theorem
|
||||||
|
constants, then `omega`/`positivity`/`decide`/`nlinarith`) finds a proof
|
||||||
|
term; the search process exports the proof-term closure with the stock
|
||||||
|
`leanexport` tool;
|
||||||
|
5. the verifier independently (a) kernel-replays the whole closure with the
|
||||||
|
toolchain's `con-leche --verified`, (b) re-elaborates the expected
|
||||||
|
proposition from the current sources in a *separate* process without the
|
||||||
|
proof, (c) checks alpha-equivalence of the target theorem type with the
|
||||||
|
expected prop, rejects metavariables, and (d) enforces the axiom set
|
||||||
|
`propext`, `Classical.choice`, `Quot.sound`;
|
||||||
|
6. the bundle is published under
|
||||||
|
`examples/.marqdo/prove/bundles/<sha256>/manifest.json` + `proof.ndjson`;
|
||||||
|
7. the report distinguishes declared vs actually used dependencies. For the
|
||||||
|
`vector` fixture, the exported proof term genuinely references **both**
|
||||||
|
algebra theorems (not merely `positivity`).
|
||||||
|
|
||||||
|
Observed results (wall clock, warm filesystem, debug build of Prove):
|
||||||
|
|
||||||
|
| Command | Result |
|
||||||
|
| --- | --- |
|
||||||
|
| `check examples/algebra.mq.md` | 2 targets `verified`, `mathematical`, `current`, axioms ⊆ allowed; ~24 s |
|
||||||
|
| `check examples/vector.mq.md` | 1 target `verified`; 2 declared, 2 used, 0 unused; ~23 s |
|
||||||
|
| `check examples/arithmetic.mq.md` | 1 target `verified`, `scope=program_model`, real `@[expose]` model definition checked; ~24 s |
|
||||||
|
| `check tests/fixtures/false.mq.md` | 2 targets `refuted` via Lean-proven negations with concrete witnesses; exit 1; ~28 s |
|
||||||
|
| `check examples/vector.mq.md --out DIR` then `replay examples/vector.mq.md DIR` | export contains `manifest.json` + `proof.ndjson`; replay `verified`/`current`, no search, exit 0 |
|
||||||
|
| repeated `check examples/algebra.mq.md` | same content-addressed cache key; hit is replayed, not trusted, `freshness=current` |
|
||||||
|
| tampered `proof.ndjson` then `replay` | rejected with exit 2 (`certificate.invalid`), no `verified` |
|
||||||
|
|
||||||
|
Run as `cargo test --test e2e -- --ignored --test-threads=1` (requires
|
||||||
|
`MARQDO_BIN` and the fixed backend): **7 passed, 0 failed, 166.77 s**.
|
||||||
|
|
||||||
|
## Executed test suite
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cargo fmt --all -- --check # passed
|
||||||
|
cargo clippy --all-targets -- -D warnings # passed, no warnings
|
||||||
|
cargo test # see counts below
|
||||||
|
```
|
||||||
|
|
||||||
|
| Suite | Result |
|
||||||
|
| --- | --- |
|
||||||
|
| library unit tests (`analysis`, `document`, `formula`, `linker`, `model`, `lean`, `certificate`) | 69 passed |
|
||||||
|
| `tests/analysis_document.rs` (real CLI, entry extraction) | 3 passed |
|
||||||
|
| `tests/formula_contract.rs` (grammar, precedence, bounds, diagnostics, rendering, evaluation) | 12 passed |
|
||||||
|
| `tests/document_contract.rs` (no-target, shape errors, unsupported/invalid formulas, missing/external links, cycles, `--unit`, upstream static failure, root escape) | 11 passed |
|
||||||
|
| `tests/e2e.rs` (Lean-backed, `#[ignore]`) | 7 passed, 166.77 s |
|
||||||
|
|
||||||
|
## Verified behaviours (with fixtures)
|
||||||
|
|
||||||
|
- no `证明依赖` heading → `no_targets`, exit 0, no proof search;
|
||||||
|
- 0/2 direct display goals → `document.goal_count`, exit 1;
|
||||||
|
- dependency list with extra text / not a plain link list → `document.dependencies_shape`;
|
||||||
|
- `\mathbb{R}` / fractions / existence → `unsupported` (`formula.unsupported`), source kept readable;
|
||||||
|
- free variables, chained comparisons, implicit multiplication, trailing tokens, oversized literals/exponents/variable counts → `formula.syntax`/`formula.free_variable`, nothing sent to Lean;
|
||||||
|
- missing link target → `link.missing`; external URL → `link.invalid`; A→B→A cycle → `link.cycle` with a concrete chain;
|
||||||
|
- `--unit` with an unknown fragment → exit 1 with `document.unit`;
|
||||||
|
- upstream CLI static error → `upstream.contract`, exit 2, no raw-Markdown fallback;
|
||||||
|
- `--root` outside the entry → `link.outside_root`, exit 2;
|
||||||
|
- program model with unsupported constructs (`/`, loops, branches, calls, non-Int params, defaults) → `model.unsupported` before any Lean search;
|
||||||
|
- `refuted` only after Lean kernel-verified `¬expected` (bounded witness candidates: 0, ±1, ±2, ±3, ±5, ±10, ≤16 trials);
|
||||||
|
- `--out` with multiple requested targets writes one self-contained bundle
|
||||||
|
directory per target under `PATH/<cache_key>/`; with one target `PATH` is the
|
||||||
|
bundle directory itself.
|
||||||
|
|
||||||
|
## Known gaps (not claimed as done)
|
||||||
|
|
||||||
|
1. **Resource isolation**: no cgroup/RSS cap; address-space rlimit disabled for
|
||||||
|
the measured reason above. Network isolation is not enforced by a sandbox
|
||||||
|
namespace — the backend cannot reach the network in the executed environment,
|
||||||
|
but that is an environmental fact, not a code guarantee.
|
||||||
|
2. **M4 release evidence**: no clean-machine installation run, no CI evidence at
|
||||||
|
a single SHA, no signed archive/digest publication, no performance P50/P95
|
||||||
|
matrix, and no `--out` cross-checkout replay on a second host.
|
||||||
|
3. **Search strength**: fixed template only. Goals outside
|
||||||
|
`solve_by_elim`+`omega`/`positivity`/`decide`/`nlinarith` yield `unknown`.
|
||||||
|
The evaluation corpus required by §13.1 (40 positive/20 false/20 negative
|
||||||
|
fixtures) is not yet assembled; the committed examples are a first subset.
|
||||||
|
4. **Conditional premises**: the whole antecedent is preserved and displayed,
|
||||||
|
but premise non-emptiness is explicitly *not* proven (reported as such).
|
||||||
|
Contradictory premises can therefore verify vacuously; there is no
|
||||||
|
satisfiability check.
|
||||||
|
5. **Program model**: only the documented straight-line `Int` subset. No claim
|
||||||
|
of runtime refinement (`runtime_verified` is not a supported status).
|
||||||
|
6. **Upstream coupling**: the local `marqdo-cli` tree at `3.0.0-rc.4` happens to
|
||||||
|
contain the merged Analysis revision 3; the document's original audit SHA
|
||||||
|
(`e6066e6`) does not. Prove accepts only revision 3 and has no compatibility
|
||||||
|
reader, as required.
|
||||||
|
7. **Replay model**: the payload is a self-contained `lean4export` closure
|
||||||
|
(project declarations plus the used Mathlib closure), replayed with
|
||||||
|
`con-leche --verified`; the bundle additionally requires the same pinned
|
||||||
|
backend to re-elaborate the expected proposition. Cross-Lean-version replay
|
||||||
|
is not supported.
|
||||||
|
8. **`--out` bundle set**: one target per bundle manifest; a multi-target
|
||||||
|
project exports one bundle per target (no combined multi-target bundle yet).
|
||||||
|
|
||||||
|
## Reproduce
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# 1. upstream CLI (real, current Analysis contract)
|
||||||
|
export MARQDO_BIN=/path/to/marqdo-3.0.0-rc.4
|
||||||
|
|
||||||
|
# 2. pinned backend (one-time; needs network)
|
||||||
|
cd lean && lake update && lake exe cache get && lake build marqdo-replay && cd ..
|
||||||
|
export MARQDO_PROVE_LEAN_ROOT="$PWD/lean"
|
||||||
|
export MARQDO_PROVE_LEAN_BIN_DIR=/path/to/lean-toolchain/bin
|
||||||
|
|
||||||
|
# 3. fast suites
|
||||||
|
cargo fmt --all -- --check
|
||||||
|
cargo clippy --all-targets -- -D warnings
|
||||||
|
cargo test
|
||||||
|
|
||||||
|
# 4. real end-to-end
|
||||||
|
cargo test --test e2e -- --ignored --test-threads=1
|
||||||
|
cargo run --release -- check examples/vector.mq.md --json
|
||||||
|
```
|
||||||
|
|
||||||
|
## What this file is not
|
||||||
|
|
||||||
|
It is not a claim that the first release gates in `docs/DEVELOPMENT.md` §13–§14
|
||||||
|
are satisfied. It records the executed subset above, including the failures to
|
||||||
|
meet the full gate list.
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Evidence index
|
||||||
|
|
||||||
|
Executed evidence for this tree lives in [`../STATUS.md`](../STATUS.md). It
|
||||||
|
records the pinned toolchain and Mathlib identities, the exact commands run, the
|
||||||
|
observed results, the measured backend constraint on `RLIMIT_AS`, and the known
|
||||||
|
gaps against the release gates.
|
||||||
|
|
||||||
|
There is intentionally no `PASS` file here: status is derived from the commands
|
||||||
|
in `STATUS.md`, not from a checked-in verdict. A future release candidate should
|
||||||
|
add a same-SHA record (CI link, archive digest, clean-install transcript,
|
||||||
|
performance measurements) to this directory.
|
||||||
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
+72
@@ -0,0 +1,72 @@
|
|||||||
|
{
|
||||||
|
"schema": "marqdo.proof",
|
||||||
|
"schema_version": 1,
|
||||||
|
"tool": {
|
||||||
|
"name": "marqdo-prove",
|
||||||
|
"version": "0.1.0"
|
||||||
|
},
|
||||||
|
"target": {
|
||||||
|
"unit_id": "root:default::algebra.mq.md#基础代数/整数平方非负性",
|
||||||
|
"unit_path": [
|
||||||
|
"基础代数",
|
||||||
|
"整数平方非负性"
|
||||||
|
],
|
||||||
|
"locator": "algebra.mq.md",
|
||||||
|
"scope": "mathematical",
|
||||||
|
"outcome": "verified",
|
||||||
|
"statement_literal": "\\forall x\\in\\mathbb{Z},\\quad x^2\\geq 0\n",
|
||||||
|
"statement_normalized": "∀ x : ℤ, x^2 ≥ 0",
|
||||||
|
"statement_lean": "∀ mqx0 : Int, ((mqx0 ^ (2 : Nat)) ≥ (0 : Int))",
|
||||||
|
"goal_span": {
|
||||||
|
"start": 88,
|
||||||
|
"end": 132
|
||||||
|
},
|
||||||
|
"goal_payload_span": {
|
||||||
|
"start": 91,
|
||||||
|
"end": 130
|
||||||
|
},
|
||||||
|
"goal_digest": "08340b3ea68d6027d14ea100cd1c66a60ec79b51427d69eb041d1b5297c66b5e",
|
||||||
|
"premises": [],
|
||||||
|
"theorem_name": "marqdoTarget_56304010d2fd7740d17a",
|
||||||
|
"expected_name": "marqdoExpected_56304010d2fd7740d17a",
|
||||||
|
"model_definitions": []
|
||||||
|
},
|
||||||
|
"sources": [
|
||||||
|
{
|
||||||
|
"locator": "algebra.mq.md",
|
||||||
|
"module_id": "root:default::algebra.mq.md",
|
||||||
|
"source_digest": "ed9a14ef1e695605743cffac56066dbf8cb13200c0a0537084f2c65157195b22",
|
||||||
|
"analysis_digest": "1a1b1a237a43368284ccc39d01e46ec2789d5ed878b897241c8d402ae541e2f9"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"environment": {
|
||||||
|
"lean_toolchain": "leanprover/lean4:v4.36.0",
|
||||||
|
"lean_version": "86_64",
|
||||||
|
"mathlib_rev": "fc4f59e577feb1a4956671bc04ac18aaaf8cd842",
|
||||||
|
"lake_manifest_digest": "bb82472009ad8aba44b75c1a1095dfe290dd87319421d55039e02fe57f2e0022",
|
||||||
|
"replay_verifier_digest": "02cbc2c8b00dbdac2c5bcf359b25a62f896372b9964f7578caca4d4346d544c1",
|
||||||
|
"con_leche_version": "con-leche-a6380d68b4fb3641",
|
||||||
|
"formula_compiler": "marqdo-prove-0.1.0",
|
||||||
|
"semantic_mapping": "marqdo-int-exact-v1",
|
||||||
|
"environment_id": "9622d44bfc5540616117b8e4b60b3e06a84122535d4495925739a08acc14877a"
|
||||||
|
},
|
||||||
|
"declared_dependencies": [],
|
||||||
|
"used_dependencies": [],
|
||||||
|
"transitive_dependencies": [
|
||||||
|
"algebra.mq.md#基础代数/整数平方非负性"
|
||||||
|
],
|
||||||
|
"axioms": [
|
||||||
|
"Classical.choice",
|
||||||
|
"Quot.sound",
|
||||||
|
"propext"
|
||||||
|
],
|
||||||
|
"proof": {
|
||||||
|
"file": "proof.ndjson",
|
||||||
|
"bytes": 3713445,
|
||||||
|
"sha256": "264138ec6f095b4162b1ea2691f86ad0d06c70ac20b056352f99885b21226db1",
|
||||||
|
"export_format": "lean4export-3.1.0",
|
||||||
|
"target_decl": "marqdoTarget_56304010d2fd7740d17a",
|
||||||
|
"expected_decl": "marqdoExpected_56304010d2fd7740d17a"
|
||||||
|
},
|
||||||
|
"cache_key": "00ff63bc5e80b023b3714d2f85c892de6be99831aa8a0baec9f852b2371a9bbf"
|
||||||
|
}
|
||||||
+69917
File diff suppressed because it is too large.
Load diff
+73
@@ -0,0 +1,73 @@
|
|||||||
|
{
|
||||||
|
"schema": "marqdo.proof",
|
||||||
|
"schema_version": 1,
|
||||||
|
"tool": {
|
||||||
|
"name": "marqdo-prove",
|
||||||
|
"version": "0.1.0"
|
||||||
|
},
|
||||||
|
"target": {
|
||||||
|
"unit_id": "root:default::algebra.mq.md#基础代数/非负整数加法",
|
||||||
|
"unit_path": [
|
||||||
|
"基础代数",
|
||||||
|
"非负整数加法"
|
||||||
|
],
|
||||||
|
"locator": "algebra.mq.md",
|
||||||
|
"scope": "mathematical",
|
||||||
|
"outcome": "verified",
|
||||||
|
"statement_literal": "\\forall a,b\\in\\mathbb{Z},\\quad (a\\geq0\\land b\\geq0)\\Rightarrow a+b\\geq0\n",
|
||||||
|
"statement_normalized": "∀ a b : ℤ, (a ≥ 0 ∧ b ≥ 0) → a + b ≥ 0",
|
||||||
|
"statement_lean": "∀ mqx0 mqx1 : Int, (((mqx0 ≥ (0 : Int)) ∧ (mqx1 ≥ (0 : Int))) → ((mqx0 + mqx1) ≥ (0 : Int)))",
|
||||||
|
"goal_span": {
|
||||||
|
"start": 227,
|
||||||
|
"end": 304
|
||||||
|
},
|
||||||
|
"goal_payload_span": {
|
||||||
|
"start": 230,
|
||||||
|
"end": 302
|
||||||
|
},
|
||||||
|
"goal_digest": "05b19fe479e9065a6e45ea3a5cb50315cdd05ec88d9951d998ef8435f57d3624",
|
||||||
|
"premises": [
|
||||||
|
"a ≥ 0 ∧ b ≥ 0"
|
||||||
|
],
|
||||||
|
"theorem_name": "marqdoTarget_36d89cf628e282b50d0b",
|
||||||
|
"expected_name": "marqdoExpected_36d89cf628e282b50d0b",
|
||||||
|
"model_definitions": []
|
||||||
|
},
|
||||||
|
"sources": [
|
||||||
|
{
|
||||||
|
"locator": "algebra.mq.md",
|
||||||
|
"module_id": "root:default::algebra.mq.md",
|
||||||
|
"source_digest": "ed9a14ef1e695605743cffac56066dbf8cb13200c0a0537084f2c65157195b22",
|
||||||
|
"analysis_digest": "1a1b1a237a43368284ccc39d01e46ec2789d5ed878b897241c8d402ae541e2f9"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"environment": {
|
||||||
|
"lean_toolchain": "leanprover/lean4:v4.36.0",
|
||||||
|
"lean_version": "86_64",
|
||||||
|
"mathlib_rev": "fc4f59e577feb1a4956671bc04ac18aaaf8cd842",
|
||||||
|
"lake_manifest_digest": "bb82472009ad8aba44b75c1a1095dfe290dd87319421d55039e02fe57f2e0022",
|
||||||
|
"replay_verifier_digest": "02cbc2c8b00dbdac2c5bcf359b25a62f896372b9964f7578caca4d4346d544c1",
|
||||||
|
"con_leche_version": "con-leche-a6380d68b4fb3641",
|
||||||
|
"formula_compiler": "marqdo-prove-0.1.0",
|
||||||
|
"semantic_mapping": "marqdo-int-exact-v1",
|
||||||
|
"environment_id": "9622d44bfc5540616117b8e4b60b3e06a84122535d4495925739a08acc14877a"
|
||||||
|
},
|
||||||
|
"declared_dependencies": [],
|
||||||
|
"used_dependencies": [],
|
||||||
|
"transitive_dependencies": [
|
||||||
|
"algebra.mq.md#基础代数/非负整数加法"
|
||||||
|
],
|
||||||
|
"axioms": [
|
||||||
|
"Quot.sound",
|
||||||
|
"propext"
|
||||||
|
],
|
||||||
|
"proof": {
|
||||||
|
"file": "proof.ndjson",
|
||||||
|
"bytes": 4204971,
|
||||||
|
"sha256": "22ed9b0ed6615b248f1fd9ae63ae1e3279614d8f17799f662f8859c6329da6e6",
|
||||||
|
"export_format": "lean4export-3.1.0",
|
||||||
|
"target_decl": "marqdoTarget_36d89cf628e282b50d0b",
|
||||||
|
"expected_decl": "marqdoExpected_36d89cf628e282b50d0b"
|
||||||
|
},
|
||||||
|
"cache_key": "98189b31742bf1201623dcd95a43c58c2e4fcf8f4b4c0c5a941fc0b1840b0d3e"
|
||||||
|
}
|
||||||
+82691
File diff suppressed because it is too large.
Load diff
+106
@@ -0,0 +1,106 @@
|
|||||||
|
{
|
||||||
|
"schema": "marqdo.proof",
|
||||||
|
"schema_version": 1,
|
||||||
|
"tool": {
|
||||||
|
"name": "marqdo-prove",
|
||||||
|
"version": "0.1.0"
|
||||||
|
},
|
||||||
|
"target": {
|
||||||
|
"unit_id": "root:default::arithmetic.mq.md#整数计算/平方函数的非负性",
|
||||||
|
"unit_path": [
|
||||||
|
"整数计算",
|
||||||
|
"平方函数的非负性"
|
||||||
|
],
|
||||||
|
"locator": "arithmetic.mq.md",
|
||||||
|
"scope": "program_model",
|
||||||
|
"outcome": "verified",
|
||||||
|
"statement_literal": "\\forall x\\in\\mathbb{Z},\\quad \\operatorname{square}(x)\\geq0\n",
|
||||||
|
"statement_normalized": "∀ x : ℤ, square(x) ≥ 0",
|
||||||
|
"statement_lean": "∀ mqx0 : Int, ((marqdoModel_bc89da8a98c85c898736 mqx0) ≥ (0 : Int))",
|
||||||
|
"goal_span": {
|
||||||
|
"start": 204,
|
||||||
|
"end": 268
|
||||||
|
},
|
||||||
|
"goal_payload_span": {
|
||||||
|
"start": 207,
|
||||||
|
"end": 266
|
||||||
|
},
|
||||||
|
"goal_digest": "9bf39b6885fd6cdee71b36412c8afb7645a9e621d4e5a4261e4e6886437d8b92",
|
||||||
|
"premises": [],
|
||||||
|
"theorem_name": "marqdoTarget_9f61c8e6f82c16133237",
|
||||||
|
"expected_name": "marqdoExpected_9f61c8e6f82c16133237",
|
||||||
|
"model_definitions": [
|
||||||
|
{
|
||||||
|
"unit_id": "root:default::arithmetic.mq.md#整数计算/square",
|
||||||
|
"locator": "arithmetic.mq.md",
|
||||||
|
"function_id": "root:default::arithmetic.mq.md::整数计算.square",
|
||||||
|
"lean_name": "marqdoModel_bc89da8a98c85c898736",
|
||||||
|
"digest": "e03f9f60e3eb7d6b9b08f2140c12b732ff73541caa6fc8d6940498b9aaa5d217",
|
||||||
|
"module_name": "MarqdoProof.Generated.Model_bc89da8a98c85c898736",
|
||||||
|
"semantics": "exact integer single-frame straight-line model returning Int; not a runtime refinement"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"sources": [
|
||||||
|
{
|
||||||
|
"locator": "algebra.mq.md",
|
||||||
|
"module_id": "root:default::algebra.mq.md",
|
||||||
|
"source_digest": "ed9a14ef1e695605743cffac56066dbf8cb13200c0a0537084f2c65157195b22",
|
||||||
|
"analysis_digest": "1a1b1a237a43368284ccc39d01e46ec2789d5ed878b897241c8d402ae541e2f9"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"locator": "arithmetic.mq.md",
|
||||||
|
"module_id": "root:default::arithmetic.mq.md",
|
||||||
|
"source_digest": "61b9751ac9ce790a8534fd3d3d045dfe676648c1cfecd8c9d3aefbe32f56dcde",
|
||||||
|
"analysis_digest": "95250c02e98a693974ecc7b6f588f3dce416d209747528fe2e041930396461f2"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"environment": {
|
||||||
|
"lean_toolchain": "leanprover/lean4:v4.36.0",
|
||||||
|
"lean_version": "86_64",
|
||||||
|
"mathlib_rev": "fc4f59e577feb1a4956671bc04ac18aaaf8cd842",
|
||||||
|
"lake_manifest_digest": "bb82472009ad8aba44b75c1a1095dfe290dd87319421d55039e02fe57f2e0022",
|
||||||
|
"replay_verifier_digest": "02cbc2c8b00dbdac2c5bcf359b25a62f896372b9964f7578caca4d4346d544c1",
|
||||||
|
"con_leche_version": "con-leche-a6380d68b4fb3641",
|
||||||
|
"formula_compiler": "marqdo-prove-0.1.0",
|
||||||
|
"semantic_mapping": "marqdo-int-exact-v1",
|
||||||
|
"environment_id": "9622d44bfc5540616117b8e4b60b3e06a84122535d4495925739a08acc14877a"
|
||||||
|
},
|
||||||
|
"declared_dependencies": [
|
||||||
|
{
|
||||||
|
"kind": "model",
|
||||||
|
"locator": "arithmetic.mq.md#root:default::arithmetic.mq.md#整数计算/square",
|
||||||
|
"unit_id": "root:default::arithmetic.mq.md#整数计算/square",
|
||||||
|
"link_text": "square",
|
||||||
|
"binding": "bc89da8a98c85c898736"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"kind": "theorem",
|
||||||
|
"locator": "algebra.mq.md#基础代数/整数平方非负性",
|
||||||
|
"unit_id": "root:default::algebra.mq.md#基础代数/整数平方非负性",
|
||||||
|
"link_text": "整数平方非负性",
|
||||||
|
"binding": "marqdoTarget_56304010d2fd7740d17a"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"used_dependencies": [
|
||||||
|
"arithmetic.mq.md#整数计算/square"
|
||||||
|
],
|
||||||
|
"transitive_dependencies": [
|
||||||
|
"arithmetic.mq.md#整数计算/square",
|
||||||
|
"arithmetic.mq.md#整数计算/平方函数的非负性"
|
||||||
|
],
|
||||||
|
"axioms": [
|
||||||
|
"Classical.choice",
|
||||||
|
"Quot.sound",
|
||||||
|
"propext"
|
||||||
|
],
|
||||||
|
"proof": {
|
||||||
|
"file": "proof.ndjson",
|
||||||
|
"bytes": 4568438,
|
||||||
|
"sha256": "4e0be0c12a56f11a58efcf069123a71497ca72e5a44ddb2d4a3df462e6e677be",
|
||||||
|
"export_format": "lean4export-3.1.0",
|
||||||
|
"target_decl": "marqdoTarget_9f61c8e6f82c16133237",
|
||||||
|
"expected_decl": "marqdoExpected_9f61c8e6f82c16133237"
|
||||||
|
},
|
||||||
|
"cache_key": "ace6c0fcfe559a6f67c3f0b8b98a0ae71d58860893addf6df1fb2ee55bcface8"
|
||||||
|
}
|
||||||
+86736
File diff suppressed because it is too large.
Load diff
+98
@@ -0,0 +1,98 @@
|
|||||||
|
{
|
||||||
|
"schema": "marqdo.proof",
|
||||||
|
"schema_version": 1,
|
||||||
|
"tool": {
|
||||||
|
"name": "marqdo-prove",
|
||||||
|
"version": "0.1.0"
|
||||||
|
},
|
||||||
|
"target": {
|
||||||
|
"unit_id": "root:default::vector.mq.md#向量数学/平方和非负性",
|
||||||
|
"unit_path": [
|
||||||
|
"向量数学",
|
||||||
|
"平方和非负性"
|
||||||
|
],
|
||||||
|
"locator": "vector.mq.md",
|
||||||
|
"scope": "mathematical",
|
||||||
|
"outcome": "verified",
|
||||||
|
"statement_literal": "\\forall x,y\\in\\mathbb{Z},\\quad x^2+y^2\\geq0\n",
|
||||||
|
"statement_normalized": "∀ x y : ℤ, x^2 + y^2 ≥ 0",
|
||||||
|
"statement_lean": "∀ mqx0 mqx1 : Int, (((mqx0 ^ (2 : Nat)) + (mqx1 ^ (2 : Nat))) ≥ (0 : Int))",
|
||||||
|
"goal_span": {
|
||||||
|
"start": 94,
|
||||||
|
"end": 143
|
||||||
|
},
|
||||||
|
"goal_payload_span": {
|
||||||
|
"start": 97,
|
||||||
|
"end": 141
|
||||||
|
},
|
||||||
|
"goal_digest": "96995d5fb7d68d092e5a349a774f73a65a6384b37a30a15cfc128183067dab8a",
|
||||||
|
"premises": [],
|
||||||
|
"theorem_name": "marqdoTarget_97424ed21bb12c19f758",
|
||||||
|
"expected_name": "marqdoExpected_97424ed21bb12c19f758",
|
||||||
|
"model_definitions": []
|
||||||
|
},
|
||||||
|
"sources": [
|
||||||
|
{
|
||||||
|
"locator": "algebra.mq.md",
|
||||||
|
"module_id": "root:default::algebra.mq.md",
|
||||||
|
"source_digest": "ed9a14ef1e695605743cffac56066dbf8cb13200c0a0537084f2c65157195b22",
|
||||||
|
"analysis_digest": "1a1b1a237a43368284ccc39d01e46ec2789d5ed878b897241c8d402ae541e2f9"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"locator": "vector.mq.md",
|
||||||
|
"module_id": "root:default::vector.mq.md",
|
||||||
|
"source_digest": "ddb7f3bdc9c3914c89fc4d0f9c686f8552473cdc576a1992941f3e9850dbb5bb",
|
||||||
|
"analysis_digest": "d1fabe313dbcb35065c969538aa7e2aba8339ea5ad03632c80197fd976a50908"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"environment": {
|
||||||
|
"lean_toolchain": "leanprover/lean4:v4.36.0",
|
||||||
|
"lean_version": "86_64",
|
||||||
|
"mathlib_rev": "fc4f59e577feb1a4956671bc04ac18aaaf8cd842",
|
||||||
|
"lake_manifest_digest": "bb82472009ad8aba44b75c1a1095dfe290dd87319421d55039e02fe57f2e0022",
|
||||||
|
"replay_verifier_digest": "02cbc2c8b00dbdac2c5bcf359b25a62f896372b9964f7578caca4d4346d544c1",
|
||||||
|
"con_leche_version": "con-leche-a6380d68b4fb3641",
|
||||||
|
"formula_compiler": "marqdo-prove-0.1.0",
|
||||||
|
"semantic_mapping": "marqdo-int-exact-v1",
|
||||||
|
"environment_id": "9622d44bfc5540616117b8e4b60b3e06a84122535d4495925739a08acc14877a"
|
||||||
|
},
|
||||||
|
"declared_dependencies": [
|
||||||
|
{
|
||||||
|
"kind": "theorem",
|
||||||
|
"locator": "algebra.mq.md#基础代数/整数平方非负性",
|
||||||
|
"unit_id": "root:default::algebra.mq.md#基础代数/整数平方非负性",
|
||||||
|
"link_text": "整数平方非负性",
|
||||||
|
"binding": "marqdoTarget_56304010d2fd7740d17a"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"kind": "theorem",
|
||||||
|
"locator": "algebra.mq.md#基础代数/非负整数加法",
|
||||||
|
"unit_id": "root:default::algebra.mq.md#基础代数/非负整数加法",
|
||||||
|
"link_text": "非负整数加法",
|
||||||
|
"binding": "marqdoTarget_36d89cf628e282b50d0b"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"used_dependencies": [
|
||||||
|
"algebra.mq.md#基础代数/整数平方非负性",
|
||||||
|
"algebra.mq.md#基础代数/非负整数加法"
|
||||||
|
],
|
||||||
|
"transitive_dependencies": [
|
||||||
|
"algebra.mq.md#基础代数/整数平方非负性",
|
||||||
|
"algebra.mq.md#基础代数/非负整数加法",
|
||||||
|
"vector.mq.md#向量数学/平方和非负性"
|
||||||
|
],
|
||||||
|
"axioms": [
|
||||||
|
"Classical.choice",
|
||||||
|
"Quot.sound",
|
||||||
|
"propext"
|
||||||
|
],
|
||||||
|
"proof": {
|
||||||
|
"file": "proof.ndjson",
|
||||||
|
"bytes": 6086904,
|
||||||
|
"sha256": "ac888cea3eabf926f26324bc01c55c87c5d335d361db19e249e62a33d177fd6a",
|
||||||
|
"export_format": "lean4export-3.1.0",
|
||||||
|
"target_decl": "marqdoTarget_97424ed21bb12c19f758",
|
||||||
|
"expected_decl": "marqdoExpected_97424ed21bb12c19f758"
|
||||||
|
},
|
||||||
|
"cache_key": "de68611d32ac1916e1a810796a176c366a59db621cb7b563dabfc6329d04312a"
|
||||||
|
}
|
||||||
+117390
File diff suppressed because it is too large.
Load diff
+164
-63
@@ -51,7 +51,9 @@ pub struct ModuleData {
|
|||||||
|
|
||||||
impl ModuleData {
|
impl ModuleData {
|
||||||
pub fn unit(&self, unit_id: &str) -> Option<&Unit> {
|
pub fn unit(&self, unit_id: &str) -> Option<&Unit> {
|
||||||
self.unit_by_id.get(unit_id).map(|index| &self.units[*index])
|
self.unit_by_id
|
||||||
|
.get(unit_id)
|
||||||
|
.map(|index| &self.units[*index])
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Direct child units of `parent_id`, in document order.
|
/// Direct child units of `parent_id`, in document order.
|
||||||
@@ -184,7 +186,10 @@ impl AnalysisBackend {
|
|||||||
if !marqdo_bin.is_absolute() {
|
if !marqdo_bin.is_absolute() {
|
||||||
return Err(Failure::new(
|
return Err(Failure::new(
|
||||||
codes::BACKEND_UNAVAILABLE,
|
codes::BACKEND_UNAVAILABLE,
|
||||||
format!("MARQDO_BIN must be an absolute path, got `{}`", marqdo_bin.display()),
|
format!(
|
||||||
|
"MARQDO_BIN must be an absolute path, got `{}`",
|
||||||
|
marqdo_bin.display()
|
||||||
|
),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
if !marqdo_bin.is_file() {
|
if !marqdo_bin.is_file() {
|
||||||
@@ -197,7 +202,10 @@ impl AnalysisBackend {
|
|||||||
std::fs::create_dir_all(&work_dir).map_err(|error| {
|
std::fs::create_dir_all(&work_dir).map_err(|error| {
|
||||||
Failure::new(
|
Failure::new(
|
||||||
codes::BACKEND_UNAVAILABLE,
|
codes::BACKEND_UNAVAILABLE,
|
||||||
format!("cannot create private work directory `{}`: {error}", work_dir.display()),
|
format!(
|
||||||
|
"cannot create private work directory `{}`: {error}",
|
||||||
|
work_dir.display()
|
||||||
|
),
|
||||||
)
|
)
|
||||||
})?;
|
})?;
|
||||||
if let Ok(revision) = std::env::var("MARQDO_API_REVISION") {
|
if let Ok(revision) = std::env::var("MARQDO_API_REVISION") {
|
||||||
@@ -252,7 +260,10 @@ impl AnalysisBackend {
|
|||||||
}
|
}
|
||||||
None => {
|
None => {
|
||||||
let mut directory = entry.parent().map(Path::to_path_buf).ok_or_else(|| {
|
let mut directory = entry.parent().map(Path::to_path_buf).ok_or_else(|| {
|
||||||
Failure::new(codes::DOCUMENT_UNIT, "entry document has no parent directory")
|
Failure::new(
|
||||||
|
codes::DOCUMENT_UNIT,
|
||||||
|
"entry document has no parent directory",
|
||||||
|
)
|
||||||
})?;
|
})?;
|
||||||
let start = directory.clone();
|
let start = directory.clone();
|
||||||
loop {
|
loop {
|
||||||
@@ -306,9 +317,7 @@ impl AnalysisBackend {
|
|||||||
}
|
}
|
||||||
let bytes = self.emit_analysis(&canonical, &root)?;
|
let bytes = self.emit_analysis(&canonical, &root)?;
|
||||||
let snapshot = Arc::new(parse_and_validate(&bytes, &canonical, &root)?);
|
let snapshot = Arc::new(parse_and_validate(&bytes, &canonical, &root)?);
|
||||||
self.cache
|
self.cache.borrow_mut().insert(canonical, snapshot.clone());
|
||||||
.borrow_mut()
|
|
||||||
.insert(canonical, snapshot.clone());
|
|
||||||
Ok(snapshot)
|
Ok(snapshot)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -511,6 +520,10 @@ struct AnalysisFile {
|
|||||||
#[serde(deny_unknown_fields)]
|
#[serde(deny_unknown_fields)]
|
||||||
struct Producer {
|
struct Producer {
|
||||||
name: String,
|
name: String,
|
||||||
|
/// Contract field: the CLI version is recorded in the upstream contract but
|
||||||
|
/// Prove binds through the environment identity instead of the producer
|
||||||
|
/// string, so the value is validated for presence and then unused.
|
||||||
|
#[allow(dead_code)]
|
||||||
version: String,
|
version: String,
|
||||||
markdown_profile: String,
|
markdown_profile: String,
|
||||||
}
|
}
|
||||||
@@ -523,12 +536,18 @@ struct Project {
|
|||||||
entry_module_id: String,
|
entry_module_id: String,
|
||||||
lock_digest: String,
|
lock_digest: String,
|
||||||
manifest_digest: String,
|
manifest_digest: String,
|
||||||
|
/// Contract field validated by the upstream schema; Prove never uses stdlib.
|
||||||
|
#[allow(dead_code)]
|
||||||
stdlib: Option<StdlibIdentity>,
|
stdlib: Option<StdlibIdentity>,
|
||||||
|
/// Contract field validated by the upstream schema; Prove never loads
|
||||||
|
/// extensions through Analysis.
|
||||||
|
#[allow(dead_code)]
|
||||||
extensions: Vec<serde_json::Value>,
|
extensions: Vec<serde_json::Value>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize)]
|
||||||
#[serde(deny_unknown_fields)]
|
#[serde(deny_unknown_fields)]
|
||||||
|
#[allow(dead_code)]
|
||||||
struct StdlibIdentity {
|
struct StdlibIdentity {
|
||||||
version: String,
|
version: String,
|
||||||
digest: String,
|
digest: String,
|
||||||
@@ -549,6 +568,9 @@ struct RawModule {
|
|||||||
functions: Vec<Function>,
|
functions: Vec<Function>,
|
||||||
imports: Vec<Import>,
|
imports: Vec<Import>,
|
||||||
references: Vec<Reference>,
|
references: Vec<Reference>,
|
||||||
|
/// Inert call-binding projection; the program-model bridge does not use
|
||||||
|
/// cross-function calls in the first release.
|
||||||
|
#[allow(dead_code)]
|
||||||
calls: Vec<serde_json::Value>,
|
calls: Vec<serde_json::Value>,
|
||||||
resources: Vec<Resource>,
|
resources: Vec<Resource>,
|
||||||
}
|
}
|
||||||
@@ -661,10 +683,7 @@ pub enum Statement {
|
|||||||
#[serde(rename = "expression")]
|
#[serde(rename = "expression")]
|
||||||
Expression { value: Expression, span: Span },
|
Expression { value: Expression, span: Span },
|
||||||
#[serde(rename = "branch")]
|
#[serde(rename = "branch")]
|
||||||
Branch {
|
Branch { arms: Vec<BranchArm>, span: Span },
|
||||||
arms: Vec<BranchArm>,
|
|
||||||
span: Span,
|
|
||||||
},
|
|
||||||
#[serde(rename = "loop")]
|
#[serde(rename = "loop")]
|
||||||
Loop {
|
Loop {
|
||||||
condition: Expression,
|
condition: Expression,
|
||||||
@@ -728,10 +747,7 @@ pub enum Expression {
|
|||||||
#[serde(rename = "variable")]
|
#[serde(rename = "variable")]
|
||||||
Variable { name: String, span: Span },
|
Variable { name: String, span: Span },
|
||||||
#[serde(rename = "list")]
|
#[serde(rename = "list")]
|
||||||
List {
|
List { items: Vec<Expression>, span: Span },
|
||||||
items: Vec<Expression>,
|
|
||||||
span: Span,
|
|
||||||
},
|
|
||||||
#[serde(rename = "record")]
|
#[serde(rename = "record")]
|
||||||
Record {
|
Record {
|
||||||
entries: Vec<RecordEntry>,
|
entries: Vec<RecordEntry>,
|
||||||
@@ -843,6 +859,7 @@ pub struct Resource {
|
|||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize)]
|
||||||
#[serde(deny_unknown_fields)]
|
#[serde(deny_unknown_fields)]
|
||||||
|
#[allow(dead_code)]
|
||||||
struct RawDiagnostic {
|
struct RawDiagnostic {
|
||||||
module: String,
|
module: String,
|
||||||
relative_path: String,
|
relative_path: String,
|
||||||
@@ -896,10 +913,16 @@ fn parse_and_validate(bytes: &[u8], entry_path: &Path, root: &Path) -> Result<Sn
|
|||||||
file.producer.markdown_profile
|
file.producer.markdown_profile
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
if !file.diagnostics.iter().all(|diagnostic| diagnostic.severity != "error") {
|
if !file
|
||||||
|
.diagnostics
|
||||||
|
.iter()
|
||||||
|
.all(|diagnostic| diagnostic.severity != "error")
|
||||||
|
{
|
||||||
return contract("Analysis contains error diagnostics despite a successful check");
|
return contract("Analysis contains error diagnostics despite a successful check");
|
||||||
}
|
}
|
||||||
if file.project.identity_kind != "manifest" && file.project.identity_kind != "workspace_snapshot" {
|
if file.project.identity_kind != "manifest"
|
||||||
|
&& file.project.identity_kind != "workspace_snapshot"
|
||||||
|
{
|
||||||
return contract(format!(
|
return contract(format!(
|
||||||
"unexpected project identity kind `{}`",
|
"unexpected project identity kind `{}`",
|
||||||
file.project.identity_kind
|
file.project.identity_kind
|
||||||
@@ -931,7 +954,11 @@ fn parse_and_validate(bytes: &[u8], entry_path: &Path, root: &Path) -> Result<Sn
|
|||||||
.map_err(|_| {
|
.map_err(|_| {
|
||||||
Failure::new(
|
Failure::new(
|
||||||
codes::LINK_OUTSIDE_ROOT,
|
codes::LINK_OUTSIDE_ROOT,
|
||||||
format!("entry `{}` is not below root `{}`", entry_path.display(), root.display()),
|
format!(
|
||||||
|
"entry `{}` is not below root `{}`",
|
||||||
|
entry_path.display(),
|
||||||
|
root.display()
|
||||||
|
),
|
||||||
)
|
)
|
||||||
})?
|
})?
|
||||||
.to_string_lossy()
|
.to_string_lossy()
|
||||||
@@ -968,9 +995,11 @@ fn parse_and_validate(bytes: &[u8], entry_path: &Path, root: &Path) -> Result<Sn
|
|||||||
),
|
),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
if let Some(previous) = instance_roots.insert(data.package_instance_id.clone(), canonical.clone())
|
if let Some(previous) =
|
||||||
|
instance_roots.insert(data.package_instance_id.clone(), canonical.clone())
|
||||||
{
|
{
|
||||||
if previous != canonical && data.package_instance_id != entry_matches[0].package_instance_id
|
if previous != canonical
|
||||||
|
&& data.package_instance_id != entry_matches[0].package_instance_id
|
||||||
{
|
{
|
||||||
// Distinct packages are allowed; equal instance ids are not.
|
// Distinct packages are allowed; equal instance ids are not.
|
||||||
}
|
}
|
||||||
@@ -1014,7 +1043,10 @@ fn validate_module(raw: &RawModule) -> Result<ModuleData> {
|
|||||||
if raw.relative_path.is_empty()
|
if raw.relative_path.is_empty()
|
||||||
|| raw.relative_path.starts_with('/')
|
|| raw.relative_path.starts_with('/')
|
||||||
|| raw.relative_path.contains('\\')
|
|| raw.relative_path.contains('\\')
|
||||||
|| raw.relative_path.split('/').any(|segment| segment.is_empty() || segment == "." || segment == "..")
|
|| raw
|
||||||
|
.relative_path
|
||||||
|
.split('/')
|
||||||
|
.any(|segment| segment.is_empty() || segment == "." || segment == "..")
|
||||||
{
|
{
|
||||||
return contract(format!(
|
return contract(format!(
|
||||||
"module.relative_path `{}` is not a safe package-relative path",
|
"module.relative_path `{}` is not a safe package-relative path",
|
||||||
@@ -1035,7 +1067,10 @@ fn validate_module(raw: &RawModule) -> Result<ModuleData> {
|
|||||||
if raw.units.len() > max_units {
|
if raw.units.len() > max_units {
|
||||||
return Err(Failure::new(
|
return Err(Failure::new(
|
||||||
codes::DOCUMENT_UNIT,
|
codes::DOCUMENT_UNIT,
|
||||||
format!("module has {} units, above the {max_units} unit limit", raw.units.len()),
|
format!(
|
||||||
|
"module has {} units, above the {max_units} unit limit",
|
||||||
|
raw.units.len()
|
||||||
|
),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
let mut unit_by_id = HashMap::new();
|
let mut unit_by_id = HashMap::new();
|
||||||
@@ -1047,11 +1082,17 @@ fn validate_module(raw: &RawModule) -> Result<ModuleData> {
|
|||||||
return contract(format!("duplicate unit id `{}`", unit.id));
|
return contract(format!("duplicate unit id `{}`", unit.id));
|
||||||
}
|
}
|
||||||
if !unit.span.is_valid_in(&raw.source) {
|
if !unit.span.is_valid_in(&raw.source) {
|
||||||
return contract(format!("unit `{}` has an out-of-range section span", unit.id));
|
return contract(format!(
|
||||||
|
"unit `{}` has an out-of-range section span",
|
||||||
|
unit.id
|
||||||
|
));
|
||||||
}
|
}
|
||||||
if let Some(heading_span) = unit.heading_span {
|
if let Some(heading_span) = unit.heading_span {
|
||||||
if !heading_span.is_valid_in(&raw.source) {
|
if !heading_span.is_valid_in(&raw.source) {
|
||||||
return contract(format!("unit `{}` has an out-of-range heading span", unit.id));
|
return contract(format!(
|
||||||
|
"unit `{}` has an out-of-range heading span",
|
||||||
|
unit.id
|
||||||
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
match unit.mode.as_str() {
|
match unit.mode.as_str() {
|
||||||
@@ -1064,7 +1105,11 @@ fn validate_module(raw: &RawModule) -> Result<ModuleData> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Exactly one root unit, and a well-formed parent tree.
|
// Exactly one root unit, and a well-formed parent tree.
|
||||||
let roots: Vec<&Unit> = raw.units.iter().filter(|unit| unit.kind == "root").collect();
|
let roots: Vec<&Unit> = raw
|
||||||
|
.units
|
||||||
|
.iter()
|
||||||
|
.filter(|unit| unit.kind == "root")
|
||||||
|
.collect();
|
||||||
if roots.len() != 1 {
|
if roots.len() != 1 {
|
||||||
return contract("module must contain exactly one root unit");
|
return contract("module must contain exactly one root unit");
|
||||||
}
|
}
|
||||||
@@ -1085,10 +1130,12 @@ fn validate_module(raw: &RawModule) -> Result<ModuleData> {
|
|||||||
if unit.path.is_empty() {
|
if unit.path.is_empty() {
|
||||||
return contract(format!("unit `{}` has an empty path", unit.id));
|
return contract(format!("unit `{}` has an empty path", unit.id));
|
||||||
}
|
}
|
||||||
let parent_id = unit
|
let parent_id = unit.parent_id.as_deref().ok_or_else(|| {
|
||||||
.parent_id
|
Failure::new(
|
||||||
.as_deref()
|
codes::UPSTREAM_CONTRACT,
|
||||||
.ok_or_else(|| Failure::new(codes::UPSTREAM_CONTRACT, format!("unit `{}` has no parent", unit.id)))?;
|
format!("unit `{}` has no parent", unit.id),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
let parent = raw
|
let parent = raw
|
||||||
.units
|
.units
|
||||||
.iter()
|
.iter()
|
||||||
@@ -1108,9 +1155,14 @@ fn validate_module(raw: &RawModule) -> Result<ModuleData> {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
if unit.span.start < parent.span.start || unit.span.end > parent.span.end {
|
if unit.span.start < parent.span.start || unit.span.end > parent.span.end {
|
||||||
return contract(format!("unit `{}` span is not nested in its parent", unit.id));
|
return contract(format!(
|
||||||
|
"unit `{}` span is not nested in its parent",
|
||||||
|
unit.id
|
||||||
|
));
|
||||||
}
|
}
|
||||||
if unit.mode_source_unit_id != unit.id && !is_ancestor(raw, &unit.mode_source_unit_id, &unit.id) {
|
if unit.mode_source_unit_id != unit.id
|
||||||
|
&& !is_ancestor(raw, &unit.mode_source_unit_id, &unit.id)
|
||||||
|
{
|
||||||
return contract(format!(
|
return contract(format!(
|
||||||
"unit `{}` mode_source_unit_id is not itself or an ancestor",
|
"unit `{}` mode_source_unit_id is not itself or an ancestor",
|
||||||
unit.id
|
unit.id
|
||||||
@@ -1124,18 +1176,29 @@ fn validate_module(raw: &RawModule) -> Result<ModuleData> {
|
|||||||
return contract("empty anchor name in Analysis");
|
return contract("empty anchor name in Analysis");
|
||||||
}
|
}
|
||||||
if !unit_by_id.contains_key(&anchor.unit_id) {
|
if !unit_by_id.contains_key(&anchor.unit_id) {
|
||||||
return contract(format!("anchor `{}` points at an unknown unit", anchor.anchor));
|
return contract(format!(
|
||||||
|
"anchor `{}` points at an unknown unit",
|
||||||
|
anchor.anchor
|
||||||
|
));
|
||||||
}
|
}
|
||||||
if anchors.insert(anchor.anchor.clone(), anchor.unit_id.clone()).is_some() {
|
if anchors
|
||||||
|
.insert(anchor.anchor.clone(), anchor.unit_id.clone())
|
||||||
|
.is_some()
|
||||||
|
{
|
||||||
return contract(format!("duplicate anchor `{}`", anchor.anchor));
|
return contract(format!("duplicate anchor `{}`", anchor.anchor));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for function in &raw.functions {
|
for function in &raw.functions {
|
||||||
if !unit_by_id.contains_key(&function.unit_id) {
|
if !unit_by_id.contains_key(&function.unit_id) {
|
||||||
return contract(format!("function `{}` points at an unknown unit", function.id));
|
return contract(format!(
|
||||||
|
"function `{}` points at an unknown unit",
|
||||||
|
function.id
|
||||||
|
));
|
||||||
}
|
}
|
||||||
if !function.span.is_valid_in(&raw.source) || !function.heading_span.is_valid_in(&raw.source) {
|
if !function.span.is_valid_in(&raw.source)
|
||||||
|
|| !function.heading_span.is_valid_in(&raw.source)
|
||||||
|
{
|
||||||
return contract(format!("function `{}` has out-of-range spans", function.id));
|
return contract(format!("function `{}` has out-of-range spans", function.id));
|
||||||
}
|
}
|
||||||
validate_statements(&function.body, &raw.source)?;
|
validate_statements(&function.body, &raw.source)?;
|
||||||
@@ -1146,7 +1209,10 @@ fn validate_module(raw: &RawModule) -> Result<ModuleData> {
|
|||||||
return contract("reference.source does not match its module");
|
return contract("reference.source does not match its module");
|
||||||
}
|
}
|
||||||
if !reference.span.is_valid_in(&raw.source) {
|
if !reference.span.is_valid_in(&raw.source) {
|
||||||
return contract(format!("reference `{}` has an out-of-range span", reference.url));
|
return contract(format!(
|
||||||
|
"reference `{}` has an out-of-range span",
|
||||||
|
reference.url
|
||||||
|
));
|
||||||
}
|
}
|
||||||
if !unit_by_id.contains_key(&reference.source_unit) {
|
if !unit_by_id.contains_key(&reference.source_unit) {
|
||||||
return contract("reference.source_unit points at an unknown unit");
|
return contract("reference.source_unit points at an unknown unit");
|
||||||
@@ -1166,17 +1232,26 @@ fn validate_module(raw: &RawModule) -> Result<ModuleData> {
|
|||||||
|
|
||||||
for resource in &raw.resources {
|
for resource in &raw.resources {
|
||||||
if !resource.span.is_valid_in(&raw.source) {
|
if !resource.span.is_valid_in(&raw.source) {
|
||||||
return contract(format!("resource `{}` has an out-of-range span", resource.id));
|
return contract(format!(
|
||||||
|
"resource `{}` has an out-of-range span",
|
||||||
|
resource.id
|
||||||
|
));
|
||||||
}
|
}
|
||||||
if !unit_by_id.contains_key(&resource.unit_id) {
|
if !unit_by_id.contains_key(&resource.unit_id) {
|
||||||
return contract(format!("resource `{}` points at an unknown unit", resource.id));
|
return contract(format!(
|
||||||
|
"resource `{}` points at an unknown unit",
|
||||||
|
resource.id
|
||||||
|
));
|
||||||
}
|
}
|
||||||
match resource.kind.as_str() {
|
match resource.kind.as_str() {
|
||||||
"formula" => {
|
"formula" => {
|
||||||
let payload = find_payload(&raw.document, resource.span).ok_or_else(|| {
|
let payload = find_payload(&raw.document, resource.span).ok_or_else(|| {
|
||||||
Failure::new(
|
Failure::new(
|
||||||
codes::UPSTREAM_CONTRACT,
|
codes::UPSTREAM_CONTRACT,
|
||||||
format!("formula resource `{}` has no matching math node", resource.id),
|
format!(
|
||||||
|
"formula resource `{}` has no matching math node",
|
||||||
|
resource.id
|
||||||
|
),
|
||||||
)
|
)
|
||||||
})?;
|
})?;
|
||||||
let literal = math_literal(payload).ok_or_else(|| {
|
let literal = math_literal(payload).ok_or_else(|| {
|
||||||
@@ -1259,7 +1334,10 @@ fn validate_node_spans(node: &Node, source: &str, depth: usize) -> Result<()> {
|
|||||||
if depth > crate::limits::MAX_AST_DEPTH {
|
if depth > crate::limits::MAX_AST_DEPTH {
|
||||||
return Err(Failure::new(
|
return Err(Failure::new(
|
||||||
codes::DOCUMENT_UNIT,
|
codes::DOCUMENT_UNIT,
|
||||||
format!("document AST is deeper than {} levels", crate::limits::MAX_AST_DEPTH),
|
format!(
|
||||||
|
"document AST is deeper than {} levels",
|
||||||
|
crate::limits::MAX_AST_DEPTH
|
||||||
|
),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
if !node.span.is_valid_in(source) {
|
if !node.span.is_valid_in(source) {
|
||||||
@@ -1278,12 +1356,12 @@ fn validate_node_spans(node: &Node, source: &str, depth: usize) -> Result<()> {
|
|||||||
validate_node_spans(child, source, depth + 1)?;
|
validate_node_spans(child, source, depth + 1)?;
|
||||||
}
|
}
|
||||||
match node.kind.as_str() {
|
match node.kind.as_str() {
|
||||||
"math_block" | "math" | "text" | "code" | "code_block" | "front_matter" | "html_block"
|
"math_block" | "math" | "text" | "code" | "code_block" | "front_matter" | "html_block" => {
|
||||||
| "html_inline" => {
|
if node.literal.is_none() {
|
||||||
if node.literal.is_none() && node.kind != "html_inline" {
|
|
||||||
return contract(format!("document node `{}` has no literal", node.kind));
|
return contract(format!("document node `{}` has no literal", node.kind));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
"html_inline" => {}
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -1305,7 +1383,9 @@ fn validate_statements(statements: &[Statement], source: &str) -> Result<()> {
|
|||||||
validate_statements(&arm.body, source)?;
|
validate_statements(&arm.body, source)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Statement::Loop { condition, body, .. } => {
|
Statement::Loop {
|
||||||
|
condition, body, ..
|
||||||
|
} => {
|
||||||
validate_expression(condition, source)?;
|
validate_expression(condition, source)?;
|
||||||
validate_statements(body, source)?;
|
validate_statements(body, source)?;
|
||||||
}
|
}
|
||||||
@@ -1352,7 +1432,7 @@ fn validate_expression(expression: &Expression, source: &str) -> Result<()> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Find the node whose span equals the resource span.
|
/// Find the node whose span equals the resource span.
|
||||||
fn find_payload<'a>(node: &'a Node, span: Span) -> Option<&'a Node> {
|
fn find_payload(node: &Node, span: Span) -> Option<&Node> {
|
||||||
if node.span == span {
|
if node.span == span {
|
||||||
return Some(node);
|
return Some(node);
|
||||||
}
|
}
|
||||||
@@ -1378,14 +1458,19 @@ fn is_sha256_digest(value: &str) -> bool {
|
|||||||
let Some(hex) = value.strip_prefix("sha256:") else {
|
let Some(hex) = value.strip_prefix("sha256:") else {
|
||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
hex.len() == 64 && hex.bytes().all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
|
hex.len() == 64
|
||||||
|
&& hex
|
||||||
|
.bytes()
|
||||||
|
.all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn contract<T>(message: impl Into<String>) -> Result<T> {
|
fn contract<T>(message: impl Into<String>) -> Result<T> {
|
||||||
Err(Failure::new(codes::UPSTREAM_CONTRACT, message.into()).with_hint(
|
Err(
|
||||||
"install and build a Marqdo CLI that emits the current `marqdo.analysis` revision 3 \
|
Failure::new(codes::UPSTREAM_CONTRACT, message.into()).with_hint(
|
||||||
|
"install and build a Marqdo CLI that emits the current `marqdo.analysis` revision 3 \
|
||||||
contract; Prove has no compatibility reader",
|
contract; Prove has no compatibility reader",
|
||||||
))
|
),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
@@ -1449,30 +1534,43 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn rejects_wrong_schema_revision() {
|
fn rejects_wrong_schema_revision() {
|
||||||
let json = analysis_json(&simple_module()).replace("\"schema_version\": 3", "\"schema_version\": 2");
|
let json = analysis_json(&simple_module())
|
||||||
let error = parse_and_validate(json.as_bytes(), Path::new("/tmp/index.mq.md"), Path::new("/tmp"))
|
.replace("\"schema_version\": 3", "\"schema_version\": 2");
|
||||||
.unwrap_err();
|
let error = parse_and_validate(
|
||||||
|
json.as_bytes(),
|
||||||
|
Path::new("/tmp/index.mq.md"),
|
||||||
|
Path::new("/tmp"),
|
||||||
|
)
|
||||||
|
.unwrap_err();
|
||||||
assert_eq!(error.code, codes::UPSTREAM_CONTRACT);
|
assert_eq!(error.code, codes::UPSTREAM_CONTRACT);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn rejects_source_digest_mismatch() {
|
fn rejects_source_digest_mismatch() {
|
||||||
let json = analysis_json(&simple_module()).replace(
|
let json = analysis_json(&simple_module())
|
||||||
&sha256_hex("# 标题\n".as_bytes()),
|
.replace(&sha256_hex("# 标题\n".as_bytes()), &sha256_hex(b"tampered"));
|
||||||
&sha256_hex(b"tampered"),
|
let error = parse_and_validate(
|
||||||
);
|
json.as_bytes(),
|
||||||
let error = parse_and_validate(json.as_bytes(), Path::new("/tmp/index.mq.md"), Path::new("/tmp"))
|
Path::new("/tmp/index.mq.md"),
|
||||||
.unwrap_err();
|
Path::new("/tmp"),
|
||||||
|
)
|
||||||
|
.unwrap_err();
|
||||||
assert_eq!(error.code, codes::UPSTREAM_CONTRACT);
|
assert_eq!(error.code, codes::UPSTREAM_CONTRACT);
|
||||||
assert!(error.message.contains("source_digest"));
|
assert!(error.message.contains("source_digest"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn rejects_escaping_relative_path() {
|
fn rejects_escaping_relative_path() {
|
||||||
let json = analysis_json(&simple_module())
|
let json = analysis_json(&simple_module()).replace(
|
||||||
.replace("\"relative_path\": \"index.mq.md\"", "\"relative_path\": \"../index.mq.md\"");
|
"\"relative_path\": \"index.mq.md\"",
|
||||||
let error = parse_and_validate(json.as_bytes(), Path::new("/tmp/index.mq.md"), Path::new("/tmp"))
|
"\"relative_path\": \"../index.mq.md\"",
|
||||||
.unwrap_err();
|
);
|
||||||
|
let error = parse_and_validate(
|
||||||
|
json.as_bytes(),
|
||||||
|
Path::new("/tmp/index.mq.md"),
|
||||||
|
Path::new("/tmp"),
|
||||||
|
)
|
||||||
|
.unwrap_err();
|
||||||
assert_eq!(error.code, codes::UPSTREAM_CONTRACT);
|
assert_eq!(error.code, codes::UPSTREAM_CONTRACT);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1513,6 +1611,9 @@ mod tests {
|
|||||||
unit_by_id: HashMap::new(),
|
unit_by_id: HashMap::new(),
|
||||||
};
|
};
|
||||||
assert_eq!(module.resolve_fragment("缺失"), FragmentResolution::Missing);
|
assert_eq!(module.resolve_fragment("缺失"), FragmentResolution::Missing);
|
||||||
assert_eq!(module.resolve_fragment(""), FragmentResolution::DocumentRoot);
|
assert_eq!(
|
||||||
|
module.resolve_fragment(""),
|
||||||
|
FragmentResolution::DocumentRoot
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+42
-18
@@ -181,7 +181,10 @@ impl BundleManifest {
|
|||||||
return invalid("proof target goal_digest is not a canonical sha256 digest");
|
return invalid("proof target goal_digest is not a canonical sha256 digest");
|
||||||
}
|
}
|
||||||
if self.proof.file != PAYLOAD_FILE {
|
if self.proof.file != PAYLOAD_FILE {
|
||||||
return invalid(format!("unexpected proof payload file `{}`", self.proof.file));
|
return invalid(format!(
|
||||||
|
"unexpected proof payload file `{}`",
|
||||||
|
self.proof.file
|
||||||
|
));
|
||||||
}
|
}
|
||||||
if !is_hex_sha256(&self.proof.sha256) {
|
if !is_hex_sha256(&self.proof.sha256) {
|
||||||
return invalid("proof payload sha256 is not a canonical digest");
|
return invalid("proof payload sha256 is not a canonical digest");
|
||||||
@@ -250,21 +253,27 @@ impl Bundle {
|
|||||||
if manifest_bytes.len() > 4 * 1024 * 1024 {
|
if manifest_bytes.len() > 4 * 1024 * 1024 {
|
||||||
return invalid("proof manifest is unreasonably large");
|
return invalid("proof manifest is unreasonably large");
|
||||||
}
|
}
|
||||||
let manifest: BundleManifest = serde_json::from_slice(&manifest_bytes).map_err(|error| {
|
let manifest: BundleManifest =
|
||||||
Failure::new(
|
serde_json::from_slice(&manifest_bytes).map_err(|error| {
|
||||||
codes::CERTIFICATE_INVALID,
|
Failure::new(
|
||||||
format!(
|
codes::CERTIFICATE_INVALID,
|
||||||
"`{}` does not match the current marqdo.proof revision 1 shape: {error}",
|
format!(
|
||||||
manifest_path.display()
|
"`{}` 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")
|
)
|
||||||
})?;
|
.with_hint(
|
||||||
|
"delete the generated cache entry and re-run `check`; there is no migration",
|
||||||
|
)
|
||||||
|
})?;
|
||||||
manifest.validate()?;
|
manifest.validate()?;
|
||||||
let payload = std::fs::read(&payload_path).map_err(|error| {
|
let payload = std::fs::read(&payload_path).map_err(|error| {
|
||||||
Failure::new(
|
Failure::new(
|
||||||
codes::CERTIFICATE_INVALID,
|
codes::CERTIFICATE_INVALID,
|
||||||
format!("cannot read proof payload `{}`: {error}", payload_path.display()),
|
format!(
|
||||||
|
"cannot read proof payload `{}`: {error}",
|
||||||
|
payload_path.display()
|
||||||
|
),
|
||||||
)
|
)
|
||||||
})?;
|
})?;
|
||||||
if payload.len() as u64 != manifest.proof.bytes {
|
if payload.len() as u64 != manifest.proof.bytes {
|
||||||
@@ -323,7 +332,9 @@ impl CacheIdentity {
|
|||||||
let mut sources = self.sources.clone();
|
let mut sources = self.sources.clone();
|
||||||
sources.sort();
|
sources.sort();
|
||||||
for (locator, source_digest, analysis_digest) in sources {
|
for (locator, source_digest, analysis_digest) in sources {
|
||||||
buffer.push_str(&format!("source:{locator}\0{source_digest}\0{analysis_digest}\n"));
|
buffer.push_str(&format!(
|
||||||
|
"source:{locator}\0{source_digest}\0{analysis_digest}\n"
|
||||||
|
));
|
||||||
}
|
}
|
||||||
let mut declared = self.declared.clone();
|
let mut declared = self.declared.clone();
|
||||||
declared.sort();
|
declared.sort();
|
||||||
@@ -396,7 +407,10 @@ impl CacheStore {
|
|||||||
std::fs::remove_dir_all(&directory).map_err(|error| {
|
std::fs::remove_dir_all(&directory).map_err(|error| {
|
||||||
Failure::new(
|
Failure::new(
|
||||||
codes::CERTIFICATE_INVALID,
|
codes::CERTIFICATE_INVALID,
|
||||||
format!("cannot replace stale cache entry `{}`: {error}", directory.display()),
|
format!(
|
||||||
|
"cannot replace stale cache entry `{}`: {error}",
|
||||||
|
directory.display()
|
||||||
|
),
|
||||||
)
|
)
|
||||||
})?;
|
})?;
|
||||||
}
|
}
|
||||||
@@ -422,7 +436,10 @@ fn publish_manifest_and_payload(
|
|||||||
std::fs::create_dir_all(parent).map_err(|error| {
|
std::fs::create_dir_all(parent).map_err(|error| {
|
||||||
Failure::new(
|
Failure::new(
|
||||||
codes::CERTIFICATE_INVALID,
|
codes::CERTIFICATE_INVALID,
|
||||||
format!("cannot create bundle parent `{}`: {error}", parent.display()),
|
format!(
|
||||||
|
"cannot create bundle parent `{}`: {error}",
|
||||||
|
parent.display()
|
||||||
|
),
|
||||||
)
|
)
|
||||||
})?;
|
})?;
|
||||||
let unique = format!(
|
let unique = format!(
|
||||||
@@ -437,7 +454,10 @@ fn publish_manifest_and_payload(
|
|||||||
std::fs::create_dir(&temporary).map_err(|error| {
|
std::fs::create_dir(&temporary).map_err(|error| {
|
||||||
Failure::new(
|
Failure::new(
|
||||||
codes::CERTIFICATE_INVALID,
|
codes::CERTIFICATE_INVALID,
|
||||||
format!("cannot create temporary bundle `{}`: {error}", temporary.display()),
|
format!(
|
||||||
|
"cannot create temporary bundle `{}`: {error}",
|
||||||
|
temporary.display()
|
||||||
|
),
|
||||||
)
|
)
|
||||||
})?;
|
})?;
|
||||||
let result = (|| -> Result<()> {
|
let result = (|| -> Result<()> {
|
||||||
@@ -487,7 +507,10 @@ fn write_file(path: &Path, bytes: &[u8]) -> Result<()> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn is_hex_sha256(value: &str) -> bool {
|
fn is_hex_sha256(value: &str) -> bool {
|
||||||
value.len() == 64 && value.bytes().all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
|
value.len() == 64
|
||||||
|
&& value
|
||||||
|
.bytes()
|
||||||
|
.all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn invalid<T>(message: impl Into<String>) -> Result<T> {
|
fn invalid<T>(message: impl Into<String>) -> Result<T> {
|
||||||
@@ -573,7 +596,8 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn rejects_payload_digest_mismatch_when_loading() {
|
fn rejects_payload_digest_mismatch_when_loading() {
|
||||||
let root = std::env::temp_dir().join(format!("marqdo-prove-cert-test-{}", std::process::id()));
|
let root =
|
||||||
|
std::env::temp_dir().join(format!("marqdo-prove-cert-test-{}", std::process::id()));
|
||||||
let _ = std::fs::remove_dir_all(&root);
|
let _ = std::fs::remove_dir_all(&root);
|
||||||
let mut m = manifest();
|
let mut m = manifest();
|
||||||
let payload = b"abc".to_vec();
|
let payload = b"abc".to_vec();
|
||||||
|
|||||||
+227
-40
@@ -165,7 +165,9 @@ pub fn resolve_selection(module: &ModuleData, fragment: &str) -> Result<String,
|
|||||||
candidates.join(", ")
|
candidates.join(", ")
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
.with_hint("copy the exact heading anchor from the document; Prove never picks the first match")),
|
.with_hint(
|
||||||
|
"copy the exact heading anchor from the document; Prove never picks the first match",
|
||||||
|
)),
|
||||||
FragmentResolution::DocumentRoot => Err(Diagnostic::error(
|
FragmentResolution::DocumentRoot => Err(Diagnostic::error(
|
||||||
codes::DOCUMENT_UNIT,
|
codes::DOCUMENT_UNIT,
|
||||||
"`--unit` must address one Knowledge H2, not the document root",
|
"`--unit` must address one Knowledge H2, not the document root",
|
||||||
@@ -181,7 +183,10 @@ fn build_unit(
|
|||||||
if unit.mode != "knowledge" {
|
if unit.mode != "knowledge" {
|
||||||
return Err(Diagnostic::error(
|
return Err(Diagnostic::error(
|
||||||
codes::DOCUMENT_UNIT,
|
codes::DOCUMENT_UNIT,
|
||||||
format!("proof target `{}` is not in effective Knowledge mode", display_path(unit)),
|
format!(
|
||||||
|
"proof target `{}` is not in effective Knowledge mode",
|
||||||
|
display_path(unit)
|
||||||
|
),
|
||||||
)
|
)
|
||||||
.at(unit.heading_span.unwrap_or(unit.span)));
|
.at(unit.heading_span.unwrap_or(unit.span)));
|
||||||
}
|
}
|
||||||
@@ -198,7 +203,10 @@ fn build_unit(
|
|||||||
if dependency_unit.path.last().map(String::as_str) != Some(DEPENDENCIES_HEADING) {
|
if dependency_unit.path.last().map(String::as_str) != Some(DEPENDENCIES_HEADING) {
|
||||||
return Err(Diagnostic::error(
|
return Err(Diagnostic::error(
|
||||||
codes::DOCUMENT_DEPENDENCIES_SHAPE,
|
codes::DOCUMENT_DEPENDENCIES_SHAPE,
|
||||||
format!("dependency heading of `{}` is not canonical", display_path(unit)),
|
format!(
|
||||||
|
"dependency heading of `{}` is not canonical",
|
||||||
|
display_path(unit)
|
||||||
|
),
|
||||||
)
|
)
|
||||||
.at(dependency_unit.heading_span.unwrap_or(dependency_unit.span)));
|
.at(dependency_unit.heading_span.unwrap_or(dependency_unit.span)));
|
||||||
}
|
}
|
||||||
@@ -211,7 +219,10 @@ fn build_unit(
|
|||||||
let dependency_heading_span = dependency_unit.heading_span.ok_or_else(|| {
|
let dependency_heading_span = dependency_unit.heading_span.ok_or_else(|| {
|
||||||
Diagnostic::error(
|
Diagnostic::error(
|
||||||
codes::DOCUMENT_DEPENDENCIES_SHAPE,
|
codes::DOCUMENT_DEPENDENCIES_SHAPE,
|
||||||
format!("`{DEPENDENCIES_HEADING}` of `{}` has no heading span", display_path(unit)),
|
format!(
|
||||||
|
"`{DEPENDENCIES_HEADING}` of `{}` has no heading span",
|
||||||
|
display_path(unit)
|
||||||
|
),
|
||||||
)
|
)
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
@@ -241,7 +252,10 @@ fn build_unit(
|
|||||||
let literal = math_block.literal.clone().ok_or_else(|| {
|
let literal = math_block.literal.clone().ok_or_else(|| {
|
||||||
Diagnostic::error(
|
Diagnostic::error(
|
||||||
codes::DOCUMENT_GOAL_COUNT,
|
codes::DOCUMENT_GOAL_COUNT,
|
||||||
format!("selected math block of `{}` has no literal", display_path(unit)),
|
format!(
|
||||||
|
"selected math block of `{}` has no literal",
|
||||||
|
display_path(unit)
|
||||||
|
),
|
||||||
)
|
)
|
||||||
.at(math_block.span)
|
.at(math_block.span)
|
||||||
})?;
|
})?;
|
||||||
@@ -266,7 +280,8 @@ fn build_unit(
|
|||||||
}
|
}
|
||||||
let payload_span = locate_payload(&module.source, math_block, &literal);
|
let payload_span = locate_payload(&module.source, math_block, &literal);
|
||||||
|
|
||||||
let dependencies = extract_dependencies(module, unit, dependency_unit, dependency_heading_span)?;
|
let dependencies =
|
||||||
|
extract_dependencies(module, unit, dependency_unit, dependency_heading_span)?;
|
||||||
|
|
||||||
Ok(ProofUnit {
|
Ok(ProofUnit {
|
||||||
module_id: module.id.clone(),
|
module_id: module.id.clone(),
|
||||||
@@ -290,9 +305,7 @@ fn direct_dependency_units<'a>(module: &'a ModuleData, unit: &'a Unit) -> Vec<&'
|
|||||||
module
|
module
|
||||||
.children_of(&unit.id)
|
.children_of(&unit.id)
|
||||||
.filter(|child| {
|
.filter(|child| {
|
||||||
child.level == 3
|
child.level == 3 && child.name == DEPENDENCIES_HEADING && child.kind == "section"
|
||||||
&& child.name == DEPENDENCIES_HEADING
|
|
||||||
&& child.kind == "section"
|
|
||||||
})
|
})
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
@@ -347,7 +360,10 @@ fn extract_dependencies(
|
|||||||
if dependency_unit.span.start > unit.span.end || dependency_unit.span.end > unit.span.end {
|
if dependency_unit.span.start > unit.span.end || dependency_unit.span.end > unit.span.end {
|
||||||
return Err(Diagnostic::error(
|
return Err(Diagnostic::error(
|
||||||
codes::DOCUMENT_DEPENDENCIES_SHAPE,
|
codes::DOCUMENT_DEPENDENCIES_SHAPE,
|
||||||
format!("`{DEPENDENCIES_HEADING}` section of `{}` is not inside the H2", display_path(unit)),
|
format!(
|
||||||
|
"`{DEPENDENCIES_HEADING}` section of `{}` is not inside the H2",
|
||||||
|
display_path(unit)
|
||||||
|
),
|
||||||
)
|
)
|
||||||
.at(dependency_heading_span));
|
.at(dependency_heading_span));
|
||||||
}
|
}
|
||||||
@@ -407,7 +423,10 @@ fn extract_dependencies(
|
|||||||
return Err(shape_error(
|
return Err(shape_error(
|
||||||
unit,
|
unit,
|
||||||
item.span,
|
item.span,
|
||||||
format!("`{DEPENDENCIES_HEADING}` contains a non-item node `{}`", item.kind),
|
format!(
|
||||||
|
"`{DEPENDENCIES_HEADING}` contains a non-item node `{}`",
|
||||||
|
item.kind
|
||||||
|
),
|
||||||
"the dependency list must contain only bullet items",
|
"the dependency list must contain only bullet items",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
@@ -495,12 +514,7 @@ fn locate_payload(source: &str, math_block: &Node, literal: &str) -> Option<Span
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn shape_error(
|
fn shape_error(unit: &Unit, span: Span, message: String, hint: &'static str) -> Diagnostic {
|
||||||
unit: &Unit,
|
|
||||||
span: Span,
|
|
||||||
message: String,
|
|
||||||
hint: &'static str,
|
|
||||||
) -> Diagnostic {
|
|
||||||
Diagnostic::error(
|
Diagnostic::error(
|
||||||
codes::DOCUMENT_DEPENDENCIES_SHAPE,
|
codes::DOCUMENT_DEPENDENCIES_SHAPE,
|
||||||
format!("{}: {message}", display_path(unit)),
|
format!("{}: {message}", display_path(unit)),
|
||||||
@@ -523,7 +537,17 @@ mod tests {
|
|||||||
use crate::analysis::ModuleData;
|
use crate::analysis::ModuleData;
|
||||||
use std::collections::{BTreeMap, HashMap};
|
use std::collections::{BTreeMap, HashMap};
|
||||||
|
|
||||||
fn unit(id: &str, path: &[&str], parent: Option<&str>, kind: &str, name: &str, level: u32, heading: Span, span: Span) -> Unit {
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
fn unit(
|
||||||
|
id: &str,
|
||||||
|
path: &[&str],
|
||||||
|
parent: Option<&str>,
|
||||||
|
kind: &str,
|
||||||
|
name: &str,
|
||||||
|
level: u32,
|
||||||
|
heading: Span,
|
||||||
|
span: Span,
|
||||||
|
) -> Unit {
|
||||||
serde_json::from_value(serde_json::json!({
|
serde_json::from_value(serde_json::json!({
|
||||||
"id": id,
|
"id": id,
|
||||||
"path": path,
|
"path": path,
|
||||||
@@ -541,7 +565,14 @@ mod tests {
|
|||||||
.expect("unit fixture")
|
.expect("unit fixture")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn node(kind: &str, span: Span, literal: Option<&str>, level: Option<u32>, url: Option<&str>, children: Vec<Node>) -> Node {
|
fn node(
|
||||||
|
kind: &str,
|
||||||
|
span: Span,
|
||||||
|
literal: Option<&str>,
|
||||||
|
level: Option<u32>,
|
||||||
|
url: Option<&str>,
|
||||||
|
children: Vec<Node>,
|
||||||
|
) -> Node {
|
||||||
Node {
|
Node {
|
||||||
kind: kind.to_string(),
|
kind: kind.to_string(),
|
||||||
span,
|
span,
|
||||||
@@ -583,8 +614,26 @@ mod tests {
|
|||||||
// 29..38 "### 证明依赖"
|
// 29..38 "### 证明依赖"
|
||||||
let root_id = "root:test::doc.mq.md#";
|
let root_id = "root:test::doc.mq.md#";
|
||||||
let units = vec![
|
let units = vec![
|
||||||
unit(root_id, &[], None, "root", "", 0, Span::new(0, 0), Span::new(0, source.len())),
|
unit(
|
||||||
unit("root:test::doc.mq.md#A", &["A"], Some(root_id), "knowledge", "A", 2, Span::new(0, 15), Span::new(0, source.len())),
|
root_id,
|
||||||
|
&[],
|
||||||
|
None,
|
||||||
|
"root",
|
||||||
|
"",
|
||||||
|
0,
|
||||||
|
Span::new(0, 0),
|
||||||
|
Span::new(0, source.len()),
|
||||||
|
),
|
||||||
|
unit(
|
||||||
|
"root:test::doc.mq.md#A",
|
||||||
|
&["A"],
|
||||||
|
Some(root_id),
|
||||||
|
"knowledge",
|
||||||
|
"A",
|
||||||
|
2,
|
||||||
|
Span::new(0, 15),
|
||||||
|
Span::new(0, source.len()),
|
||||||
|
),
|
||||||
unit(
|
unit(
|
||||||
"root:test::doc.mq.md#A/证明依赖",
|
"root:test::doc.mq.md#A/证明依赖",
|
||||||
&["A", "证明依赖"],
|
&["A", "证明依赖"],
|
||||||
@@ -604,7 +653,14 @@ mod tests {
|
|||||||
None,
|
None,
|
||||||
vec![
|
vec![
|
||||||
node("heading", Span::new(0, 15), None, Some(2), None, vec![]),
|
node("heading", Span::new(0, 15), None, Some(2), None, vec![]),
|
||||||
node("math_block", Span::new(17, 25), Some("x=1"), None, None, vec![]),
|
node(
|
||||||
|
"math_block",
|
||||||
|
Span::new(17, 25),
|
||||||
|
Some("x=1"),
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
vec![],
|
||||||
|
),
|
||||||
node("heading", Span::new(29, 38), None, Some(3), None, vec![]),
|
node("heading", Span::new(29, 38), None, Some(3), None, vec![]),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
@@ -631,8 +687,26 @@ mod tests {
|
|||||||
let source = "## @knowledge A\n\n$$x=1$$\n";
|
let source = "## @knowledge A\n\n$$x=1$$\n";
|
||||||
let root_id = "root:test::doc.mq.md#";
|
let root_id = "root:test::doc.mq.md#";
|
||||||
let units = vec![
|
let units = vec![
|
||||||
unit(root_id, &[], None, "root", "", 0, Span::new(0, 0), Span::new(0, source.len())),
|
unit(
|
||||||
unit("root:test::doc.mq.md#A", &["A"], Some(root_id), "knowledge", "A", 2, Span::new(0, 15), Span::new(0, source.len())),
|
root_id,
|
||||||
|
&[],
|
||||||
|
None,
|
||||||
|
"root",
|
||||||
|
"",
|
||||||
|
0,
|
||||||
|
Span::new(0, 0),
|
||||||
|
Span::new(0, source.len()),
|
||||||
|
),
|
||||||
|
unit(
|
||||||
|
"root:test::doc.mq.md#A",
|
||||||
|
&["A"],
|
||||||
|
Some(root_id),
|
||||||
|
"knowledge",
|
||||||
|
"A",
|
||||||
|
2,
|
||||||
|
Span::new(0, 15),
|
||||||
|
Span::new(0, source.len()),
|
||||||
|
),
|
||||||
];
|
];
|
||||||
let document = node(
|
let document = node(
|
||||||
"document",
|
"document",
|
||||||
@@ -642,7 +716,14 @@ mod tests {
|
|||||||
None,
|
None,
|
||||||
vec![
|
vec![
|
||||||
node("heading", Span::new(0, 15), None, Some(2), None, vec![]),
|
node("heading", Span::new(0, 15), None, Some(2), None, vec![]),
|
||||||
node("math_block", Span::new(17, 22), Some("x=1"), None, None, vec![]),
|
node(
|
||||||
|
"math_block",
|
||||||
|
Span::new(17, 22),
|
||||||
|
Some("x=1"),
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
vec![],
|
||||||
|
),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
assert!(extract(&module_with(source, units, document)).is_empty());
|
assert!(extract(&module_with(source, units, document)).is_empty());
|
||||||
@@ -653,8 +734,26 @@ mod tests {
|
|||||||
let source = "## @knowledge A\n\n$$x=1$$\n\n$$y=2$$\n\n### 证明依赖\n";
|
let source = "## @knowledge A\n\n$$x=1$$\n\n$$y=2$$\n\n### 证明依赖\n";
|
||||||
let root_id = "root:test::doc.mq.md#";
|
let root_id = "root:test::doc.mq.md#";
|
||||||
let units = vec![
|
let units = vec![
|
||||||
unit(root_id, &[], None, "root", "", 0, Span::new(0, 0), Span::new(0, source.len())),
|
unit(
|
||||||
unit("root:test::doc.mq.md#A", &["A"], Some(root_id), "knowledge", "A", 2, Span::new(0, 15), Span::new(0, source.len())),
|
root_id,
|
||||||
|
&[],
|
||||||
|
None,
|
||||||
|
"root",
|
||||||
|
"",
|
||||||
|
0,
|
||||||
|
Span::new(0, 0),
|
||||||
|
Span::new(0, source.len()),
|
||||||
|
),
|
||||||
|
unit(
|
||||||
|
"root:test::doc.mq.md#A",
|
||||||
|
&["A"],
|
||||||
|
Some(root_id),
|
||||||
|
"knowledge",
|
||||||
|
"A",
|
||||||
|
2,
|
||||||
|
Span::new(0, 15),
|
||||||
|
Span::new(0, source.len()),
|
||||||
|
),
|
||||||
unit(
|
unit(
|
||||||
"root:test::doc.mq.md#A/证明依赖",
|
"root:test::doc.mq.md#A/证明依赖",
|
||||||
&["A", "证明依赖"],
|
&["A", "证明依赖"],
|
||||||
@@ -674,8 +773,22 @@ mod tests {
|
|||||||
None,
|
None,
|
||||||
vec![
|
vec![
|
||||||
node("heading", Span::new(0, 15), None, Some(2), None, vec![]),
|
node("heading", Span::new(0, 15), None, Some(2), None, vec![]),
|
||||||
node("math_block", Span::new(17, 24), Some("x=1"), None, None, vec![]),
|
node(
|
||||||
node("math_block", Span::new(26, 33), Some("y=2"), None, None, vec![]),
|
"math_block",
|
||||||
|
Span::new(17, 24),
|
||||||
|
Some("x=1"),
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
vec![],
|
||||||
|
),
|
||||||
|
node(
|
||||||
|
"math_block",
|
||||||
|
Span::new(26, 33),
|
||||||
|
Some("y=2"),
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
vec![],
|
||||||
|
),
|
||||||
node("heading", Span::new(33, 44), None, Some(3), None, vec![]),
|
node("heading", Span::new(33, 44), None, Some(3), None, vec![]),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
@@ -684,7 +797,9 @@ mod tests {
|
|||||||
match &extracted[0] {
|
match &extracted[0] {
|
||||||
Extraction::Invalid(diagnostic) => {
|
Extraction::Invalid(diagnostic) => {
|
||||||
assert_eq!(diagnostic.code, codes::DOCUMENT_GOAL_COUNT);
|
assert_eq!(diagnostic.code, codes::DOCUMENT_GOAL_COUNT);
|
||||||
assert!(diagnostic.message.contains("exactly one display math block"));
|
assert!(diagnostic
|
||||||
|
.message
|
||||||
|
.contains("exactly one display math block"));
|
||||||
}
|
}
|
||||||
other => panic!("expected invalid, got {other:?}"),
|
other => panic!("expected invalid, got {other:?}"),
|
||||||
}
|
}
|
||||||
@@ -692,11 +807,30 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn dependency_list_must_be_one_link_per_item() {
|
fn dependency_list_must_be_one_link_per_item() {
|
||||||
let source = "## @knowledge A\n\n$$x=1$$\n\n### 证明依赖\n\n- [x](other.mq.md#B) and text\n";
|
let source =
|
||||||
|
"## @knowledge A\n\n$$x=1$$\n\n### 证明依赖\n\n- [x](other.mq.md#B) and text\n";
|
||||||
let root_id = "root:test::doc.mq.md#";
|
let root_id = "root:test::doc.mq.md#";
|
||||||
let units = vec![
|
let units = vec![
|
||||||
unit(root_id, &[], None, "root", "", 0, Span::new(0, 0), Span::new(0, source.len())),
|
unit(
|
||||||
unit("root:test::doc.mq.md#A", &["A"], Some(root_id), "knowledge", "A", 2, Span::new(0, 15), Span::new(0, source.len())),
|
root_id,
|
||||||
|
&[],
|
||||||
|
None,
|
||||||
|
"root",
|
||||||
|
"",
|
||||||
|
0,
|
||||||
|
Span::new(0, 0),
|
||||||
|
Span::new(0, source.len()),
|
||||||
|
),
|
||||||
|
unit(
|
||||||
|
"root:test::doc.mq.md#A",
|
||||||
|
&["A"],
|
||||||
|
Some(root_id),
|
||||||
|
"knowledge",
|
||||||
|
"A",
|
||||||
|
2,
|
||||||
|
Span::new(0, 15),
|
||||||
|
Span::new(0, source.len()),
|
||||||
|
),
|
||||||
unit(
|
unit(
|
||||||
"root:test::doc.mq.md#A/证明依赖",
|
"root:test::doc.mq.md#A/证明依赖",
|
||||||
&["A", "证明依赖"],
|
&["A", "证明依赖"],
|
||||||
@@ -715,11 +849,32 @@ mod tests {
|
|||||||
None,
|
None,
|
||||||
None,
|
None,
|
||||||
vec![
|
vec![
|
||||||
node("link", Span::new(42, 62), None, None, Some("other.mq.md#B"), vec![]),
|
node(
|
||||||
node("text", Span::new(62, source.len() - 1), Some(" and text"), None, None, vec![]),
|
"link",
|
||||||
|
Span::new(42, 62),
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
Some("other.mq.md#B"),
|
||||||
|
vec![],
|
||||||
|
),
|
||||||
|
node(
|
||||||
|
"text",
|
||||||
|
Span::new(62, source.len() - 1),
|
||||||
|
Some(" and text"),
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
vec![],
|
||||||
|
),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
let item = node("item", Span::new(39, source.len() - 1), None, None, None, vec![paragraph]);
|
let item = node(
|
||||||
|
"item",
|
||||||
|
Span::new(39, source.len() - 1),
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
vec![paragraph],
|
||||||
|
);
|
||||||
let list = Node {
|
let list = Node {
|
||||||
kind: "list".to_string(),
|
kind: "list".to_string(),
|
||||||
span: Span::new(39, source.len() - 1),
|
span: Span::new(39, source.len() - 1),
|
||||||
@@ -736,7 +891,14 @@ mod tests {
|
|||||||
None,
|
None,
|
||||||
vec![
|
vec![
|
||||||
node("heading", Span::new(0, 15), None, Some(2), None, vec![]),
|
node("heading", Span::new(0, 15), None, Some(2), None, vec![]),
|
||||||
node("math_block", Span::new(17, 25), Some("x=1"), None, None, vec![]),
|
node(
|
||||||
|
"math_block",
|
||||||
|
Span::new(17, 25),
|
||||||
|
Some("x=1"),
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
vec![],
|
||||||
|
),
|
||||||
node("heading", Span::new(29, 38), None, Some(3), None, vec![]),
|
node("heading", Span::new(29, 38), None, Some(3), None, vec![]),
|
||||||
list,
|
list,
|
||||||
],
|
],
|
||||||
@@ -756,8 +918,26 @@ mod tests {
|
|||||||
let source = "## A\n";
|
let source = "## A\n";
|
||||||
let root_id = "root:test::doc.mq.md#";
|
let root_id = "root:test::doc.mq.md#";
|
||||||
let units = vec![
|
let units = vec![
|
||||||
unit(root_id, &[], None, "root", "", 0, Span::new(0, 0), Span::new(0, source.len())),
|
unit(
|
||||||
unit("root:test::doc.mq.md#A", &["A"], Some(root_id), "knowledge", "A", 2, Span::new(0, 4), Span::new(0, source.len())),
|
root_id,
|
||||||
|
&[],
|
||||||
|
None,
|
||||||
|
"root",
|
||||||
|
"",
|
||||||
|
0,
|
||||||
|
Span::new(0, 0),
|
||||||
|
Span::new(0, source.len()),
|
||||||
|
),
|
||||||
|
unit(
|
||||||
|
"root:test::doc.mq.md#A",
|
||||||
|
&["A"],
|
||||||
|
Some(root_id),
|
||||||
|
"knowledge",
|
||||||
|
"A",
|
||||||
|
2,
|
||||||
|
Span::new(0, 4),
|
||||||
|
Span::new(0, source.len()),
|
||||||
|
),
|
||||||
];
|
];
|
||||||
let document = node(
|
let document = node(
|
||||||
"document",
|
"document",
|
||||||
@@ -765,7 +945,14 @@ mod tests {
|
|||||||
None,
|
None,
|
||||||
None,
|
None,
|
||||||
None,
|
None,
|
||||||
vec![node("heading", Span::new(0, 4), None, Some(2), None, vec![])],
|
vec![node(
|
||||||
|
"heading",
|
||||||
|
Span::new(0, 4),
|
||||||
|
None,
|
||||||
|
Some(2),
|
||||||
|
None,
|
||||||
|
vec![],
|
||||||
|
)],
|
||||||
);
|
);
|
||||||
let module = module_with(source, units, document);
|
let module = module_with(source, units, document);
|
||||||
let error = resolve_selection(&module, "A").unwrap_err();
|
let error = resolve_selection(&module, "A").unwrap_err();
|
||||||
|
|||||||
+1
-1
@@ -2031,7 +2031,7 @@ mod tests {
|
|||||||
fn ten_pow(exponent: u32) -> BigInt {
|
fn ten_pow(exponent: u32) -> BigInt {
|
||||||
let mut value = BigInt::from(1);
|
let mut value = BigInt::from(1);
|
||||||
for _ in 0..exponent {
|
for _ in 0..exponent {
|
||||||
value = value * BigInt::from(10);
|
value *= BigInt::from(10);
|
||||||
}
|
}
|
||||||
value
|
value
|
||||||
}
|
}
|
||||||
|
|||||||
+71
-35
@@ -172,14 +172,15 @@ impl LeanBackend {
|
|||||||
}
|
}
|
||||||
let mut command = self.lake_command()?;
|
let mut command = self.lake_command()?;
|
||||||
command.args(["build", "marqdo-replay"]);
|
command.args(["build", "marqdo-replay"]);
|
||||||
let output = self.run(command, Duration::from_secs(900), "lake build marqdo-replay")?;
|
let output = self.run(
|
||||||
|
command,
|
||||||
|
Duration::from_secs(900),
|
||||||
|
"lake build marqdo-replay",
|
||||||
|
)?;
|
||||||
if !output.status_success {
|
if !output.status_success {
|
||||||
return Err(Failure::new(
|
return Err(Failure::new(
|
||||||
codes::BACKEND_UNAVAILABLE,
|
codes::BACKEND_UNAVAILABLE,
|
||||||
format!(
|
format!("cannot build the fixed verifier: {}", tail(&output.stderr)),
|
||||||
"cannot build the fixed verifier: {}",
|
|
||||||
tail(&output.stderr)
|
|
||||||
),
|
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
if !self.config.replay_bin.is_file() {
|
if !self.config.replay_bin.is_file() {
|
||||||
@@ -193,18 +194,20 @@ impl LeanBackend {
|
|||||||
|
|
||||||
fn compute_identity(&self) -> Result<EnvironmentIdentity> {
|
fn compute_identity(&self) -> Result<EnvironmentIdentity> {
|
||||||
let lean_root = &self.config.lean_root;
|
let lean_root = &self.config.lean_root;
|
||||||
let toolchain = std::fs::read_to_string(lean_root.join("lean-toolchain")).map_err(|error| {
|
let toolchain =
|
||||||
Failure::new(
|
std::fs::read_to_string(lean_root.join("lean-toolchain")).map_err(|error| {
|
||||||
codes::BACKEND_UNAVAILABLE,
|
Failure::new(
|
||||||
format!("cannot read lean-toolchain: {error}"),
|
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(
|
let manifest_bytes =
|
||||||
codes::BACKEND_UNAVAILABLE,
|
std::fs::read(lean_root.join("lake-manifest.json")).map_err(|error| {
|
||||||
format!("cannot read lake-manifest.json: {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| {
|
let manifest: LakeManifest = serde_json::from_slice(&manifest_bytes).map_err(|error| {
|
||||||
Failure::new(
|
Failure::new(
|
||||||
codes::BACKEND_UNAVAILABLE,
|
codes::BACKEND_UNAVAILABLE,
|
||||||
@@ -228,7 +231,10 @@ impl LeanBackend {
|
|||||||
let lean_version = parse_lean_version(&version.stdout).ok_or_else(|| {
|
let lean_version = parse_lean_version(&version.stdout).ok_or_else(|| {
|
||||||
Failure::new(
|
Failure::new(
|
||||||
codes::BACKEND_UNAVAILABLE,
|
codes::BACKEND_UNAVAILABLE,
|
||||||
format!("unexpected `lean --version` output: {}", tail(&version.stdout)),
|
format!(
|
||||||
|
"unexpected `lean --version` output: {}",
|
||||||
|
tail(&version.stdout)
|
||||||
|
),
|
||||||
)
|
)
|
||||||
})?;
|
})?;
|
||||||
let replay_digest = sha256_file(&self.config.replay_bin)?;
|
let replay_digest = sha256_file(&self.config.replay_bin)?;
|
||||||
@@ -314,7 +320,10 @@ impl LeanBackend {
|
|||||||
if let Err(failure) = compile {
|
if let Err(failure) = compile {
|
||||||
let detail = failure.message.clone();
|
let detail = failure.message.clone();
|
||||||
if std::env::var_os("MARQDO_PROVE_KEEP_GENERATED").is_some() {
|
if std::env::var_os("MARQDO_PROVE_KEEP_GENERATED").is_some() {
|
||||||
eprintln!("marqdo-prove: kept failed generated module {}", target_path.display());
|
eprintln!(
|
||||||
|
"marqdo-prove: kept failed generated module {}",
|
||||||
|
target_path.display()
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
let _ = std::fs::remove_file(&target_path);
|
let _ = std::fs::remove_file(&target_path);
|
||||||
}
|
}
|
||||||
@@ -349,7 +358,8 @@ impl LeanBackend {
|
|||||||
format!("cannot stage expected proposition: {error}"),
|
format!("cannot stage expected proposition: {error}"),
|
||||||
)
|
)
|
||||||
})?;
|
})?;
|
||||||
let verified = self.verify_staged(&payload_path, &expected_path, &theorem_name, &expected_name);
|
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(&payload_path);
|
||||||
let _ = std::fs::remove_file(&expected_path);
|
let _ = std::fs::remove_file(&expected_path);
|
||||||
let evidence = verified?;
|
let evidence = verified?;
|
||||||
@@ -367,6 +377,7 @@ impl LeanBackend {
|
|||||||
/// This is the replay path: it never runs proof search, never imports the
|
/// 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
|
/// payload's `.olean`, and accepts only a kernel-replayed proof whose type
|
||||||
/// matches the expected proposition.
|
/// matches the expected proposition.
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
pub fn verify_payload(
|
pub fn verify_payload(
|
||||||
&self,
|
&self,
|
||||||
key: &str,
|
key: &str,
|
||||||
@@ -427,7 +438,8 @@ impl LeanBackend {
|
|||||||
format!("cannot stage expected proposition: {error}"),
|
format!("cannot stage expected proposition: {error}"),
|
||||||
)
|
)
|
||||||
})?;
|
})?;
|
||||||
let evidence = self.verify_staged(&payload_path, &expected_path, theorem_name, expected_name);
|
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(&payload_path);
|
||||||
let _ = std::fs::remove_file(&expected_path);
|
let _ = std::fs::remove_file(&expected_path);
|
||||||
let evidence = evidence?;
|
let evidence = evidence?;
|
||||||
@@ -462,7 +474,10 @@ impl LeanBackend {
|
|||||||
if !output.status_success {
|
if !output.status_success {
|
||||||
return Err(Failure::new(
|
return Err(Failure::new(
|
||||||
codes::PROOF_REPLAY_FAILED,
|
codes::PROOF_REPLAY_FAILED,
|
||||||
format!("independent kernel replay rejected the payload: {}", tail(&output.stderr)),
|
format!(
|
||||||
|
"independent kernel replay rejected the payload: {}",
|
||||||
|
tail(&output.stderr)
|
||||||
|
),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
// Statement/axiom verifier.
|
// Statement/axiom verifier.
|
||||||
@@ -492,7 +507,10 @@ impl LeanBackend {
|
|||||||
let report: ReplayReport = serde_json::from_str(&report_text).map_err(|error| {
|
let report: ReplayReport = serde_json::from_str(&report_text).map_err(|error| {
|
||||||
Failure::new(
|
Failure::new(
|
||||||
codes::PROOF_REPLAY_FAILED,
|
codes::PROOF_REPLAY_FAILED,
|
||||||
format!("verifier produced an unreadable report: {error}: {}", tail(&output.stdout)),
|
format!(
|
||||||
|
"verifier produced an unreadable report: {error}: {}",
|
||||||
|
tail(&output.stdout)
|
||||||
|
),
|
||||||
)
|
)
|
||||||
})?;
|
})?;
|
||||||
if !report.ok {
|
if !report.ok {
|
||||||
@@ -589,7 +607,10 @@ impl LeanBackend {
|
|||||||
std::fs::write(&path, source).map_err(|error| {
|
std::fs::write(&path, source).map_err(|error| {
|
||||||
Failure::new(
|
Failure::new(
|
||||||
codes::BACKEND_UNAVAILABLE,
|
codes::BACKEND_UNAVAILABLE,
|
||||||
format!("cannot write generated Lean source `{}`: {error}", path.display()),
|
format!(
|
||||||
|
"cannot write generated Lean source `{}`: {error}",
|
||||||
|
path.display()
|
||||||
|
),
|
||||||
)
|
)
|
||||||
})?;
|
})?;
|
||||||
Ok(path)
|
Ok(path)
|
||||||
@@ -883,12 +904,11 @@ fn render_target_module(
|
|||||||
source.push_str(" exact absurd hypothesis (by decide)\n");
|
source.push_str(" exact absurd hypothesis (by decide)\n");
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
source.push_str(&format!("public theorem {theorem_name} : {statement} := by\n"));
|
source.push_str(&format!(
|
||||||
|
"public theorem {theorem_name} : {statement} := by\n"
|
||||||
|
));
|
||||||
if !attempt.variable_names.is_empty() {
|
if !attempt.variable_names.is_empty() {
|
||||||
source.push_str(&format!(
|
source.push_str(&format!(" intros {}\n", attempt.variable_names.join(" ")));
|
||||||
" intros {}\n",
|
|
||||||
attempt.variable_names.join(" ")
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
source.push_str(" intros\n");
|
source.push_str(" intros\n");
|
||||||
if !attempt.model_sources.is_empty() {
|
if !attempt.model_sources.is_empty() {
|
||||||
@@ -934,7 +954,9 @@ fn render_expected_module(
|
|||||||
"public def {expected_name} : Prop := ¬ ({statement})\n"
|
"public def {expected_name} : Prop := ¬ ({statement})\n"
|
||||||
));
|
));
|
||||||
} else {
|
} else {
|
||||||
source.push_str(&format!("public def {expected_name} : Prop := {statement}\n"));
|
source.push_str(&format!(
|
||||||
|
"public def {expected_name} : Prop := {statement}\n"
|
||||||
|
));
|
||||||
}
|
}
|
||||||
let _ = module_name;
|
let _ = module_name;
|
||||||
source
|
source
|
||||||
@@ -1014,7 +1036,11 @@ fn parse_lean_version(stdout: &[u8]) -> Option<String> {
|
|||||||
if version.is_empty() {
|
if version.is_empty() {
|
||||||
None
|
None
|
||||||
} else {
|
} else {
|
||||||
Some(version.trim_matches(|c: char| !c.is_ascii_digit() && c != '.').to_string())
|
Some(
|
||||||
|
version
|
||||||
|
.trim_matches(|c: char| !c.is_ascii_digit() && c != '.')
|
||||||
|
.to_string(),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1034,7 +1060,10 @@ fn spawn_pipe_reader<T: Read + Send + 'static>(pipe: Option<T>) -> Option<PipeRe
|
|||||||
pipe.map(|mut pipe| {
|
pipe.map(|mut pipe| {
|
||||||
std::thread::spawn(move || {
|
std::thread::spawn(move || {
|
||||||
let mut buffer = Vec::new();
|
let mut buffer = Vec::new();
|
||||||
let _ = pipe.by_ref().take(64 * 1024 * 1024).read_to_end(&mut buffer);
|
let _ = pipe
|
||||||
|
.by_ref()
|
||||||
|
.take(64 * 1024 * 1024)
|
||||||
|
.read_to_end(&mut buffer);
|
||||||
buffer
|
buffer
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
@@ -1140,7 +1169,8 @@ mod tests {
|
|||||||
hint_terms: vec!["sq_nonneg mqx0".to_string()],
|
hint_terms: vec!["sq_nonneg mqx0".to_string()],
|
||||||
variable_names: vec!["mqx0".to_string()],
|
variable_names: vec!["mqx0".to_string()],
|
||||||
};
|
};
|
||||||
let source = render_target_module("m", "marqdoTarget_abc", &attempt.statement_source, &attempt);
|
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 theorem marqdoTarget_abc : ∀ mqx0 : Int,"));
|
||||||
assert!(source.contains("public import MarqdoProof.Generated.Target_dep"));
|
assert!(source.contains("public import MarqdoProof.Generated.Target_dep"));
|
||||||
assert!(source.contains("intros mqx0"));
|
assert!(source.contains("intros mqx0"));
|
||||||
@@ -1164,7 +1194,8 @@ mod tests {
|
|||||||
hint_terms: vec![],
|
hint_terms: vec![],
|
||||||
variable_names: vec!["mqx0".to_string(), "mqx1".to_string()],
|
variable_names: vec!["mqx0".to_string(), "mqx1".to_string()],
|
||||||
};
|
};
|
||||||
let source = render_target_module("m", "marqdoTarget_abc", &attempt.statement_source, &attempt);
|
let source =
|
||||||
|
render_target_module("m", "marqdoTarget_abc", &attempt.statement_source, &attempt);
|
||||||
assert!(source.contains("¬ (∀ mqx0 : Int, ...)"));
|
assert!(source.contains("¬ (∀ mqx0 : Int, ...)"));
|
||||||
assert!(source.contains("have counterexample := hypothesis (0 : Int) (-1 : Int)"));
|
assert!(source.contains("have counterexample := hypothesis (0 : Int) (-1 : Int)"));
|
||||||
assert!(source.contains("exact absurd counterexample (by decide)"));
|
assert!(source.contains("exact absurd counterexample (by decide)"));
|
||||||
@@ -1183,7 +1214,12 @@ mod tests {
|
|||||||
hint_terms: vec![],
|
hint_terms: vec![],
|
||||||
variable_names: vec![],
|
variable_names: vec![],
|
||||||
};
|
};
|
||||||
let source = render_expected_module("m", "marqdoExpected_abc", &attempt.statement_source, &attempt);
|
let source = render_expected_module(
|
||||||
|
"m",
|
||||||
|
"marqdoExpected_abc",
|
||||||
|
&attempt.statement_source,
|
||||||
|
&attempt,
|
||||||
|
);
|
||||||
assert!(source.contains("public def marqdoExpected_abc : Prop :="));
|
assert!(source.contains("public def marqdoExpected_abc : Prop :="));
|
||||||
assert!(!source.contains("theorem"));
|
assert!(!source.contains("theorem"));
|
||||||
assert!(!source.contains("by "));
|
assert!(!source.contains("by "));
|
||||||
|
|||||||
+78
-48
@@ -14,9 +14,7 @@ use std::collections::{BTreeMap, BTreeSet, HashMap};
|
|||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use crate::analysis::{
|
use crate::analysis::{AnalysisBackend, FragmentResolution, Function, ModuleData, Snapshot, Unit};
|
||||||
AnalysisBackend, FragmentResolution, Function, ModuleData, Snapshot, Unit,
|
|
||||||
};
|
|
||||||
use crate::document::{self, DependencyLink, Extraction, ProofUnit};
|
use crate::document::{self, DependencyLink, Extraction, ProofUnit};
|
||||||
use crate::{codes, Diagnostic, Failure, Span};
|
use crate::{codes, Diagnostic, Failure, Span};
|
||||||
|
|
||||||
@@ -47,9 +45,8 @@ impl DependencyTarget {
|
|||||||
|
|
||||||
pub fn snapshot(&self) -> &Arc<Snapshot> {
|
pub fn snapshot(&self) -> &Arc<Snapshot> {
|
||||||
match self {
|
match self {
|
||||||
DependencyTarget::Theorem { snapshot, .. } | DependencyTarget::Model { snapshot, .. } => {
|
DependencyTarget::Theorem { snapshot, .. }
|
||||||
snapshot
|
| DependencyTarget::Model { snapshot, .. } => snapshot,
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -61,18 +58,25 @@ impl DependencyTarget {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Portable locator: `relative_path#fragment-of-unit`.
|
/// Portable locator: `<relative_path>#<canonical unit path joined by />`.
|
||||||
pub fn locator(&self) -> String {
|
pub fn locator(&self) -> String {
|
||||||
let fragment = match self {
|
let (snapshot, unit_id) = match self {
|
||||||
DependencyTarget::Theorem { snapshot, unit_id, .. }
|
DependencyTarget::Theorem {
|
||||||
| DependencyTarget::Model { snapshot, unit_id, .. } => snapshot
|
snapshot, unit_id, ..
|
||||||
.modules
|
}
|
||||||
.values()
|
| DependencyTarget::Model {
|
||||||
.find_map(|module| module.unit(unit_id).map(|unit| (module, unit)))
|
snapshot, unit_id, ..
|
||||||
.map(|(module, unit)| format!("{}#{}", module.relative_path, unit.name))
|
} => (snapshot, unit_id),
|
||||||
.unwrap_or_else(|| unit_id.clone()),
|
|
||||||
};
|
};
|
||||||
fragment
|
snapshot
|
||||||
|
.modules
|
||||||
|
.values()
|
||||||
|
.find_map(|module| {
|
||||||
|
module
|
||||||
|
.unit(unit_id)
|
||||||
|
.map(|unit| format!("{}#{}", module.relative_path, unit.path.join("/")))
|
||||||
|
})
|
||||||
|
.unwrap_or_else(|| unit_id.clone())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -98,7 +102,10 @@ pub struct LoadedUnit {
|
|||||||
impl LoadedUnit {
|
impl LoadedUnit {
|
||||||
/// Stable in-run key: canonical physical path plus unit id.
|
/// Stable in-run key: canonical physical path plus unit id.
|
||||||
pub fn internal_key(&self) -> (PathBuf, String) {
|
pub fn internal_key(&self) -> (PathBuf, String) {
|
||||||
(self.snapshot.canonical_path.clone(), self.proof_unit.unit_id.clone())
|
(
|
||||||
|
self.snapshot.canonical_path.clone(),
|
||||||
|
self.proof_unit.unit_id.clone(),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -161,7 +168,10 @@ impl Linker {
|
|||||||
let root = std::fs::canonicalize(&root).map_err(|error| {
|
let root = std::fs::canonicalize(&root).map_err(|error| {
|
||||||
Failure::new(
|
Failure::new(
|
||||||
codes::LINK_OUTSIDE_ROOT,
|
codes::LINK_OUTSIDE_ROOT,
|
||||||
format!("cannot canonicalize the controlled root `{}`: {error}", root.display()),
|
format!(
|
||||||
|
"cannot canonicalize the controlled root `{}`: {error}",
|
||||||
|
root.display()
|
||||||
|
),
|
||||||
)
|
)
|
||||||
})?;
|
})?;
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
@@ -238,14 +248,16 @@ impl Linker {
|
|||||||
let module = snapshot.entry().clone();
|
let module = snapshot.entry().clone();
|
||||||
document::extract(&module)
|
document::extract(&module)
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|extraction| {
|
.inspect(|extraction| {
|
||||||
if let Extraction::Invalid(diagnostic) = &extraction {
|
if let Extraction::Invalid(diagnostic) = extraction {
|
||||||
self.extraction_cache
|
self.extraction_cache
|
||||||
.entry(path.clone())
|
.entry(path.clone())
|
||||||
.or_default()
|
.or_default()
|
||||||
.insert(format!("invalid@{}", diagnostic.span.map(|s| s.start).unwrap_or(0)), extraction.clone());
|
.insert(
|
||||||
|
format!("invalid@{}", diagnostic.span.map(|s| s.start).unwrap_or(0)),
|
||||||
|
extraction.clone(),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
extraction
|
|
||||||
})
|
})
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
@@ -263,7 +275,8 @@ impl Linker {
|
|||||||
};
|
};
|
||||||
map.insert(unit_id, extraction);
|
map.insert(unit_id, extraction);
|
||||||
}
|
}
|
||||||
self.extraction_cache.insert(path.to_path_buf(), map.clone());
|
self.extraction_cache
|
||||||
|
.insert(path.to_path_buf(), map.clone());
|
||||||
map
|
map
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -277,7 +290,7 @@ impl Linker {
|
|||||||
selection: &[String],
|
selection: &[String],
|
||||||
) -> Result<Closure, Failure> {
|
) -> Result<Closure, Failure> {
|
||||||
let entry_path = entry.canonical_path.clone();
|
let entry_path = entry.canonical_path.clone();
|
||||||
let extraction = self.extraction(&entry.entry(), &entry_path);
|
let extraction = self.extraction(entry.entry(), &entry_path);
|
||||||
let mut diagnostics: Vec<Diagnostic> = Vec::new();
|
let mut diagnostics: Vec<Diagnostic> = Vec::new();
|
||||||
|
|
||||||
// Selected entry units.
|
// Selected entry units.
|
||||||
@@ -308,7 +321,6 @@ impl Linker {
|
|||||||
documents: BTreeMap::new(),
|
documents: BTreeMap::new(),
|
||||||
units: HashMap::new(),
|
units: HashMap::new(),
|
||||||
diagnostics,
|
diagnostics,
|
||||||
depth: 0,
|
|
||||||
};
|
};
|
||||||
loader.documents.insert(entry_path.clone(), entry.clone());
|
loader.documents.insert(entry_path.clone(), entry.clone());
|
||||||
for unit_id in roots {
|
for unit_id in roots {
|
||||||
@@ -362,8 +374,11 @@ impl Linker {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
diagnostics.extend(std::mem::take(&mut closure.cycles).into_iter().map(|cycle| {
|
diagnostics.extend(
|
||||||
Diagnostic::error(
|
std::mem::take(&mut closure.cycles)
|
||||||
|
.into_iter()
|
||||||
|
.map(|cycle| {
|
||||||
|
Diagnostic::error(
|
||||||
codes::LINK_CYCLE,
|
codes::LINK_CYCLE,
|
||||||
format!("dependency cycle: {}", cycle.join(" -> ")),
|
format!("dependency cycle: {}", cycle.join(" -> ")),
|
||||||
)
|
)
|
||||||
@@ -371,7 +386,8 @@ impl Linker {
|
|||||||
"remove the cycle; first-release knowledge is a DAG, mathematical induction is \
|
"remove the cycle; first-release knowledge is a DAG, mathematical induction is \
|
||||||
not expressed through file dependencies",
|
not expressed through file dependencies",
|
||||||
)
|
)
|
||||||
}));
|
}),
|
||||||
|
);
|
||||||
closure.diagnostics.extend(diagnostics);
|
closure.diagnostics.extend(diagnostics);
|
||||||
closure.units = loaded;
|
closure.units = loaded;
|
||||||
Ok(closure)
|
Ok(closure)
|
||||||
@@ -402,7 +418,11 @@ impl Linker {
|
|||||||
match reference.state.as_str() {
|
match reference.state.as_str() {
|
||||||
"resolved" => {
|
"resolved" => {
|
||||||
let target_module_id = reference.target_module.clone().ok_or_else(|| {
|
let target_module_id = reference.target_module.clone().ok_or_else(|| {
|
||||||
link_error(link, codes::LINK_INVALID, "resolved link has no target module")
|
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(|| {
|
let target_module = source.modules.get(&target_module_id).cloned().ok_or_else(|| {
|
||||||
link_error(
|
link_error(
|
||||||
@@ -432,7 +452,11 @@ impl Linker {
|
|||||||
}
|
}
|
||||||
"not_loaded" => {
|
"not_loaded" => {
|
||||||
let candidate_path = reference.candidate_path.clone().ok_or_else(|| {
|
let candidate_path = reference.candidate_path.clone().ok_or_else(|| {
|
||||||
link_error(link, codes::LINK_INVALID, "local link has no package-relative path")
|
link_error(
|
||||||
|
link,
|
||||||
|
codes::LINK_INVALID,
|
||||||
|
"local link has no package-relative path",
|
||||||
|
)
|
||||||
})?;
|
})?;
|
||||||
validate_relative_path(&candidate_path)
|
validate_relative_path(&candidate_path)
|
||||||
.map_err(|message| link_error(link, codes::LINK_INVALID, message))?;
|
.map_err(|message| link_error(link, codes::LINK_INVALID, message))?;
|
||||||
@@ -447,9 +471,9 @@ impl Linker {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
let physical = self.root.join(&candidate_path);
|
let physical = self.root.join(&candidate_path);
|
||||||
let snapshot = self.load_document(&physical).map_err(|failure| {
|
let snapshot = self
|
||||||
link_error(link, failure.code, failure.message)
|
.load_document(&physical)
|
||||||
})?;
|
.map_err(|failure| link_error(link, failure.code, failure.message))?;
|
||||||
let target_module = snapshot
|
let target_module = snapshot
|
||||||
.module_by_relative_path(&candidate_path)
|
.module_by_relative_path(&candidate_path)
|
||||||
.cloned()
|
.cloned()
|
||||||
@@ -475,9 +499,7 @@ impl Linker {
|
|||||||
return Err(link_error(
|
return Err(link_error(
|
||||||
link,
|
link,
|
||||||
codes::LINK_CONTEXT_CONFLICT,
|
codes::LINK_CONTEXT_CONFLICT,
|
||||||
format!(
|
format!("document `{candidate_path}` has an incompatible project context"),
|
||||||
"document `{candidate_path}` has an incompatible project context"
|
|
||||||
),
|
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
let fragment = reference.fragment.clone().unwrap_or_default();
|
let fragment = reference.fragment.clone().unwrap_or_default();
|
||||||
@@ -545,7 +567,10 @@ impl Linker {
|
|||||||
"invalid" => Err(link_error(
|
"invalid" => Err(link_error(
|
||||||
link,
|
link,
|
||||||
codes::LINK_INVALID,
|
codes::LINK_INVALID,
|
||||||
format!("dependency link `{}` is not a valid local document link", link.url),
|
format!(
|
||||||
|
"dependency link `{}` is not a valid local document link",
|
||||||
|
link.url
|
||||||
|
),
|
||||||
)),
|
)),
|
||||||
"external" => Err(link_error(
|
"external" => Err(link_error(
|
||||||
link,
|
link,
|
||||||
@@ -583,7 +608,10 @@ impl Linker {
|
|||||||
return Err(link_error(
|
return Err(link_error(
|
||||||
link,
|
link,
|
||||||
codes::LINK_INVALID,
|
codes::LINK_INVALID,
|
||||||
format!("`{}` is an Exec section but not a function declaration", link.url),
|
format!(
|
||||||
|
"`{}` is an Exec section but not a function declaration",
|
||||||
|
link.url
|
||||||
|
),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
let function = module
|
let function = module
|
||||||
@@ -610,8 +638,7 @@ impl Linker {
|
|||||||
format!(
|
format!(
|
||||||
"dependency link `{}` must select a Knowledge H2 (theorem) or an Exec H2 \
|
"dependency link `{}` must select a Knowledge H2 (theorem) or an Exec H2 \
|
||||||
(program model), not `{}`",
|
(program model), not `{}`",
|
||||||
link.url,
|
link.url, unit.kind
|
||||||
unit.kind
|
|
||||||
),
|
),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
@@ -650,7 +677,6 @@ struct ClosureLoader<'a> {
|
|||||||
documents: BTreeMap<PathBuf, Arc<Snapshot>>,
|
documents: BTreeMap<PathBuf, Arc<Snapshot>>,
|
||||||
units: HashMap<(PathBuf, String), LoadedUnit>,
|
units: HashMap<(PathBuf, String), LoadedUnit>,
|
||||||
diagnostics: Vec<Diagnostic>,
|
diagnostics: Vec<Diagnostic>,
|
||||||
depth: usize,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> ClosureLoader<'a> {
|
impl<'a> ClosureLoader<'a> {
|
||||||
@@ -714,10 +740,7 @@ impl<'a> ClosureLoader<'a> {
|
|||||||
let mut resolved = Vec::new();
|
let mut resolved = Vec::new();
|
||||||
let mut unit_diagnostics = Vec::new();
|
let mut unit_diagnostics = Vec::new();
|
||||||
for link in &proof_unit.dependencies.links {
|
for link in &proof_unit.dependencies.links {
|
||||||
match self
|
match self.linker.resolve_link(&path, &snapshot, &module, link) {
|
||||||
.linker
|
|
||||||
.resolve_link(&path, &snapshot, &module, link)
|
|
||||||
{
|
|
||||||
Ok(dependency) => {
|
Ok(dependency) => {
|
||||||
let dependency_key = dependency.target.snapshot().canonical_path.clone();
|
let dependency_key = dependency.target.snapshot().canonical_path.clone();
|
||||||
self.documents
|
self.documents
|
||||||
@@ -779,7 +802,10 @@ fn visit(
|
|||||||
stack.push(key.clone());
|
stack.push(key.clone());
|
||||||
if let Some(unit) = units.get(key) {
|
if let Some(unit) = units.get(key) {
|
||||||
for dependency in &unit.dependencies {
|
for dependency in &unit.dependencies {
|
||||||
if let DependencyTarget::Theorem { snapshot, unit_id, .. } = &dependency.target {
|
if let DependencyTarget::Theorem {
|
||||||
|
snapshot, unit_id, ..
|
||||||
|
} = &dependency.target
|
||||||
|
{
|
||||||
let child = (snapshot.canonical_path.clone(), unit_id.clone());
|
let child = (snapshot.canonical_path.clone(), unit_id.clone());
|
||||||
visit(units, &child, state, order, stack, cycles);
|
visit(units, &child, state, order, stack, cycles);
|
||||||
}
|
}
|
||||||
@@ -793,7 +819,9 @@ fn visit(
|
|||||||
fn link_error(link: &DependencyLink, code: &'static str, message: impl Into<String>) -> Diagnostic {
|
fn link_error(link: &DependencyLink, code: &'static str, message: impl Into<String>) -> Diagnostic {
|
||||||
Diagnostic::error(code, message)
|
Diagnostic::error(code, message)
|
||||||
.at(link.link_span)
|
.at(link.link_span)
|
||||||
.with_hint("fix the dependency link so it points at exactly one selected unit inside the root")
|
.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.
|
/// Validate one package-relative candidate path from an Analysis reference.
|
||||||
@@ -802,7 +830,9 @@ pub fn validate_relative_path(path: &str) -> std::result::Result<(), String> {
|
|||||||
return Err("link target path is empty".to_string());
|
return Err("link target path is empty".to_string());
|
||||||
}
|
}
|
||||||
if path.starts_with('/') || path.starts_with('\\') || path.contains('\\') {
|
if path.starts_with('/') || path.starts_with('\\') || path.contains('\\') {
|
||||||
return Err(format!("link target path `{path}` is absolute or uses a platform separator"));
|
return Err(format!(
|
||||||
|
"link target path `{path}` is absolute or uses a platform separator"
|
||||||
|
));
|
||||||
}
|
}
|
||||||
if let Some((before, _)) = path.split_once(':') {
|
if let Some((before, _)) = path.split_once(':') {
|
||||||
let scheme = before;
|
let scheme = before;
|
||||||
|
|||||||
+2
-8
@@ -96,15 +96,9 @@ fn emit(report: prove::Report, json: bool) -> u8 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
print!("{}", report.render_text());
|
// Diagnostics are part of the textual rendering; progress and
|
||||||
// Diagnostics are already part of the textual rendering; progress and
|
|
||||||
// engineering detail stay on stderr without polluting JSON stdout.
|
// engineering detail stay on stderr without polluting JSON stdout.
|
||||||
for diagnostic in &report.diagnostics {
|
print!("{}", report.render_text());
|
||||||
eprintln!(
|
|
||||||
"{} [{}] {}",
|
|
||||||
diagnostic.severity, diagnostic.code, diagnostic.message
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
status.exit_code() as u8
|
status.exit_code() as u8
|
||||||
}
|
}
|
||||||
|
|||||||
+79
-45
@@ -154,11 +154,11 @@ pub fn build_model(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Validate the straight-line body shape: assignments..., one final return.
|
// Validate the straight-line body shape: assignments..., one final return.
|
||||||
let mut statements = function.body.iter();
|
let statements = function.body.iter();
|
||||||
let mut assignments: Vec<(&str, &Expression)> = Vec::new();
|
let mut assignments: Vec<(&str, &Expression)> = Vec::new();
|
||||||
let mut returned: Option<&Expression> = None;
|
let mut returned: Option<&Expression> = None;
|
||||||
let mut index = 0usize;
|
let mut index = 0usize;
|
||||||
while let Some(statement) = statements.next() {
|
for statement in statements {
|
||||||
validate_span(module, statement.span(), "statement")?;
|
validate_span(module, statement.span(), "statement")?;
|
||||||
if returned.is_some() {
|
if returned.is_some() {
|
||||||
return Err(unsupported(
|
return Err(unsupported(
|
||||||
@@ -183,7 +183,10 @@ pub fn build_model(
|
|||||||
));
|
));
|
||||||
};
|
};
|
||||||
if name.is_empty() {
|
if name.is_empty() {
|
||||||
return Err(unsupported(statement.span(), "empty local assignment target"));
|
return Err(unsupported(
|
||||||
|
statement.span(),
|
||||||
|
"empty local assignment target",
|
||||||
|
));
|
||||||
}
|
}
|
||||||
assignments.push((name.as_str(), value));
|
assignments.push((name.as_str(), value));
|
||||||
}
|
}
|
||||||
@@ -219,7 +222,10 @@ pub fn build_model(
|
|||||||
Statement::Break { .. } => {
|
Statement::Break { .. } => {
|
||||||
return Err(unsupported(
|
return Err(unsupported(
|
||||||
statement.span(),
|
statement.span(),
|
||||||
format!("function `{}` uses `break` outside a supported loop", function.local_name),
|
format!(
|
||||||
|
"function `{}` uses `break` outside a supported loop",
|
||||||
|
function.local_name
|
||||||
|
),
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
Statement::Continue { .. } => {
|
Statement::Continue { .. } => {
|
||||||
@@ -295,7 +301,13 @@ pub fn build_model(
|
|||||||
.map(|name| format!("{name}: Int"))
|
.map(|name| format!("{name}: Int"))
|
||||||
.collect::<Vec<_>>()
|
.collect::<Vec<_>>()
|
||||||
.join(", "),
|
.join(", "),
|
||||||
render_summary(return_expression, &assignments, &environment, module, function)?
|
render_summary(
|
||||||
|
return_expression,
|
||||||
|
&assignments,
|
||||||
|
&environment,
|
||||||
|
module,
|
||||||
|
function
|
||||||
|
)?
|
||||||
);
|
);
|
||||||
Ok(ModelDef {
|
Ok(ModelDef {
|
||||||
function_id: function.id.clone(),
|
function_id: function.id.clone(),
|
||||||
@@ -337,7 +349,10 @@ fn render_lean(
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
let Some(serde_json::Value::String(text)) = value else {
|
let Some(serde_json::Value::String(text)) = value else {
|
||||||
return Err(unsupported(*span, "integer literal has a non-string Analysis value"));
|
return Err(unsupported(
|
||||||
|
*span,
|
||||||
|
"integer literal has a non-string Analysis value",
|
||||||
|
));
|
||||||
};
|
};
|
||||||
if text.len() > crate::limits::MAX_LITERAL_DIGITS {
|
if text.len() > crate::limits::MAX_LITERAL_DIGITS {
|
||||||
return Err(unsupported(
|
return Err(unsupported(
|
||||||
@@ -428,29 +443,25 @@ fn render_original(
|
|||||||
function: &Function,
|
function: &Function,
|
||||||
) -> std::result::Result<String, Diagnostic> {
|
) -> std::result::Result<String, Diagnostic> {
|
||||||
let _ = environment;
|
let _ = environment;
|
||||||
render_pretty(expression, module, function)
|
let _ = module;
|
||||||
|
render_pretty(expression, function)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn render_pretty(
|
fn render_pretty(
|
||||||
expression: &Expression,
|
expression: &Expression,
|
||||||
module: &ModuleData,
|
|
||||||
function: &Function,
|
function: &Function,
|
||||||
) -> std::result::Result<String, Diagnostic> {
|
) -> std::result::Result<String, Diagnostic> {
|
||||||
match expression {
|
match expression {
|
||||||
Expression::Literal { ty, value, .. } => {
|
Expression::Literal { ty: _, value, .. } => {
|
||||||
let Some(serde_json::Value::String(text)) = value else {
|
let Some(serde_json::Value::String(text)) = value else {
|
||||||
return Err(unsupported(expression.span(), "non-string integer literal"));
|
return Err(unsupported(expression.span(), "non-string integer literal"));
|
||||||
};
|
};
|
||||||
let normalized = normalize_integer_literal(text).ok_or_else(|| {
|
let normalized = normalize_integer_literal(text)
|
||||||
unsupported(expression.span(), "invalid integer literal")
|
.ok_or_else(|| unsupported(expression.span(), "invalid integer literal"))?;
|
||||||
})?;
|
|
||||||
Ok(normalized)
|
Ok(normalized)
|
||||||
}
|
}
|
||||||
Expression::Variable { name, .. } => Ok(name.clone()),
|
Expression::Variable { name, .. } => Ok(name.clone()),
|
||||||
Expression::Unary { operand, .. } => Ok(format!(
|
Expression::Unary { operand, .. } => Ok(format!("-{}", render_pretty(operand, function)?)),
|
||||||
"-{}",
|
|
||||||
render_pretty(operand, module, function)?
|
|
||||||
)),
|
|
||||||
Expression::Binary {
|
Expression::Binary {
|
||||||
op, left, right, ..
|
op, left, right, ..
|
||||||
} => {
|
} => {
|
||||||
@@ -467,8 +478,8 @@ fn render_pretty(
|
|||||||
};
|
};
|
||||||
Ok(format!(
|
Ok(format!(
|
||||||
"({} {operator} {})",
|
"({} {operator} {})",
|
||||||
render_pretty(left, module, function)?,
|
render_pretty(left, function)?,
|
||||||
render_pretty(right, module, function)?
|
render_pretty(right, function)?
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
other => Err(unsupported(
|
other => Err(unsupported(
|
||||||
@@ -594,11 +605,11 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn expression(json: serde_json::Value) -> Expression {
|
fn function_fixture(
|
||||||
serde_json::from_value(json).expect("expression fixture")
|
body: serde_json::Value,
|
||||||
}
|
params: serde_json::Value,
|
||||||
|
kind: &str,
|
||||||
fn function_fixture(body: serde_json::Value, params: serde_json::Value, kind: &str) -> Function {
|
) -> Function {
|
||||||
serde_json::from_value(serde_json::json!({
|
serde_json::from_value(serde_json::json!({
|
||||||
"id": "root:t::arith.mq.md::整数计算.square",
|
"id": "root:t::arith.mq.md::整数计算.square",
|
||||||
"unit_id": "root:t::arith.mq.md#整数计算/square",
|
"unit_id": "root:t::arith.mq.md#整数计算/square",
|
||||||
@@ -647,7 +658,8 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn square_model_maps_to_exact_lean_definition() {
|
fn square_model_maps_to_exact_lean_definition() {
|
||||||
let function = function_fixture(serde_json::json!([return_stmt(binary("mul", variable("x"), variable("x")))]),
|
let function = function_fixture(
|
||||||
|
serde_json::json!([return_stmt(binary("mul", variable("x"), variable("x")))]),
|
||||||
serde_json::json!([int_param("x", 20, 30)]),
|
serde_json::json!([int_param("x", 20, 30)]),
|
||||||
"explicit",
|
"explicit",
|
||||||
);
|
);
|
||||||
@@ -657,11 +669,18 @@ mod tests {
|
|||||||
assert!(model.lean_name.starts_with("marqdoModel_"));
|
assert!(model.lean_name.starts_with("marqdoModel_"));
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
model.lean_definition(),
|
model.lean_definition(),
|
||||||
"@[expose] public def marqdoModel_".to_string() + &model.key + " (mqp0 : Int) : Int := (mqp0 * mqp0)\n"
|
"@[expose] public def marqdoModel_".to_string()
|
||||||
|
+ &model.key
|
||||||
|
+ " (mqp0 : Int) : Int := (mqp0 * mqp0)\n"
|
||||||
);
|
);
|
||||||
assert_eq!(model.digest.len(), 64);
|
assert_eq!(model.digest.len(), 64);
|
||||||
assert!(model.source_summary.starts_with("def square(x: Int) : Int := (x * x)"));
|
assert!(model
|
||||||
assert_eq!(lean_module_name(&model), format!("MarqdoProof.Generated.Model_{}", model.key));
|
.source_summary
|
||||||
|
.starts_with("def square(x: Int) : Int := (x * x)"));
|
||||||
|
assert_eq!(
|
||||||
|
lean_module_name(&model),
|
||||||
|
format!("MarqdoProof.Generated.Model_{}", model.key)
|
||||||
|
);
|
||||||
// deterministic
|
// deterministic
|
||||||
let again = build_model(&function, &module(200)).expect("square model");
|
let again = build_model(&function, &module(200)).expect("square model");
|
||||||
assert_eq!(model.key, again.key);
|
assert_eq!(model.key, again.key);
|
||||||
@@ -670,7 +689,8 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn zero_parameter_constant_model() {
|
fn zero_parameter_constant_model() {
|
||||||
let function = function_fixture(serde_json::json!([return_stmt(int_literal("42"))]),
|
let function = function_fixture(
|
||||||
|
serde_json::json!([return_stmt(int_literal("42"))]),
|
||||||
serde_json::json!([]),
|
serde_json::json!([]),
|
||||||
"explicit",
|
"explicit",
|
||||||
);
|
);
|
||||||
@@ -681,7 +701,8 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn rebinding_creates_fresh_slots() {
|
fn rebinding_creates_fresh_slots() {
|
||||||
let function = function_fixture(serde_json::json!([
|
let function = function_fixture(
|
||||||
|
serde_json::json!([
|
||||||
assign("y", binary("add", variable("x"), int_literal("1"))),
|
assign("y", binary("add", variable("x"), int_literal("1"))),
|
||||||
assign("y", binary("mul", variable("y"), variable("y"))),
|
assign("y", binary("mul", variable("y"), variable("y"))),
|
||||||
return_stmt(variable("y"))
|
return_stmt(variable("y"))
|
||||||
@@ -698,7 +719,8 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn negative_literals_and_unary_minus_render_exactly() {
|
fn negative_literals_and_unary_minus_render_exactly() {
|
||||||
let function = function_fixture(serde_json::json!([return_stmt(serde_json::json!({
|
let function = function_fixture(
|
||||||
|
serde_json::json!([return_stmt(serde_json::json!({
|
||||||
"kind": "unary", "op": "neg", "operand": int_literal("-7"),
|
"kind": "unary", "op": "neg", "operand": int_literal("-7"),
|
||||||
"span": {"start": 0, "end": 20}
|
"span": {"start": 0, "end": 20}
|
||||||
}))]),
|
}))]),
|
||||||
@@ -717,14 +739,16 @@ mod tests {
|
|||||||
fn rejects_unsupported_shapes() {
|
fn rejects_unsupported_shapes() {
|
||||||
let cases: Vec<(Function, &str)> = vec![
|
let cases: Vec<(Function, &str)> = vec![
|
||||||
(
|
(
|
||||||
function_fixture(serde_json::json!([return_stmt(variable("x"))]),
|
function_fixture(
|
||||||
|
serde_json::json!([return_stmt(variable("x"))]),
|
||||||
serde_json::json!([int_param("x", 20, 30)]),
|
serde_json::json!([int_param("x", 20, 30)]),
|
||||||
"inferred",
|
"inferred",
|
||||||
),
|
),
|
||||||
"inferred",
|
"inferred",
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
function_fixture(serde_json::json!([return_stmt(variable("x"))]),
|
function_fixture(
|
||||||
|
serde_json::json!([return_stmt(variable("x"))]),
|
||||||
serde_json::json!([{
|
serde_json::json!([{
|
||||||
"name": "x", "required": true, "type": "Float",
|
"name": "x", "required": true, "type": "Float",
|
||||||
"default": null, "span": {"start": 20, "end": 30}
|
"default": null, "span": {"start": 20, "end": 30}
|
||||||
@@ -734,35 +758,44 @@ mod tests {
|
|||||||
"type",
|
"type",
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
function_fixture(serde_json::json!([return_stmt(int_literal("1.5"))]),
|
function_fixture(
|
||||||
|
serde_json::json!([return_stmt(int_literal("1.5"))]),
|
||||||
serde_json::json!([]),
|
serde_json::json!([]),
|
||||||
"explicit",
|
"explicit",
|
||||||
),
|
),
|
||||||
"literal",
|
"literal",
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
function_fixture(serde_json::json!([return_stmt(binary("div", variable("x"), int_literal("2")))]),
|
function_fixture(
|
||||||
|
serde_json::json!([return_stmt(binary(
|
||||||
|
"div",
|
||||||
|
variable("x"),
|
||||||
|
int_literal("2")
|
||||||
|
))]),
|
||||||
serde_json::json!([int_param("x", 20, 30)]),
|
serde_json::json!([int_param("x", 20, 30)]),
|
||||||
"explicit",
|
"explicit",
|
||||||
),
|
),
|
||||||
"operator",
|
"operator",
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
function_fixture(serde_json::json!([return_stmt(variable("y"))]),
|
function_fixture(
|
||||||
|
serde_json::json!([return_stmt(variable("y"))]),
|
||||||
serde_json::json!([int_param("x", 20, 30)]),
|
serde_json::json!([int_param("x", 20, 30)]),
|
||||||
"explicit",
|
"explicit",
|
||||||
),
|
),
|
||||||
"before it is defined",
|
"before it is defined",
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
function_fixture(serde_json::json!([assign("x", int_literal("1"))]),
|
function_fixture(
|
||||||
|
serde_json::json!([assign("x", int_literal("1"))]),
|
||||||
serde_json::json!([]),
|
serde_json::json!([]),
|
||||||
"explicit",
|
"explicit",
|
||||||
),
|
),
|
||||||
"return",
|
"return",
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
function_fixture(serde_json::json!([
|
function_fixture(
|
||||||
|
serde_json::json!([
|
||||||
return_stmt(int_literal("1")),
|
return_stmt(int_literal("1")),
|
||||||
assign("x", int_literal("2"))
|
assign("x", int_literal("2"))
|
||||||
]),
|
]),
|
||||||
@@ -772,7 +805,8 @@ mod tests {
|
|||||||
"after",
|
"after",
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
function_fixture(serde_json::json!([{
|
function_fixture(
|
||||||
|
serde_json::json!([{
|
||||||
"kind": "branch",
|
"kind": "branch",
|
||||||
"arms": [{"condition": int_literal("1"), "condition_span": {"start": 0, "end": 1},
|
"arms": [{"condition": int_literal("1"), "condition_span": {"start": 0, "end": 1},
|
||||||
"body": [], "span": {"start": 0, "end": 1}}],
|
"body": [], "span": {"start": 0, "end": 1}}],
|
||||||
@@ -788,22 +822,21 @@ mod tests {
|
|||||||
let error = build_model(&function, &module(400)).expect_err(needle);
|
let error = build_model(&function, &module(400)).expect_err(needle);
|
||||||
assert_eq!(error.code, codes::MODEL_UNSUPPORTED);
|
assert_eq!(error.code, codes::MODEL_UNSUPPORTED);
|
||||||
let whole = format!("{error:?}");
|
let whole = format!("{error:?}");
|
||||||
assert!(
|
assert!(whole.contains(needle), "expected {needle:?} in {whole:?}");
|
||||||
whole.contains(needle),
|
|
||||||
"expected {needle:?} in {whole:?}"
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn huge_literal_is_rejected_and_leading_zeros_normalized() {
|
fn huge_literal_is_rejected_and_leading_zeros_normalized() {
|
||||||
let huge = "9".repeat(5000);
|
let huge = "9".repeat(5000);
|
||||||
let function = function_fixture(serde_json::json!([return_stmt(int_literal(&huge))]),
|
let function = function_fixture(
|
||||||
|
serde_json::json!([return_stmt(int_literal(&huge))]),
|
||||||
serde_json::json!([]),
|
serde_json::json!([]),
|
||||||
"explicit",
|
"explicit",
|
||||||
);
|
);
|
||||||
assert!(build_model(&function, &module(200)).is_err());
|
assert!(build_model(&function, &module(200)).is_err());
|
||||||
let function = function_fixture(serde_json::json!([return_stmt(int_literal("00042"))]),
|
let function = function_fixture(
|
||||||
|
serde_json::json!([return_stmt(int_literal("00042"))]),
|
||||||
serde_json::json!([]),
|
serde_json::json!([]),
|
||||||
"explicit",
|
"explicit",
|
||||||
);
|
);
|
||||||
@@ -813,7 +846,8 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn index_place_assignment_is_rejected() {
|
fn index_place_assignment_is_rejected() {
|
||||||
let function = function_fixture(serde_json::json!([{
|
let function = function_fixture(
|
||||||
|
serde_json::json!([{
|
||||||
"kind": "assign",
|
"kind": "assign",
|
||||||
"target": {"kind": "index", "base": variable("x"),
|
"target": {"kind": "index", "base": variable("x"),
|
||||||
"index": int_literal("0"), "span": {"start": 0, "end": 10}},
|
"index": int_literal("0"), "span": {"start": 0, "end": 10}},
|
||||||
|
|||||||
+217
-171
@@ -8,7 +8,6 @@
|
|||||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::Instant;
|
|
||||||
|
|
||||||
use num_bigint::BigInt;
|
use num_bigint::BigInt;
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
@@ -19,7 +18,7 @@ use crate::certificate::{
|
|||||||
ProofPayload, SourceBinding, TargetIdentity, ToolIdentity, ALLOWED_AXIOMS, PAYLOAD_FILE,
|
ProofPayload, SourceBinding, TargetIdentity, ToolIdentity, ALLOWED_AXIOMS, PAYLOAD_FILE,
|
||||||
};
|
};
|
||||||
use crate::document::{self, Extraction, ProofUnit};
|
use crate::document::{self, Extraction, ProofUnit};
|
||||||
use crate::formula::{self, FormulaError, Goal};
|
use crate::formula::{self, FormulaError, FormulaErrorKind, Goal};
|
||||||
use crate::lean::{Attempt, Evidence, LeanBackend, ModelSource, ProofAttempt};
|
use crate::lean::{Attempt, Evidence, LeanBackend, ModelSource, ProofAttempt};
|
||||||
use crate::linker::{Closure, DependencyTarget, Linker, LoadedUnit};
|
use crate::linker::{Closure, DependencyTarget, Linker, LoadedUnit};
|
||||||
use crate::model::{self, ModelDef};
|
use crate::model::{self, ModelDef};
|
||||||
@@ -149,17 +148,18 @@ pub struct Report {
|
|||||||
|
|
||||||
impl Report {
|
impl Report {
|
||||||
pub fn status(&self) -> RunStatus {
|
pub fn status(&self) -> RunStatus {
|
||||||
if self.status == "failure" {
|
match self.status.as_str() {
|
||||||
RunStatus::Failure
|
"failure" => RunStatus::Failure,
|
||||||
} else {
|
"unverified" => RunStatus::Unverified,
|
||||||
match self.targets.as_slice() {
|
_ => {
|
||||||
[] => RunStatus::Success,
|
if self
|
||||||
targets => {
|
.targets
|
||||||
if targets.iter().all(|target| target.outcome == "verified") {
|
.iter()
|
||||||
RunStatus::Success
|
.all(|target| target.outcome == "verified")
|
||||||
} else {
|
{
|
||||||
RunStatus::Unverified
|
RunStatus::Success
|
||||||
}
|
} else {
|
||||||
|
RunStatus::Unverified
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -178,7 +178,7 @@ impl Report {
|
|||||||
target.outcome, target.title, target.scope, target.freshness
|
target.outcome, target.title, target.scope, target.freshness
|
||||||
));
|
));
|
||||||
out.push_str(&format!(
|
out.push_str(&format!(
|
||||||
" source: {}# {}\n",
|
" source: {} ({})\n",
|
||||||
target.source.locator, target.source.unit_id
|
target.source.locator, target.source.unit_id
|
||||||
));
|
));
|
||||||
out.push_str(&format!(" statement: {}\n", target.statement.normalized));
|
out.push_str(&format!(" statement: {}\n", target.statement.normalized));
|
||||||
@@ -207,8 +207,8 @@ impl Report {
|
|||||||
let unused: Vec<&str> = target
|
let unused: Vec<&str> = target
|
||||||
.declared_dependencies
|
.declared_dependencies
|
||||||
.iter()
|
.iter()
|
||||||
.map(|dependency| dependency.unit_id.as_str())
|
.map(|dependency| dependency.locator.as_str())
|
||||||
.filter(|unit_id| !target.used_dependencies.iter().any(|used| used == unit_id))
|
.filter(|locator| !target.used_dependencies.iter().any(|used| used == locator))
|
||||||
.collect();
|
.collect();
|
||||||
if !unused.is_empty() {
|
if !unused.is_empty() {
|
||||||
out.push_str(&format!(" declared but not used: {}\n", unused.join(", ")));
|
out.push_str(&format!(" declared but not used: {}\n", unused.join(", ")));
|
||||||
@@ -281,11 +281,13 @@ pub fn run(invocation: Invocation) -> Report {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn marqdo_bin() -> Result<PathBuf> {
|
fn marqdo_bin() -> Result<PathBuf> {
|
||||||
let bin = std::env::var_os("MARQDO_BIN").map(PathBuf::from).unwrap_or_else(|| {
|
let bin = std::env::var_os("MARQDO_BIN")
|
||||||
// Tool installs always inject an absolute MARQDO_BIN; a developer build
|
.map(PathBuf::from)
|
||||||
// may rely on PATH, which we resolve explicitly here.
|
.unwrap_or_else(|| {
|
||||||
PathBuf::from("marqdo")
|
// 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() {
|
if bin.is_absolute() {
|
||||||
return Ok(bin);
|
return Ok(bin);
|
||||||
}
|
}
|
||||||
@@ -308,7 +310,6 @@ struct Context {
|
|||||||
linker: Linker,
|
linker: Linker,
|
||||||
cache: CacheStore,
|
cache: CacheStore,
|
||||||
lean: Option<Arc<LeanBackend>>,
|
lean: Option<Arc<LeanBackend>>,
|
||||||
task_started: Instant,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Context {
|
impl Context {
|
||||||
@@ -316,15 +317,7 @@ impl Context {
|
|||||||
if self.lean.is_none() {
|
if self.lean.is_none() {
|
||||||
self.lean = Some(Arc::new(LeanBackend::discover()?));
|
self.lean = Some(Arc::new(LeanBackend::discover()?));
|
||||||
}
|
}
|
||||||
Ok(self
|
Ok(self.lean.as_ref().expect("just initialized").clone())
|
||||||
.lean
|
|
||||||
.as_ref()
|
|
||||||
.expect("just initialized")
|
|
||||||
.clone())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn work_dir(&self) -> PathBuf {
|
|
||||||
self.cache.work_dir()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -345,7 +338,6 @@ fn open_context(entry: &Path, explicit_root: Option<&Path>) -> Result<Context> {
|
|||||||
linker,
|
linker,
|
||||||
cache,
|
cache,
|
||||||
lean: None,
|
lean: None,
|
||||||
task_started: Instant::now(),
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -388,12 +380,11 @@ fn check_inner(context: &mut Context, options: &CheckOptions) -> Result<Report>
|
|||||||
selected.push((unit.unit_id.clone(), unit.clone()));
|
selected.push((unit.unit_id.clone(), unit.clone()));
|
||||||
found = true;
|
found = true;
|
||||||
}
|
}
|
||||||
Extraction::Invalid(diagnostic) => {
|
Extraction::Invalid(diagnostic)
|
||||||
if diagnostic.code == codes::DOCUMENT_DEPENDENCIES_SHAPE
|
if (diagnostic.code == codes::DOCUMENT_DEPENDENCIES_SHAPE
|
||||||
|| diagnostic.code == codes::DOCUMENT_GOAL_COUNT
|
|| diagnostic.code == codes::DOCUMENT_GOAL_COUNT) =>
|
||||||
{
|
{
|
||||||
diagnostics.push(diagnostic.clone());
|
diagnostics.push(diagnostic.clone());
|
||||||
}
|
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
@@ -432,20 +423,29 @@ fn check_inner(context: &mut Context, options: &CheckOptions) -> Result<Report>
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if selected.is_empty() {
|
if selected.is_empty() {
|
||||||
return Ok(empty_report(context, "check", &entry, RunStatus::Success, diagnostics));
|
return Ok(empty_report(
|
||||||
|
context,
|
||||||
|
"check",
|
||||||
|
&entry,
|
||||||
|
RunStatus::Success,
|
||||||
|
diagnostics,
|
||||||
|
));
|
||||||
}
|
}
|
||||||
// Dependency closure.
|
// Dependency closure.
|
||||||
let selection: Vec<String> = selected.iter().map(|(unit_id, _)| unit_id.clone()).collect();
|
let selection: Vec<String> = selected
|
||||||
|
.iter()
|
||||||
|
.map(|(unit_id, _)| unit_id.clone())
|
||||||
|
.collect();
|
||||||
let closure = context.linker.resolve_closure(&entry, &selection)?;
|
let closure = context.linker.resolve_closure(&entry, &selection)?;
|
||||||
diagnostics.extend(closure.diagnostics.iter().cloned());
|
diagnostics.extend(closure.diagnostics.iter().cloned());
|
||||||
|
|
||||||
// Prepare every closure unit (formula + program model validation).
|
// Prepare every closure unit (formula + program model validation).
|
||||||
let mut nodes = prepare_closure(&closure, &mut diagnostics);
|
let nodes = prepare_closure(&closure, &mut diagnostics);
|
||||||
// Process in dependency-first order.
|
// Process in dependency-first order.
|
||||||
let mut outcomes: HashMap<usize, UnitResult> = HashMap::new();
|
let mut outcomes: HashMap<usize, UnitResult> = HashMap::new();
|
||||||
let indices: Vec<usize> = (0..nodes.len()).collect();
|
let indices: Vec<usize> = (0..nodes.len()).collect();
|
||||||
for index in indices {
|
for index in indices {
|
||||||
let result = process_node(context, &mut nodes, &mut outcomes, index);
|
let result = process_node(context, &nodes, &mut outcomes, index);
|
||||||
outcomes.insert(index, result);
|
outcomes.insert(index, result);
|
||||||
}
|
}
|
||||||
// Report selected entry units in document order.
|
// Report selected entry units in document order.
|
||||||
@@ -460,17 +460,21 @@ fn check_inner(context: &mut Context, options: &CheckOptions) -> Result<Report>
|
|||||||
let Some(result) = outcomes.get(&index) else {
|
let Some(result) = outcomes.get(&index) else {
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
targets.push(build_target_report(context, &nodes[index], result));
|
targets.push(build_target_report(context, &nodes, &nodes[index], result));
|
||||||
}
|
}
|
||||||
// Export requested bundles.
|
// Export requested bundles.
|
||||||
if let Some(out) = &options.out {
|
if let Some(out) = &options.out {
|
||||||
export_bundles(context, &nodes, &outcomes, out, &targets)?;
|
export_bundles(context, &nodes, &outcomes, out, &targets)?;
|
||||||
}
|
}
|
||||||
let status = if targets.iter().all(|target| target.outcome == "verified") {
|
let has_error_diagnostic = diagnostics
|
||||||
RunStatus::Success
|
.iter()
|
||||||
} else {
|
.any(|diagnostic| diagnostic.severity == Severity::Error);
|
||||||
RunStatus::Unverified
|
let status =
|
||||||
};
|
if !has_error_diagnostic && targets.iter().all(|target| target.outcome == "verified") {
|
||||||
|
RunStatus::Success
|
||||||
|
} else {
|
||||||
|
RunStatus::Unverified
|
||||||
|
};
|
||||||
let report = Report {
|
let report = Report {
|
||||||
schema: RESULT_SCHEMA.to_string(),
|
schema: RESULT_SCHEMA.to_string(),
|
||||||
schema_version: RESULT_SCHEMA_VERSION,
|
schema_version: RESULT_SCHEMA_VERSION,
|
||||||
@@ -495,6 +499,15 @@ fn empty_report(
|
|||||||
status: RunStatus,
|
status: RunStatus,
|
||||||
diagnostics: Vec<Diagnostic>,
|
diagnostics: Vec<Diagnostic>,
|
||||||
) -> Report {
|
) -> Report {
|
||||||
|
let status = if status == RunStatus::Success
|
||||||
|
&& diagnostics
|
||||||
|
.iter()
|
||||||
|
.any(|diagnostic| diagnostic.severity == Severity::Error)
|
||||||
|
{
|
||||||
|
RunStatus::Unverified
|
||||||
|
} else {
|
||||||
|
status
|
||||||
|
};
|
||||||
Report {
|
Report {
|
||||||
schema: RESULT_SCHEMA.to_string(),
|
schema: RESULT_SCHEMA.to_string(),
|
||||||
schema_version: RESULT_SCHEMA_VERSION,
|
schema_version: RESULT_SCHEMA_VERSION,
|
||||||
@@ -520,12 +533,14 @@ struct PreparedModel {
|
|||||||
definition: ModelDef,
|
definition: ModelDef,
|
||||||
link_text: String,
|
link_text: String,
|
||||||
source: ModelSource,
|
source: ModelSource,
|
||||||
|
unit_path: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
struct PreparedNode {
|
struct PreparedNode {
|
||||||
loaded: LoadedUnit,
|
loaded: LoadedUnit,
|
||||||
goal: Option<Goal>,
|
goal: Option<Goal>,
|
||||||
formula_error: Option<Diagnostic>,
|
formula_error: Option<Diagnostic>,
|
||||||
|
prepared_outcome: Outcome,
|
||||||
models: Vec<PreparedModel>,
|
models: Vec<PreparedModel>,
|
||||||
alias_map: BTreeMap<String, String>,
|
alias_map: BTreeMap<String, String>,
|
||||||
statement_source: String,
|
statement_source: String,
|
||||||
@@ -564,6 +579,7 @@ fn prepare_closure(closure: &Closure, diagnostics: &mut Vec<Diagnostic>) -> Vec<
|
|||||||
loaded: loaded.clone(),
|
loaded: loaded.clone(),
|
||||||
goal: None,
|
goal: None,
|
||||||
formula_error: None,
|
formula_error: None,
|
||||||
|
prepared_outcome: Outcome::Invalid,
|
||||||
models: Vec::new(),
|
models: Vec::new(),
|
||||||
alias_map: BTreeMap::new(),
|
alias_map: BTreeMap::new(),
|
||||||
statement_source: String::new(),
|
statement_source: String::new(),
|
||||||
@@ -604,7 +620,13 @@ fn prepare_closure(closure: &Closure, diagnostics: &mut Vec<Diagnostic>) -> Vec<
|
|||||||
Err(error) => {
|
Err(error) => {
|
||||||
let diagnostic = formula_diagnostic(&loaded, &error);
|
let diagnostic = formula_diagnostic(&loaded, &error);
|
||||||
diagnostics.push(diagnostic.clone());
|
diagnostics.push(diagnostic.clone());
|
||||||
node.formula_error = Some(diagnostic);
|
node.formula_error = Some(diagnostic.clone());
|
||||||
|
node.prepared_error = Some(diagnostic);
|
||||||
|
node.prepared_outcome = if error.kind == FormulaErrorKind::Unsupported {
|
||||||
|
Outcome::Unsupported
|
||||||
|
} else {
|
||||||
|
Outcome::Invalid
|
||||||
|
};
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -612,41 +634,44 @@ fn prepare_closure(closure: &Closure, diagnostics: &mut Vec<Diagnostic>) -> Vec<
|
|||||||
for dependency in &loaded.dependencies {
|
for dependency in &loaded.dependencies {
|
||||||
match &dependency.target {
|
match &dependency.target {
|
||||||
DependencyTarget::Theorem {
|
DependencyTarget::Theorem {
|
||||||
snapshot,
|
snapshot, unit_id, ..
|
||||||
unit_id,
|
|
||||||
..
|
|
||||||
} => {
|
} => {
|
||||||
let key = (snapshot.canonical_path.clone(), unit_id.clone());
|
let key = (snapshot.canonical_path.clone(), unit_id.clone());
|
||||||
match index_of.get(&key) {
|
match index_of.get(&key) {
|
||||||
Some(index) => node.theorem_dependencies.push(*index),
|
Some(index) => node.theorem_dependencies.push(*index),
|
||||||
None => {
|
None => {
|
||||||
node.prepared_error = Some(Diagnostic::error(
|
node.prepared_error = Some(
|
||||||
codes::LINK_INVALID,
|
Diagnostic::error(
|
||||||
format!(
|
codes::LINK_INVALID,
|
||||||
"dependency `{}` was not part of the resolved closure",
|
format!(
|
||||||
dependency.link.url
|
"dependency `{}` was not part of the resolved closure",
|
||||||
),
|
dependency.link.url
|
||||||
)
|
),
|
||||||
.at(dependency.link.link_span));
|
)
|
||||||
|
.at(dependency.link.link_span),
|
||||||
|
);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
DependencyTarget::Model {
|
DependencyTarget::Model {
|
||||||
snapshot,
|
snapshot, function, ..
|
||||||
function,
|
|
||||||
..
|
|
||||||
} => {
|
} => {
|
||||||
let module = snapshot
|
let module = snapshot
|
||||||
.modules
|
.modules
|
||||||
.values()
|
.values()
|
||||||
.find(|module| module.function(&function.id).is_some());
|
.find(|module| module.function(&function.id).is_some());
|
||||||
let Some(module) = module else {
|
let Some(module) = module else {
|
||||||
node.prepared_error = Some(Diagnostic::error(
|
node.prepared_error = Some(
|
||||||
codes::LINK_CONTEXT_CONFLICT,
|
Diagnostic::error(
|
||||||
format!("program model target `{}` is not in its module", dependency.link.url),
|
codes::LINK_CONTEXT_CONFLICT,
|
||||||
)
|
format!(
|
||||||
.at(dependency.link.link_span));
|
"program model target `{}` is not in its module",
|
||||||
|
dependency.link.url
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.at(dependency.link.link_span),
|
||||||
|
);
|
||||||
break;
|
break;
|
||||||
};
|
};
|
||||||
match model::build_model(function, module) {
|
match model::build_model(function, module) {
|
||||||
@@ -667,10 +692,18 @@ fn prepare_closure(closure: &Closure, diagnostics: &mut Vec<Diagnostic>) -> Vec<
|
|||||||
definition.lean_name.clone(),
|
definition.lean_name.clone(),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
let unit_path = snapshot
|
||||||
|
.modules
|
||||||
|
.values()
|
||||||
|
.find(|module| module.function(&function.id).is_some())
|
||||||
|
.and_then(|module| module.unit(&function.unit_id))
|
||||||
|
.map(|unit| unit.path.clone())
|
||||||
|
.unwrap_or_default();
|
||||||
node.models.push(PreparedModel {
|
node.models.push(PreparedModel {
|
||||||
definition,
|
definition,
|
||||||
link_text: dependency.link.text.clone(),
|
link_text: dependency.link.text.clone(),
|
||||||
source,
|
source,
|
||||||
|
unit_path,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
Err(diagnostic) => {
|
Err(diagnostic) => {
|
||||||
@@ -718,15 +751,17 @@ fn prepare_closure(closure: &Closure, diagnostics: &mut Vec<Diagnostic>) -> Vec<
|
|||||||
if node.prepared_error.is_none() {
|
if node.prepared_error.is_none() {
|
||||||
for model in &node.models {
|
for model in &node.models {
|
||||||
if !used.contains(&model.link_text) {
|
if !used.contains(&model.link_text) {
|
||||||
node.prepared_error = Some(Diagnostic::error(
|
node.prepared_error = Some(
|
||||||
codes::MODEL_UNBOUND_ALIAS,
|
Diagnostic::error(
|
||||||
format!(
|
codes::MODEL_UNBOUND_ALIAS,
|
||||||
|
format!(
|
||||||
"program model link `{}` is declared but the formula never calls \
|
"program model link `{}` is declared but the formula never calls \
|
||||||
`\\operatorname{{{}}}(...)`",
|
`\\operatorname{{{}}}(...)`",
|
||||||
model.link_text, model.link_text
|
model.link_text, model.link_text
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
.at(node.loaded.proof_unit.goal.block_span));
|
.at(node.loaded.proof_unit.goal.block_span),
|
||||||
|
);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -756,12 +791,12 @@ fn prepare_closure(closure: &Closure, diagnostics: &mut Vec<Diagnostic>) -> Vec<
|
|||||||
fn formula_diagnostic(loaded: &LoadedUnit, error: &FormulaError) -> Diagnostic {
|
fn formula_diagnostic(loaded: &LoadedUnit, error: &FormulaError) -> Diagnostic {
|
||||||
let span = error.offset.and_then(|offset| {
|
let span = error.offset.and_then(|offset| {
|
||||||
let goal = &loaded.proof_unit.goal;
|
let goal = &loaded.proof_unit.goal;
|
||||||
goal.payload_span.and_then(|payload| {
|
goal.payload_span.map(|payload| {
|
||||||
let start = payload.start + offset;
|
let start = payload.start + offset;
|
||||||
if start <= payload.end && start <= loaded.module.source.len() {
|
if start <= payload.end && start <= loaded.module.source.len() {
|
||||||
Some(Span::new(start, start.min(payload.end)))
|
Span::new(start, start.min(payload.end))
|
||||||
} else {
|
} else {
|
||||||
Some(goal.block_span)
|
goal.block_span
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
@@ -786,7 +821,7 @@ fn formula_diagnostic(loaded: &LoadedUnit, error: &FormulaError) -> Diagnostic {
|
|||||||
|
|
||||||
fn process_node(
|
fn process_node(
|
||||||
context: &mut Context,
|
context: &mut Context,
|
||||||
nodes: &mut [PreparedNode],
|
nodes: &[PreparedNode],
|
||||||
outcomes: &mut HashMap<usize, UnitResult>,
|
outcomes: &mut HashMap<usize, UnitResult>,
|
||||||
index: usize,
|
index: usize,
|
||||||
) -> UnitResult {
|
) -> UnitResult {
|
||||||
@@ -795,19 +830,14 @@ fn process_node(
|
|||||||
(node.theorem_key.clone(), node.scope)
|
(node.theorem_key.clone(), node.scope)
|
||||||
};
|
};
|
||||||
if let Some(diagnostic) = nodes[index].prepared_error.clone() {
|
if let Some(diagnostic) = nodes[index].prepared_error.clone() {
|
||||||
return simple_result(
|
let outcome = nodes[index].prepared_outcome;
|
||||||
Outcome::Invalid,
|
return simple_result(outcome, scope, vec![diagnostic]);
|
||||||
scope,
|
|
||||||
vec![diagnostic],
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
// Blocked dependencies: every declared theorem dependency must be verified.
|
// Blocked dependencies: every declared theorem dependency must be verified.
|
||||||
let mut blocked: Vec<Diagnostic> = Vec::new();
|
let mut blocked: Vec<Diagnostic> = Vec::new();
|
||||||
for dependency in &nodes[index].loaded.dependencies {
|
for dependency in &nodes[index].loaded.dependencies {
|
||||||
if let DependencyTarget::Theorem {
|
if let DependencyTarget::Theorem {
|
||||||
snapshot,
|
snapshot, unit_id, ..
|
||||||
unit_id,
|
|
||||||
..
|
|
||||||
} = &dependency.target
|
} = &dependency.target
|
||||||
{
|
{
|
||||||
let found = nodes.iter().position(|node| {
|
let found = nodes.iter().position(|node| {
|
||||||
@@ -816,20 +846,27 @@ fn process_node(
|
|||||||
});
|
});
|
||||||
match found.and_then(|found| outcomes.get(&found)) {
|
match found.and_then(|found| outcomes.get(&found)) {
|
||||||
Some(result) if result.outcome == Outcome::Verified => {}
|
Some(result) if result.outcome == Outcome::Verified => {}
|
||||||
Some(result) => blocked.push(Diagnostic::error(
|
Some(result) => blocked.push(
|
||||||
codes::LINK_MISSING,
|
Diagnostic::error(
|
||||||
format!(
|
codes::LINK_MISSING,
|
||||||
"dependency `{}` has outcome `{}`; it cannot be used as an axiom",
|
format!(
|
||||||
dependency.link.url,
|
"dependency `{}` has outcome `{}`; it cannot be used as an axiom",
|
||||||
result.outcome.as_str()
|
dependency.link.url,
|
||||||
),
|
result.outcome.as_str()
|
||||||
)
|
),
|
||||||
.at(dependency.link.link_span)),
|
)
|
||||||
None => blocked.push(Diagnostic::error(
|
.at(dependency.link.link_span),
|
||||||
codes::LINK_MISSING,
|
),
|
||||||
format!("dependency `{}` was not verified in this run", dependency.link.url),
|
None => blocked.push(
|
||||||
)
|
Diagnostic::error(
|
||||||
.at(dependency.link.link_span)),
|
codes::LINK_MISSING,
|
||||||
|
format!(
|
||||||
|
"dependency `{}` was not verified in this run",
|
||||||
|
dependency.link.url
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.at(dependency.link.link_span),
|
||||||
|
),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -885,12 +922,18 @@ fn process_node(
|
|||||||
.theorem_dependencies
|
.theorem_dependencies
|
||||||
.iter()
|
.iter()
|
||||||
.map(|dependency| {
|
.map(|dependency| {
|
||||||
format!("MarqdoProof.Generated.Target_{}", nodes[*dependency].theorem_key)
|
format!(
|
||||||
|
"MarqdoProof.Generated.Target_{}",
|
||||||
|
nodes[*dependency].theorem_key
|
||||||
|
)
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
// Ensure every dependency artifact is importable.
|
// Ensure every dependency artifact is importable.
|
||||||
for dependency in &nodes[index].theorem_dependencies {
|
for dependency in &nodes[index].theorem_dependencies {
|
||||||
let module = format!("MarqdoProof.Generated.Target_{}", nodes[*dependency].theorem_key);
|
let module = format!(
|
||||||
|
"MarqdoProof.Generated.Target_{}",
|
||||||
|
nodes[*dependency].theorem_key
|
||||||
|
);
|
||||||
if !lean.build_olean_path(&module).is_file() {
|
if !lean.build_olean_path(&module).is_file() {
|
||||||
let artifact = context
|
let artifact = context
|
||||||
.cache
|
.cache
|
||||||
@@ -965,10 +1008,7 @@ fn process_node(
|
|||||||
key: theorem_key.clone(),
|
key: theorem_key.clone(),
|
||||||
statement_source: nodes[index].statement_source.clone(),
|
statement_source: nodes[index].statement_source.clone(),
|
||||||
refuted: true,
|
refuted: true,
|
||||||
witnesses: witnesses
|
witnesses: witnesses.iter().map(|value| value.to_string()).collect(),
|
||||||
.iter()
|
|
||||||
.map(|value| value.to_string())
|
|
||||||
.collect(),
|
|
||||||
model_sources: model_sources.clone(),
|
model_sources: model_sources.clone(),
|
||||||
imports: Vec::new(),
|
imports: Vec::new(),
|
||||||
dependency_names: Vec::new(),
|
dependency_names: Vec::new(),
|
||||||
@@ -1023,6 +1063,7 @@ fn process_node(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
fn replay_cached(
|
fn replay_cached(
|
||||||
context: &mut Context,
|
context: &mut Context,
|
||||||
nodes: &[PreparedNode],
|
nodes: &[PreparedNode],
|
||||||
@@ -1057,7 +1098,10 @@ fn replay_cached(
|
|||||||
Ok(evidence) => {
|
Ok(evidence) => {
|
||||||
// Install the artifact so later searches can import this theorem.
|
// Install the artifact so later searches can import this theorem.
|
||||||
let module = format!("MarqdoProof.Generated.Target_{}", nodes[index].theorem_key);
|
let module = format!("MarqdoProof.Generated.Target_{}", nodes[index].theorem_key);
|
||||||
let artifact = context.cache.artifacts_dir().join(format!("{module}.olean"));
|
let artifact = context
|
||||||
|
.cache
|
||||||
|
.artifacts_dir()
|
||||||
|
.join(format!("{module}.olean"));
|
||||||
if let Ok(bytes) = std::fs::read(&artifact) {
|
if let Ok(bytes) = std::fs::read(&artifact) {
|
||||||
let _ = lean.install_olean(&module, &bytes);
|
let _ = lean.install_olean(&module, &bytes);
|
||||||
}
|
}
|
||||||
@@ -1118,7 +1162,6 @@ fn publish_success(
|
|||||||
expected_name: &str,
|
expected_name: &str,
|
||||||
cache_key: &str,
|
cache_key: &str,
|
||||||
) -> UnitResult {
|
) -> UnitResult {
|
||||||
let node = &nodes[index];
|
|
||||||
let manifest = match build_manifest(
|
let manifest = match build_manifest(
|
||||||
context,
|
context,
|
||||||
nodes,
|
nodes,
|
||||||
@@ -1152,7 +1195,11 @@ fn publish_success(
|
|||||||
if let Ok(lean) = context.lean() {
|
if let Ok(lean) = context.lean() {
|
||||||
let module = format!(
|
let module = format!(
|
||||||
"MarqdoProof.Generated.{}_{}",
|
"MarqdoProof.Generated.{}_{}",
|
||||||
if outcome == Outcome::Refuted { "Refute" } else { "Target" },
|
if outcome == Outcome::Refuted {
|
||||||
|
"Refute"
|
||||||
|
} else {
|
||||||
|
"Target"
|
||||||
|
},
|
||||||
theorem_key
|
theorem_key
|
||||||
);
|
);
|
||||||
if let Ok(bytes) = lean.read_olean(&module) {
|
if let Ok(bytes) = lean.read_olean(&module) {
|
||||||
@@ -1170,7 +1217,11 @@ fn publish_success(
|
|||||||
axioms: evidence.axioms.clone(),
|
axioms: evidence.axioms.clone(),
|
||||||
certificate: Some(CertificateReport {
|
certificate: Some(CertificateReport {
|
||||||
cache_key: manifest.cache_key.clone(),
|
cache_key: manifest.cache_key.clone(),
|
||||||
directory: context.cache.bundle_dir(&manifest.cache_key).display().to_string(),
|
directory: context
|
||||||
|
.cache
|
||||||
|
.bundle_dir(&manifest.cache_key)
|
||||||
|
.display()
|
||||||
|
.to_string(),
|
||||||
payload_sha256: manifest.proof.sha256.clone(),
|
payload_sha256: manifest.proof.sha256.clone(),
|
||||||
outcome: manifest.target.outcome.clone(),
|
outcome: manifest.target.outcome.clone(),
|
||||||
}),
|
}),
|
||||||
@@ -1240,9 +1291,7 @@ fn compute_cache_key_rec(
|
|||||||
for dependency in &node.loaded.dependencies {
|
for dependency in &node.loaded.dependencies {
|
||||||
match &dependency.target {
|
match &dependency.target {
|
||||||
DependencyTarget::Theorem {
|
DependencyTarget::Theorem {
|
||||||
snapshot,
|
snapshot, unit_id, ..
|
||||||
unit_id,
|
|
||||||
..
|
|
||||||
} => {
|
} => {
|
||||||
let dependency_index = nodes.iter().position(|candidate| {
|
let dependency_index = nodes.iter().position(|candidate| {
|
||||||
candidate.loaded.snapshot.canonical_path == snapshot.canonical_path
|
candidate.loaded.snapshot.canonical_path == snapshot.canonical_path
|
||||||
@@ -1254,15 +1303,14 @@ fn compute_cache_key_rec(
|
|||||||
format!("dependency `{}` is not in the closure", dependency.link.url),
|
format!("dependency `{}` is not in the closure", dependency.link.url),
|
||||||
));
|
));
|
||||||
};
|
};
|
||||||
let dependency_key = compute_cache_key_rec(
|
let dependency_key =
|
||||||
nodes,
|
compute_cache_key_rec(nodes, dependency_index, environment_id, memo, visiting)?;
|
||||||
dependency_index,
|
|
||||||
environment_id,
|
|
||||||
memo,
|
|
||||||
visiting,
|
|
||||||
)?;
|
|
||||||
sources.push((
|
sources.push((
|
||||||
nodes[dependency_index].loaded.snapshot.relative_path.clone(),
|
nodes[dependency_index]
|
||||||
|
.loaded
|
||||||
|
.snapshot
|
||||||
|
.relative_path
|
||||||
|
.clone(),
|
||||||
nodes[dependency_index].loaded.module.source_digest.clone(),
|
nodes[dependency_index].loaded.module.source_digest.clone(),
|
||||||
nodes[dependency_index]
|
nodes[dependency_index]
|
||||||
.loaded
|
.loaded
|
||||||
@@ -1272,15 +1320,17 @@ fn compute_cache_key_rec(
|
|||||||
));
|
));
|
||||||
declared.push((
|
declared.push((
|
||||||
"theorem".to_string(),
|
"theorem".to_string(),
|
||||||
nodes[dependency_index].loaded.snapshot.relative_path.clone(),
|
nodes[dependency_index]
|
||||||
|
.loaded
|
||||||
|
.snapshot
|
||||||
|
.relative_path
|
||||||
|
.clone(),
|
||||||
unit_id.clone(),
|
unit_id.clone(),
|
||||||
dependency_key,
|
dependency_key,
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
DependencyTarget::Model {
|
DependencyTarget::Model {
|
||||||
snapshot,
|
snapshot, function, ..
|
||||||
function,
|
|
||||||
..
|
|
||||||
} => {
|
} => {
|
||||||
if let Some(model) = node
|
if let Some(model) = node
|
||||||
.models
|
.models
|
||||||
@@ -1422,19 +1472,15 @@ fn build_manifest(
|
|||||||
let lean = context.lean()?;
|
let lean = context.lean()?;
|
||||||
let environment = lean.identity().clone();
|
let environment = lean.identity().clone();
|
||||||
let mut sources: BTreeMap<String, SourceBinding> = BTreeMap::new();
|
let mut sources: BTreeMap<String, SourceBinding> = BTreeMap::new();
|
||||||
let mut add_source = |locator: String,
|
let mut add_source =
|
||||||
module_id: String,
|
|locator: String, module_id: String, source_digest: String, analysis_digest: String| {
|
||||||
source_digest: String,
|
sources.entry(locator.clone()).or_insert(SourceBinding {
|
||||||
analysis_digest: String| {
|
|
||||||
sources
|
|
||||||
.entry(locator.clone())
|
|
||||||
.or_insert(SourceBinding {
|
|
||||||
locator,
|
locator,
|
||||||
module_id,
|
module_id,
|
||||||
source_digest,
|
source_digest,
|
||||||
analysis_digest,
|
analysis_digest,
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
add_source(
|
add_source(
|
||||||
node.loaded.snapshot.relative_path.clone(),
|
node.loaded.snapshot.relative_path.clone(),
|
||||||
node.loaded.module.id.clone(),
|
node.loaded.module.id.clone(),
|
||||||
@@ -1445,9 +1491,7 @@ fn build_manifest(
|
|||||||
for dependency in &node.loaded.dependencies {
|
for dependency in &node.loaded.dependencies {
|
||||||
match &dependency.target {
|
match &dependency.target {
|
||||||
DependencyTarget::Theorem {
|
DependencyTarget::Theorem {
|
||||||
snapshot,
|
snapshot, unit_id, ..
|
||||||
unit_id,
|
|
||||||
..
|
|
||||||
} => {
|
} => {
|
||||||
let dependency_node = nodes.iter().find(|candidate| {
|
let dependency_node = nodes.iter().find(|candidate| {
|
||||||
candidate.loaded.snapshot.canonical_path == snapshot.canonical_path
|
candidate.loaded.snapshot.canonical_path == snapshot.canonical_path
|
||||||
@@ -1467,11 +1511,7 @@ fn build_manifest(
|
|||||||
locator: format!(
|
locator: format!(
|
||||||
"{}#{}",
|
"{}#{}",
|
||||||
snapshot.relative_path,
|
snapshot.relative_path,
|
||||||
dependency_node
|
dependency_node.loaded.proof_unit.path.join("/")
|
||||||
.loaded
|
|
||||||
.proof_unit
|
|
||||||
.path
|
|
||||||
.join("/")
|
|
||||||
),
|
),
|
||||||
unit_id: unit_id.clone(),
|
unit_id: unit_id.clone(),
|
||||||
link_text: dependency.link.text.clone(),
|
link_text: dependency.link.text.clone(),
|
||||||
@@ -1479,9 +1519,7 @@ fn build_manifest(
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
DependencyTarget::Model {
|
DependencyTarget::Model {
|
||||||
snapshot,
|
snapshot, function, ..
|
||||||
function,
|
|
||||||
..
|
|
||||||
} => {
|
} => {
|
||||||
add_source(
|
add_source(
|
||||||
snapshot.relative_path.clone(),
|
snapshot.relative_path.clone(),
|
||||||
@@ -1594,15 +1632,13 @@ fn map_project_decls(
|
|||||||
}
|
}
|
||||||
if let Some(key) = decl.strip_prefix("marqdoModel_") {
|
if let Some(key) = decl.strip_prefix("marqdoModel_") {
|
||||||
for node in nodes {
|
for node in nodes {
|
||||||
if let Some(model) = node
|
if let Some(model) = node.models.iter().find(|model| {
|
||||||
.models
|
model.definition.key == key || model.definition.lean_name == *decl
|
||||||
.iter()
|
}) {
|
||||||
.find(|model| model.definition.key == key || model.definition.lean_name == *decl)
|
|
||||||
{
|
|
||||||
mapped.insert(format!(
|
mapped.insert(format!(
|
||||||
"{}#{}",
|
"{}#{}",
|
||||||
model.definition.locator,
|
model.definition.locator,
|
||||||
model.definition.function_id
|
model.unit_path.join("/")
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1618,6 +1654,7 @@ fn map_project_decls(
|
|||||||
|
|
||||||
fn build_target_report(
|
fn build_target_report(
|
||||||
_context: &mut Context,
|
_context: &mut Context,
|
||||||
|
nodes: &[PreparedNode],
|
||||||
node: &PreparedNode,
|
node: &PreparedNode,
|
||||||
result: &UnitResult,
|
result: &UnitResult,
|
||||||
) -> TargetReport {
|
) -> TargetReport {
|
||||||
@@ -1630,21 +1667,15 @@ fn build_target_report(
|
|||||||
.map(|dependency| {
|
.map(|dependency| {
|
||||||
let binding = match &dependency.target {
|
let binding = match &dependency.target {
|
||||||
DependencyTarget::Theorem {
|
DependencyTarget::Theorem {
|
||||||
snapshot,
|
snapshot, unit_id, ..
|
||||||
unit_id,
|
} => nodes
|
||||||
..
|
|
||||||
} => node
|
|
||||||
.theorem_dependencies
|
|
||||||
.iter()
|
.iter()
|
||||||
.find(|index| {
|
.find(|candidate| {
|
||||||
let _ = index;
|
candidate.loaded.snapshot.canonical_path == snapshot.canonical_path
|
||||||
false
|
&& candidate.loaded.proof_unit.unit_id == *unit_id
|
||||||
})
|
})
|
||||||
.map(|_| String::new())
|
.map(|candidate| format!("marqdoTarget_{}", candidate.theorem_key))
|
||||||
.unwrap_or_else(|| {
|
.unwrap_or_default(),
|
||||||
let _ = (snapshot, unit_id);
|
|
||||||
String::new()
|
|
||||||
}),
|
|
||||||
DependencyTarget::Model { function, .. } => node
|
DependencyTarget::Model { function, .. } => node
|
||||||
.models
|
.models
|
||||||
.iter()
|
.iter()
|
||||||
@@ -1689,7 +1720,11 @@ fn build_target_report(
|
|||||||
transitive_dependencies: result.transitive.clone(),
|
transitive_dependencies: result.transitive.clone(),
|
||||||
axioms: result.axioms.clone(),
|
axioms: result.axioms.clone(),
|
||||||
certificate,
|
certificate,
|
||||||
diagnostics: result.diagnostics.iter().map(DiagnosticReport::from).collect(),
|
diagnostics: result
|
||||||
|
.diagnostics
|
||||||
|
.iter()
|
||||||
|
.map(DiagnosticReport::from)
|
||||||
|
.collect(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1715,10 +1750,16 @@ fn export_bundles(
|
|||||||
&& node.loaded.proof_unit.unit_id == target.unit_id
|
&& node.loaded.proof_unit.unit_id == target.unit_id
|
||||||
})
|
})
|
||||||
.ok_or_else(|| {
|
.ok_or_else(|| {
|
||||||
crate::Failure::new(codes::CERTIFICATE_INVALID, "cannot locate the verified target")
|
crate::Failure::new(
|
||||||
|
codes::CERTIFICATE_INVALID,
|
||||||
|
"cannot locate the verified target",
|
||||||
|
)
|
||||||
})?;
|
})?;
|
||||||
let result = outcomes.get(&index).ok_or_else(|| {
|
let result = outcomes.get(&index).ok_or_else(|| {
|
||||||
crate::Failure::new(codes::CERTIFICATE_INVALID, "target has no verification result")
|
crate::Failure::new(
|
||||||
|
codes::CERTIFICATE_INVALID,
|
||||||
|
"target has no verification result",
|
||||||
|
)
|
||||||
})?;
|
})?;
|
||||||
let manifest = result.manifest.as_ref().ok_or_else(|| {
|
let manifest = result.manifest.as_ref().ok_or_else(|| {
|
||||||
crate::Failure::new(codes::CERTIFICATE_INVALID, "target has no proof manifest")
|
crate::Failure::new(codes::CERTIFICATE_INVALID, "target has no proof manifest")
|
||||||
@@ -1753,10 +1794,16 @@ fn export_bundles(
|
|||||||
&& node.loaded.proof_unit.unit_id == target.unit_id
|
&& node.loaded.proof_unit.unit_id == target.unit_id
|
||||||
})
|
})
|
||||||
.ok_or_else(|| {
|
.ok_or_else(|| {
|
||||||
crate::Failure::new(codes::CERTIFICATE_INVALID, "cannot locate the verified target")
|
crate::Failure::new(
|
||||||
|
codes::CERTIFICATE_INVALID,
|
||||||
|
"cannot locate the verified target",
|
||||||
|
)
|
||||||
})?;
|
})?;
|
||||||
let result = outcomes.get(&index).ok_or_else(|| {
|
let result = outcomes.get(&index).ok_or_else(|| {
|
||||||
crate::Failure::new(codes::CERTIFICATE_INVALID, "target has no verification result")
|
crate::Failure::new(
|
||||||
|
codes::CERTIFICATE_INVALID,
|
||||||
|
"target has no verification result",
|
||||||
|
)
|
||||||
})?;
|
})?;
|
||||||
let manifest = result.manifest.as_ref().ok_or_else(|| {
|
let manifest = result.manifest.as_ref().ok_or_else(|| {
|
||||||
crate::Failure::new(codes::CERTIFICATE_INVALID, "target has no proof manifest")
|
crate::Failure::new(codes::CERTIFICATE_INVALID, "target has no proof manifest")
|
||||||
@@ -1847,9 +1894,9 @@ fn replay_inner(context: &mut Context, options: &ReplayOptions) -> Result<Report
|
|||||||
};
|
};
|
||||||
let closure = context
|
let closure = context
|
||||||
.linker
|
.linker
|
||||||
.resolve_closure(&entry, &[unit.unit_id.clone()])?;
|
.resolve_closure(&entry, std::slice::from_ref(&unit.unit_id))?;
|
||||||
let mut diagnostics = closure.diagnostics.clone();
|
let mut diagnostics = closure.diagnostics.clone();
|
||||||
let mut nodes = prepare_closure(&closure, &mut diagnostics);
|
let nodes = prepare_closure(&closure, &mut diagnostics);
|
||||||
let Some(index) = nodes.iter().position(|node| {
|
let Some(index) = nodes.iter().position(|node| {
|
||||||
node.loaded.snapshot.relative_path == entry.relative_path
|
node.loaded.snapshot.relative_path == entry.relative_path
|
||||||
&& node.loaded.proof_unit.unit_id == bundle.manifest.target.unit_id
|
&& node.loaded.proof_unit.unit_id == bundle.manifest.target.unit_id
|
||||||
@@ -1956,7 +2003,7 @@ fn replay_inner(context: &mut Context, options: &ReplayOptions) -> Result<Report
|
|||||||
simple_result(Outcome::Invalid, nodes[index].scope, Vec::new())
|
simple_result(Outcome::Invalid, nodes[index].scope, Vec::new())
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let target = build_target_report(context, &nodes[index], &result);
|
let target = build_target_report(context, &nodes, &nodes[index], &result);
|
||||||
Ok(Report {
|
Ok(Report {
|
||||||
schema: RESULT_SCHEMA.to_string(),
|
schema: RESULT_SCHEMA.to_string(),
|
||||||
schema_version: RESULT_SCHEMA_VERSION,
|
schema_version: RESULT_SCHEMA_VERSION,
|
||||||
@@ -1989,4 +2036,3 @@ pub fn theorem_key(locator: &str, path: &[String], goal_digest: &str) -> String
|
|||||||
pub fn allowed_axioms() -> &'static [&'static str] {
|
pub fn allowed_axioms() -> &'static [&'static str] {
|
||||||
&ALLOWED_AXIOMS
|
&ALLOWED_AXIOMS
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -52,7 +52,10 @@ fn real_cli_extracts_vector_fixture() {
|
|||||||
);
|
);
|
||||||
assert_eq!(unit.dependencies.links.len(), 2);
|
assert_eq!(unit.dependencies.links.len(), 2);
|
||||||
assert_eq!(unit.dependencies.links[0].text, "整数平方非负性");
|
assert_eq!(unit.dependencies.links[0].text, "整数平方非负性");
|
||||||
assert_eq!(unit.dependencies.links[0].url, "algebra.mq.md#整数平方非负性");
|
assert_eq!(
|
||||||
|
unit.dependencies.links[0].url,
|
||||||
|
"algebra.mq.md#整数平方非负性"
|
||||||
|
);
|
||||||
assert!(unit.goal.payload_span.is_some());
|
assert!(unit.goal.payload_span.is_some());
|
||||||
let source = &snapshot.entry().source;
|
let source = &snapshot.entry().source;
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
|
|||||||
@@ -0,0 +1,238 @@
|
|||||||
|
//! Negative/contract tests through the real CLI without requiring the Lean
|
||||||
|
//! backend: selection, document shape, formulas and link closure.
|
||||||
|
//!
|
||||||
|
//! The tests skip (and say so) when `MARQDO_BIN` is not set. Each assertion is
|
||||||
|
//! about a reported diagnostic code and the process exit code, never about
|
||||||
|
//! presentation text.
|
||||||
|
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::process::Command;
|
||||||
|
|
||||||
|
fn cli() -> Option<PathBuf> {
|
||||||
|
std::env::var_os("MARQDO_BIN").map(PathBuf::from)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fixtures() -> PathBuf {
|
||||||
|
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run(entry: &str, extra: &[&str]) -> Option<(i32, serde_json::Value)> {
|
||||||
|
let marqdo = cli()?;
|
||||||
|
let binary = env!("CARGO_BIN_EXE_marqdo-prove");
|
||||||
|
let work = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||||
|
.join(".tmp")
|
||||||
|
.join("tests/document_contract");
|
||||||
|
std::fs::create_dir_all(&work).expect("work dir");
|
||||||
|
let output = Command::new(binary)
|
||||||
|
.arg("check")
|
||||||
|
.arg(fixtures().join(entry))
|
||||||
|
.args(extra)
|
||||||
|
.arg("--json")
|
||||||
|
.env("MARQDO_BIN", &marqdo)
|
||||||
|
.env(
|
||||||
|
"MARQDO_PROVE_LEAN_ROOT",
|
||||||
|
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("lean"),
|
||||||
|
)
|
||||||
|
.output()
|
||||||
|
.expect("run marqdo-prove");
|
||||||
|
let code = output.status.code().unwrap_or(-1);
|
||||||
|
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||||
|
let parsed: serde_json::Value = serde_json::from_str(stdout.trim()).unwrap_or_else(|error| {
|
||||||
|
panic!(
|
||||||
|
"expected one JSON object on stdout, got `{stdout}` ({error}); stderr: {}",
|
||||||
|
String::from_utf8_lossy(&output.stderr)
|
||||||
|
)
|
||||||
|
});
|
||||||
|
Some((code, parsed))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn codes(report: &serde_json::Value) -> Vec<String> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
if let Some(targets) = report["targets"].as_array() {
|
||||||
|
for target in targets {
|
||||||
|
for diagnostic in target["diagnostics"]
|
||||||
|
.as_array()
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or_default()
|
||||||
|
{
|
||||||
|
if let Some(code) = diagnostic["code"].as_str() {
|
||||||
|
out.push(code.to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for diagnostic in report["diagnostics"]
|
||||||
|
.as_array()
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or_default()
|
||||||
|
{
|
||||||
|
if let Some(code) = diagnostic["code"].as_str() {
|
||||||
|
out.push(code.to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn no_target_document_succeeds_without_targets() {
|
||||||
|
let Some((code, report)) = run("no-target.mq.md", &[]) else {
|
||||||
|
eprintln!("skipping: MARQDO_BIN is not set");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
assert_eq!(code, 0, "{report}");
|
||||||
|
assert_eq!(report["targets"].as_array().map(Vec::len), Some(0));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn two_goals_are_invalid() {
|
||||||
|
let Some((code, report)) = run("two-goals.mq.md", &[]) else {
|
||||||
|
eprintln!("skipping: MARQDO_BIN is not set");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
assert_eq!(code, 1, "{report}");
|
||||||
|
assert!(
|
||||||
|
codes(&report).contains(&"document.goal_count".to_string()),
|
||||||
|
"{report}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn dependency_list_shape_is_rejected() {
|
||||||
|
let Some((code, report)) = run("bad-dependencies.mq.md", &[]) else {
|
||||||
|
eprintln!("skipping: MARQDO_BIN is not set");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
assert_eq!(code, 1, "{report}");
|
||||||
|
assert!(
|
||||||
|
codes(&report).contains(&"document.dependencies_shape".to_string()),
|
||||||
|
"{report}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unsupported_domain_is_unsupported_not_invalid() {
|
||||||
|
let Some((code, report)) = run("unsupported-domain.mq.md", &[]) else {
|
||||||
|
eprintln!("skipping: MARQDO_BIN is not set");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
assert_eq!(code, 1, "{report}");
|
||||||
|
assert_eq!(report["targets"][0]["outcome"], "unsupported");
|
||||||
|
assert!(
|
||||||
|
codes(&report).contains(&"formula.unsupported".to_string()),
|
||||||
|
"{report}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn free_variable_is_invalid() {
|
||||||
|
let Some((code, report)) = run("free-variable.mq.md", &[]) else {
|
||||||
|
eprintln!("skipping: MARQDO_BIN is not set");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
assert_eq!(code, 1, "{report}");
|
||||||
|
assert!(
|
||||||
|
codes(&report).contains(&"formula.free_variable".to_string()),
|
||||||
|
"{report}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn missing_link_is_reported() {
|
||||||
|
let Some((code, report)) = run("missing-link.mq.md", &[]) else {
|
||||||
|
eprintln!("skipping: MARQDO_BIN is not set");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
assert_eq!(code, 1, "{report}");
|
||||||
|
assert!(
|
||||||
|
codes(&report).contains(&"link.missing".to_string()),
|
||||||
|
"{report}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn external_link_is_rejected() {
|
||||||
|
let Some((code, report)) = run("external-link.mq.md", &[]) else {
|
||||||
|
eprintln!("skipping: MARQDO_BIN is not set");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
assert_eq!(code, 1, "{report}");
|
||||||
|
assert!(
|
||||||
|
codes(&report).contains(&"link.invalid".to_string()),
|
||||||
|
"{report}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn dependency_cycle_is_rejected_with_a_chain() {
|
||||||
|
let Some((code, report)) = run("cycle-a.mq.md", &[]) else {
|
||||||
|
eprintln!("skipping: MARQDO_BIN is not set");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
assert_eq!(code, 1, "{report}");
|
||||||
|
assert!(
|
||||||
|
codes(&report).contains(&"link.cycle".to_string()),
|
||||||
|
"{report}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unknown_unit_selection_fails() {
|
||||||
|
let Some((code, report)) = run("no-target.mq.md", &["--unit", "不存在的标题"]) else {
|
||||||
|
eprintln!("skipping: MARQDO_BIN is not set");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
assert_eq!(code, 1, "{report}");
|
||||||
|
assert!(
|
||||||
|
codes(&report).contains(&"document.unit".to_string()),
|
||||||
|
"{report}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn upstream_static_failure_is_a_contract_failure() {
|
||||||
|
let Some(marqdo) = cli() else {
|
||||||
|
eprintln!("skipping: MARQDO_BIN is not set");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let binary = env!("CARGO_BIN_EXE_marqdo-prove");
|
||||||
|
let output = Command::new(binary)
|
||||||
|
.arg("check")
|
||||||
|
.arg(fixtures().join("static-error.mq.md"))
|
||||||
|
.arg("--json")
|
||||||
|
.env("MARQDO_BIN", marqdo)
|
||||||
|
.output()
|
||||||
|
.expect("run marqdo-prove");
|
||||||
|
assert_eq!(
|
||||||
|
output.status.code(),
|
||||||
|
Some(2),
|
||||||
|
"{}",
|
||||||
|
String::from_utf8_lossy(&output.stderr)
|
||||||
|
);
|
||||||
|
let report: serde_json::Value =
|
||||||
|
serde_json::from_str(String::from_utf8_lossy(&output.stdout).trim()).expect("json");
|
||||||
|
assert_eq!(report["status"], "failure");
|
||||||
|
assert_eq!(report["diagnostics"][0]["code"], "upstream.contract");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn root_must_contain_the_entry() {
|
||||||
|
let Some(marqdo) = cli() else {
|
||||||
|
eprintln!("skipping: MARQDO_BIN is not set");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let binary = env!("CARGO_BIN_EXE_marqdo-prove");
|
||||||
|
let outside = Path::new("/tmp");
|
||||||
|
let output = Command::new(binary)
|
||||||
|
.arg("check")
|
||||||
|
.arg(fixtures().join("no-target.mq.md"))
|
||||||
|
.arg("--root")
|
||||||
|
.arg(outside)
|
||||||
|
.arg("--json")
|
||||||
|
.env("MARQDO_BIN", marqdo)
|
||||||
|
.output()
|
||||||
|
.expect("run marqdo-prove");
|
||||||
|
assert_eq!(output.status.code(), Some(2));
|
||||||
|
let report: serde_json::Value =
|
||||||
|
serde_json::from_str(String::from_utf8_lossy(&output.stdout).trim()).expect("json");
|
||||||
|
assert_eq!(report["diagnostics"][0]["code"], "link.outside_root");
|
||||||
|
}
|
||||||
+214
@@ -0,0 +1,214 @@
|
|||||||
|
//! Lean-backed end-to-end acceptance tests.
|
||||||
|
//!
|
||||||
|
//! These tests exercise the real CLI, the pinned Lean + Mathlib backend, the
|
||||||
|
//! independent kernel replay and the certificate path. They are `#[ignore]`d
|
||||||
|
//! because they require the fixed backend and take ~20-30s per target; CI runs
|
||||||
|
//! them explicitly:
|
||||||
|
//!
|
||||||
|
//! ```sh
|
||||||
|
//! MARQDO_BIN=/abs/marqdo cargo test --test e2e -- --ignored --test-threads=1
|
||||||
|
//! ```
|
||||||
|
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::process::Command;
|
||||||
|
|
||||||
|
use serde_json::Value;
|
||||||
|
|
||||||
|
fn marqdo() -> Option<PathBuf> {
|
||||||
|
std::env::var_os("MARQDO_BIN").map(PathBuf::from)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn repo() -> PathBuf {
|
||||||
|
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn work(tag: &str) -> PathBuf {
|
||||||
|
let directory = repo().join(".tmp").join("e2e").join(tag);
|
||||||
|
let _ = std::fs::remove_dir_all(&directory);
|
||||||
|
std::fs::create_dir_all(&directory).expect("work dir");
|
||||||
|
directory
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run(arguments: &[&str]) -> (i32, Value) {
|
||||||
|
let output = Command::new(env!("CARGO_BIN_EXE_marqdo-prove"))
|
||||||
|
.args(arguments)
|
||||||
|
.env("MARQDO_BIN", marqdo().expect("MARQDO_BIN"))
|
||||||
|
.env("MARQDO_PROVE_LEAN_ROOT", repo().join("lean"))
|
||||||
|
.output()
|
||||||
|
.expect("run marqdo-prove");
|
||||||
|
let code = output.status.code().unwrap_or(-1);
|
||||||
|
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||||
|
let report: Value = serde_json::from_str(stdout.trim()).unwrap_or_else(|error| {
|
||||||
|
panic!(
|
||||||
|
"expected one JSON object, got `{stdout}` ({error}); stderr: {}",
|
||||||
|
String::from_utf8_lossy(&output.stderr)
|
||||||
|
)
|
||||||
|
});
|
||||||
|
(code, report)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check(entry: &Path, extra: &[&str]) -> (i32, Value) {
|
||||||
|
let mut arguments = vec!["check", entry.to_str().expect("utf8 path"), "--json"];
|
||||||
|
arguments.extend_from_slice(extra);
|
||||||
|
run(&arguments)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[ignore]
|
||||||
|
fn algebra_fixture_verifies_and_publishes_certificates() {
|
||||||
|
let (code, report) = check(&repo().join("examples/algebra.mq.md"), &[]);
|
||||||
|
assert_eq!(code, 0, "{report}");
|
||||||
|
let targets = report["targets"].as_array().expect("targets");
|
||||||
|
assert_eq!(targets.len(), 2);
|
||||||
|
for target in targets {
|
||||||
|
assert_eq!(target["outcome"], "verified", "{target}");
|
||||||
|
assert_eq!(target["freshness"], "current");
|
||||||
|
assert_eq!(target["scope"], "mathematical");
|
||||||
|
assert!(target["certificate"]["cache_key"].as_str().is_some());
|
||||||
|
let axioms = target["axioms"].as_array().expect("axioms");
|
||||||
|
for axiom in axioms {
|
||||||
|
assert!(
|
||||||
|
["propext", "Classical.choice", "Quot.sound"]
|
||||||
|
.contains(&axiom.as_str().unwrap_or("")),
|
||||||
|
"{axiom}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[ignore]
|
||||||
|
fn vector_composition_uses_both_linked_theorems() {
|
||||||
|
let (code, report) = check(&repo().join("examples/vector.mq.md"), &[]);
|
||||||
|
assert_eq!(code, 0, "{report}");
|
||||||
|
let target = &report["targets"][0];
|
||||||
|
assert_eq!(target["outcome"], "verified", "{target}");
|
||||||
|
let declared = target["declared_dependencies"]
|
||||||
|
.as_array()
|
||||||
|
.expect("declared");
|
||||||
|
let used = target["used_dependencies"].as_array().expect("used");
|
||||||
|
assert_eq!(declared.len(), 2);
|
||||||
|
// Actual proof-term dependencies, not merely declared links.
|
||||||
|
assert_eq!(used.len(), 2, "{target}");
|
||||||
|
for dependency in declared {
|
||||||
|
assert!(
|
||||||
|
used.iter().any(|used| used == &dependency["locator"]),
|
||||||
|
"declared {} was not used: {target}",
|
||||||
|
dependency["locator"]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[ignore]
|
||||||
|
fn program_model_bridge_is_exact_integer_scope() {
|
||||||
|
let (code, report) = check(&repo().join("examples/arithmetic.mq.md"), &[]);
|
||||||
|
assert_eq!(code, 0, "{report}");
|
||||||
|
let target = &report["targets"][0];
|
||||||
|
assert_eq!(target["outcome"], "verified", "{target}");
|
||||||
|
assert_eq!(target["scope"], "program_model");
|
||||||
|
let declared = target["declared_dependencies"]
|
||||||
|
.as_array()
|
||||||
|
.expect("declared");
|
||||||
|
assert!(declared
|
||||||
|
.iter()
|
||||||
|
.any(|dependency| dependency["kind"] == "model"));
|
||||||
|
assert!(declared
|
||||||
|
.iter()
|
||||||
|
.any(|dependency| dependency["kind"] == "theorem"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[ignore]
|
||||||
|
fn false_propositions_are_refuted_by_proven_negations() {
|
||||||
|
let (code, report) = check(&repo().join("tests/fixtures/false.mq.md"), &[]);
|
||||||
|
assert_eq!(code, 1, "{report}");
|
||||||
|
let targets = report["targets"].as_array().expect("targets");
|
||||||
|
assert_eq!(targets.len(), 2);
|
||||||
|
for target in targets {
|
||||||
|
assert_eq!(target["outcome"], "refuted", "{target}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[ignore]
|
||||||
|
fn exported_bundle_replays_without_search() {
|
||||||
|
let directory = work("replay");
|
||||||
|
let bundle = directory.join("vector-proof");
|
||||||
|
let (code, report) = check(
|
||||||
|
&repo().join("examples/vector.mq.md"),
|
||||||
|
&["--out", bundle.to_str().expect("utf8")],
|
||||||
|
);
|
||||||
|
assert_eq!(code, 0, "{report}");
|
||||||
|
assert!(bundle.join("manifest.json").is_file());
|
||||||
|
assert!(bundle.join("proof.ndjson").is_file());
|
||||||
|
let (code, replayed) = run(&[
|
||||||
|
"replay",
|
||||||
|
repo().join("examples/vector.mq.md").to_str().expect("utf8"),
|
||||||
|
bundle.to_str().expect("utf8"),
|
||||||
|
"--json",
|
||||||
|
]);
|
||||||
|
assert_eq!(code, 0, "{replayed}");
|
||||||
|
assert_eq!(replayed["targets"][0]["outcome"], "verified", "{replayed}");
|
||||||
|
assert_eq!(replayed["targets"][0]["freshness"], "current");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[ignore]
|
||||||
|
fn repeated_check_reuses_and_replays_the_certificate() {
|
||||||
|
let entry = repo().join("examples/algebra.mq.md");
|
||||||
|
let (_, first) = check(&entry, &[]);
|
||||||
|
let key = first["targets"][0]["certificate"]["cache_key"]
|
||||||
|
.as_str()
|
||||||
|
.expect("cache key")
|
||||||
|
.to_string();
|
||||||
|
let (code, second) = check(&entry, &[]);
|
||||||
|
assert_eq!(code, 0, "{second}");
|
||||||
|
assert_eq!(second["targets"][0]["outcome"], "verified");
|
||||||
|
assert_eq!(second["targets"][0]["freshness"], "current");
|
||||||
|
assert_eq!(
|
||||||
|
second["targets"][0]["certificate"]["cache_key"],
|
||||||
|
Value::String(key),
|
||||||
|
"a cache hit must keep the same content address"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[ignore]
|
||||||
|
fn tampered_payload_is_rejected() {
|
||||||
|
let directory = work("tamper");
|
||||||
|
let bundle = directory.join("algebra-proof");
|
||||||
|
let (code, report) = check(
|
||||||
|
&repo().join("examples/algebra.mq.md"),
|
||||||
|
&[
|
||||||
|
"--unit",
|
||||||
|
"整数平方非负性",
|
||||||
|
"--out",
|
||||||
|
bundle.to_str().expect("utf8"),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
assert_eq!(code, 0, "{report}");
|
||||||
|
let payload = bundle.join("proof.ndjson");
|
||||||
|
let mut bytes = std::fs::read(&payload).expect("payload");
|
||||||
|
let last = bytes.len() - 2;
|
||||||
|
bytes[last] ^= 0x01;
|
||||||
|
std::fs::write(&payload, &bytes).expect("tamper");
|
||||||
|
let output = Command::new(env!("CARGO_BIN_EXE_marqdo-prove"))
|
||||||
|
.args([
|
||||||
|
"replay",
|
||||||
|
repo()
|
||||||
|
.join("examples/algebra.mq.md")
|
||||||
|
.to_str()
|
||||||
|
.expect("utf8"),
|
||||||
|
bundle.to_str().expect("utf8"),
|
||||||
|
"--json",
|
||||||
|
])
|
||||||
|
.env("MARQDO_BIN", marqdo().expect("MARQDO_BIN"))
|
||||||
|
.env("MARQDO_PROVE_LEAN_ROOT", repo().join("lean"))
|
||||||
|
.output()
|
||||||
|
.expect("run replay");
|
||||||
|
assert_ne!(output.status.code(), Some(0));
|
||||||
|
let report: Value =
|
||||||
|
serde_json::from_str(String::from_utf8_lossy(&output.stdout).trim()).expect("json");
|
||||||
|
assert_eq!(report["status"], "failure", "{report}");
|
||||||
|
}
|
||||||
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
+70
@@ -0,0 +1,70 @@
|
|||||||
|
{
|
||||||
|
"schema": "marqdo.proof",
|
||||||
|
"schema_version": 1,
|
||||||
|
"tool": {
|
||||||
|
"name": "marqdo-prove",
|
||||||
|
"version": "0.1.0"
|
||||||
|
},
|
||||||
|
"target": {
|
||||||
|
"unit_id": "root:default::false.mq.md#反例/平方总是负",
|
||||||
|
"unit_path": [
|
||||||
|
"反例",
|
||||||
|
"平方总是负"
|
||||||
|
],
|
||||||
|
"locator": "false.mq.md",
|
||||||
|
"scope": "mathematical",
|
||||||
|
"outcome": "refuted",
|
||||||
|
"statement_literal": "\\forall x\\in\\mathbb{Z},\\quad x^2<0\n",
|
||||||
|
"statement_normalized": "∀ x : ℤ, x^2 < 0",
|
||||||
|
"statement_lean": "∀ mqx0 : Int, ((mqx0 ^ (2 : Nat)) < (0 : Int))",
|
||||||
|
"goal_span": {
|
||||||
|
"start": 41,
|
||||||
|
"end": 81
|
||||||
|
},
|
||||||
|
"goal_payload_span": {
|
||||||
|
"start": 44,
|
||||||
|
"end": 79
|
||||||
|
},
|
||||||
|
"goal_digest": "07b45c4054327cb560709dd7142d81bc2b39428b9dab088d035f2e15c5d3040d",
|
||||||
|
"premises": [],
|
||||||
|
"theorem_name": "marqdoTarget_a9f1eee0314c784457f9",
|
||||||
|
"expected_name": "marqdoExpected_a9f1eee0314c784457f9",
|
||||||
|
"model_definitions": []
|
||||||
|
},
|
||||||
|
"sources": [
|
||||||
|
{
|
||||||
|
"locator": "false.mq.md",
|
||||||
|
"module_id": "root:default::false.mq.md",
|
||||||
|
"source_digest": "88e2eef4fe81a1287b5596daf7aba0b5e8725ef668012ccc193702685f610543",
|
||||||
|
"analysis_digest": "e987323e501121c1a21709e50720746bd891c989a0b25f79ca37c81e3196e87b"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"environment": {
|
||||||
|
"lean_toolchain": "leanprover/lean4:v4.36.0",
|
||||||
|
"lean_version": "86_64",
|
||||||
|
"mathlib_rev": "fc4f59e577feb1a4956671bc04ac18aaaf8cd842",
|
||||||
|
"lake_manifest_digest": "bb82472009ad8aba44b75c1a1095dfe290dd87319421d55039e02fe57f2e0022",
|
||||||
|
"replay_verifier_digest": "02cbc2c8b00dbdac2c5bcf359b25a62f896372b9964f7578caca4d4346d544c1",
|
||||||
|
"con_leche_version": "con-leche-a6380d68b4fb3641",
|
||||||
|
"formula_compiler": "marqdo-prove-0.1.0",
|
||||||
|
"semantic_mapping": "marqdo-int-exact-v1",
|
||||||
|
"environment_id": "9622d44bfc5540616117b8e4b60b3e06a84122535d4495925739a08acc14877a"
|
||||||
|
},
|
||||||
|
"declared_dependencies": [],
|
||||||
|
"used_dependencies": [],
|
||||||
|
"transitive_dependencies": [
|
||||||
|
"false.mq.md#反例/平方总是负"
|
||||||
|
],
|
||||||
|
"axioms": [
|
||||||
|
"propext"
|
||||||
|
],
|
||||||
|
"proof": {
|
||||||
|
"file": "proof.ndjson",
|
||||||
|
"bytes": 1493702,
|
||||||
|
"sha256": "21bfd1a3d53438e8521379ddc1fb806e5ba5121f9d6bc8485dc0bb05a28942bc",
|
||||||
|
"export_format": "lean4export-3.1.0",
|
||||||
|
"target_decl": "marqdoTarget_a9f1eee0314c784457f9",
|
||||||
|
"expected_decl": "marqdoExpected_a9f1eee0314c784457f9"
|
||||||
|
},
|
||||||
|
"cache_key": "364469fffce1d2c9810883f6df462a3fc6655ee2de4c65684aa6d77ae8e6efd0"
|
||||||
|
}
|
||||||
+28062
File diff suppressed because it is too large.
Load diff
+68
@@ -0,0 +1,68 @@
|
|||||||
|
{
|
||||||
|
"schema": "marqdo.proof",
|
||||||
|
"schema_version": 1,
|
||||||
|
"tool": {
|
||||||
|
"name": "marqdo-prove",
|
||||||
|
"version": "0.1.0"
|
||||||
|
},
|
||||||
|
"target": {
|
||||||
|
"unit_id": "root:default::false.mq.md#反例/封闭错误等式",
|
||||||
|
"unit_path": [
|
||||||
|
"反例",
|
||||||
|
"封闭错误等式"
|
||||||
|
],
|
||||||
|
"locator": "false.mq.md",
|
||||||
|
"scope": "mathematical",
|
||||||
|
"outcome": "refuted",
|
||||||
|
"statement_literal": "3+4=8\n",
|
||||||
|
"statement_normalized": "3 + 4 = 8",
|
||||||
|
"statement_lean": "(((3 : Int) + (4 : Int)) = (8 : Int))",
|
||||||
|
"goal_span": {
|
||||||
|
"start": 135,
|
||||||
|
"end": 146
|
||||||
|
},
|
||||||
|
"goal_payload_span": {
|
||||||
|
"start": 138,
|
||||||
|
"end": 144
|
||||||
|
},
|
||||||
|
"goal_digest": "1511e16776c3dedbc83717b7809f26ef859cb24a0980c34f5186efab40b751f3",
|
||||||
|
"premises": [],
|
||||||
|
"theorem_name": "marqdoTarget_c1a66f9163cb21940c3e",
|
||||||
|
"expected_name": "marqdoExpected_c1a66f9163cb21940c3e",
|
||||||
|
"model_definitions": []
|
||||||
|
},
|
||||||
|
"sources": [
|
||||||
|
{
|
||||||
|
"locator": "false.mq.md",
|
||||||
|
"module_id": "root:default::false.mq.md",
|
||||||
|
"source_digest": "88e2eef4fe81a1287b5596daf7aba0b5e8725ef668012ccc193702685f610543",
|
||||||
|
"analysis_digest": "e987323e501121c1a21709e50720746bd891c989a0b25f79ca37c81e3196e87b"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"environment": {
|
||||||
|
"lean_toolchain": "leanprover/lean4:v4.36.0",
|
||||||
|
"lean_version": "86_64",
|
||||||
|
"mathlib_rev": "fc4f59e577feb1a4956671bc04ac18aaaf8cd842",
|
||||||
|
"lake_manifest_digest": "bb82472009ad8aba44b75c1a1095dfe290dd87319421d55039e02fe57f2e0022",
|
||||||
|
"replay_verifier_digest": "02cbc2c8b00dbdac2c5bcf359b25a62f896372b9964f7578caca4d4346d544c1",
|
||||||
|
"con_leche_version": "con-leche-a6380d68b4fb3641",
|
||||||
|
"formula_compiler": "marqdo-prove-0.1.0",
|
||||||
|
"semantic_mapping": "marqdo-int-exact-v1",
|
||||||
|
"environment_id": "9622d44bfc5540616117b8e4b60b3e06a84122535d4495925739a08acc14877a"
|
||||||
|
},
|
||||||
|
"declared_dependencies": [],
|
||||||
|
"used_dependencies": [],
|
||||||
|
"transitive_dependencies": [
|
||||||
|
"false.mq.md#反例/封闭错误等式"
|
||||||
|
],
|
||||||
|
"axioms": [],
|
||||||
|
"proof": {
|
||||||
|
"file": "proof.ndjson",
|
||||||
|
"bytes": 174123,
|
||||||
|
"sha256": "b802f214ce34fabcf6e88750c87965d0e7a53e809098cb51006e2d483d3f4501",
|
||||||
|
"export_format": "lean4export-3.1.0",
|
||||||
|
"target_decl": "marqdoTarget_c1a66f9163cb21940c3e",
|
||||||
|
"expected_decl": "marqdoExpected_c1a66f9163cb21940c3e"
|
||||||
|
},
|
||||||
|
"cache_key": "c5f87c70f553453cf28e79fe129cf80e94a38912d1bc9e466e916d43e876b4d3"
|
||||||
|
}
|
||||||
+3166
File diff suppressed because it is too large.
Load diff
+11
@@ -0,0 +1,11 @@
|
|||||||
|
# 依赖形状错误
|
||||||
|
|
||||||
|
## @knowledge 目标
|
||||||
|
|
||||||
|
$$
|
||||||
|
1 = 1
|
||||||
|
$$
|
||||||
|
|
||||||
|
### 证明依赖
|
||||||
|
|
||||||
|
- [目标](other.mq.md#目标) 多余文字
|
||||||
Vendored
+11
@@ -0,0 +1,11 @@
|
|||||||
|
# 环形 A
|
||||||
|
|
||||||
|
## @knowledge A
|
||||||
|
|
||||||
|
$$
|
||||||
|
1 = 1
|
||||||
|
$$
|
||||||
|
|
||||||
|
### 证明依赖
|
||||||
|
|
||||||
|
- [B](cycle-b.mq.md#B)
|
||||||
Vendored
+11
@@ -0,0 +1,11 @@
|
|||||||
|
# 环形 B
|
||||||
|
|
||||||
|
## @knowledge B
|
||||||
|
|
||||||
|
$$
|
||||||
|
1 = 1
|
||||||
|
$$
|
||||||
|
|
||||||
|
### 证明依赖
|
||||||
|
|
||||||
|
- [A](cycle-a.mq.md#A)
|
||||||
Vendored
+11
@@ -0,0 +1,11 @@
|
|||||||
|
# 外部链接
|
||||||
|
|
||||||
|
## @knowledge 目标
|
||||||
|
|
||||||
|
$$
|
||||||
|
1 = 1
|
||||||
|
$$
|
||||||
|
|
||||||
|
### 证明依赖
|
||||||
|
|
||||||
|
- [外部知识](https://example.com/theory)
|
||||||
Vendored
+17
@@ -0,0 +1,17 @@
|
|||||||
|
# 反例
|
||||||
|
|
||||||
|
## @knowledge 平方总是负
|
||||||
|
|
||||||
|
$$
|
||||||
|
\forall x\in\mathbb{Z},\quad x^2<0
|
||||||
|
$$
|
||||||
|
|
||||||
|
### 证明依赖
|
||||||
|
|
||||||
|
## @knowledge 封闭错误等式
|
||||||
|
|
||||||
|
$$
|
||||||
|
3+4=8
|
||||||
|
$$
|
||||||
|
|
||||||
|
### 证明依赖
|
||||||
Vendored
+9
@@ -0,0 +1,9 @@
|
|||||||
|
# 自由变量
|
||||||
|
|
||||||
|
## @knowledge 没有定义域
|
||||||
|
|
||||||
|
$$
|
||||||
|
x^2\geq0
|
||||||
|
$$
|
||||||
|
|
||||||
|
### 证明依赖
|
||||||
Vendored
+11
@@ -0,0 +1,11 @@
|
|||||||
|
# 断链
|
||||||
|
|
||||||
|
## @knowledge 目标
|
||||||
|
|
||||||
|
$$
|
||||||
|
1 = 1
|
||||||
|
$$
|
||||||
|
|
||||||
|
### 证明依赖
|
||||||
|
|
||||||
|
- [缺失定理](does-not-exist.mq.md#定理)
|
||||||
Vendored
+9
@@ -0,0 +1,9 @@
|
|||||||
|
# 普通知识
|
||||||
|
|
||||||
|
## @knowledge 仅解释
|
||||||
|
|
||||||
|
这里有一个公式,但没有 `证明依赖` 标题,因此不是证明目标。
|
||||||
|
|
||||||
|
$$
|
||||||
|
\forall x\in\mathbb{Z},\quad x^2\geq0
|
||||||
|
$$
|
||||||
Vendored
+5
@@ -0,0 +1,5 @@
|
|||||||
|
# bad
|
||||||
|
|
||||||
|
## @exec broken
|
||||||
|
|
||||||
|
`return +`
|
||||||
Vendored
+13
@@ -0,0 +1,13 @@
|
|||||||
|
# 双目标
|
||||||
|
|
||||||
|
## @knowledge 两个公式
|
||||||
|
|
||||||
|
$$
|
||||||
|
x = 1
|
||||||
|
$$
|
||||||
|
|
||||||
|
$$
|
||||||
|
y = 2
|
||||||
|
$$
|
||||||
|
|
||||||
|
### 证明依赖
|
||||||
+9
@@ -0,0 +1,9 @@
|
|||||||
|
# 不支持的域
|
||||||
|
|
||||||
|
## @knowledge 实数平方
|
||||||
|
|
||||||
|
$$
|
||||||
|
\forall x\in\mathbb{R},\quad x^2\geq0
|
||||||
|
$$
|
||||||
|
|
||||||
|
### 证明依赖
|
||||||
+69
-25
@@ -39,17 +39,15 @@ fn fixture_vector_proposition() {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn fixture_nonnegative_addition_preserves_premises() {
|
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");
|
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!(goal.vars, vec!["a", "b"]);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
lean(&goal),
|
lean(&goal),
|
||||||
"∀ mqx0 mqx1 : Int, (((mqx0 ≥ (0 : Int)) ∧ (mqx1 ≥ (0 : Int))) → \
|
"∀ mqx0 mqx1 : Int, (((mqx0 ≥ (0 : Int)) ∧ (mqx1 ≥ (0 : Int))) → \
|
||||||
((mqx0 + mqx1) ≥ (0 : Int)))"
|
((mqx0 + mqx1) ≥ (0 : Int)))"
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(goal.normal(), "∀ a b : ℤ, (a ≥ 0 ∧ b ≥ 0) → a + b ≥ 0");
|
||||||
goal.normal(),
|
|
||||||
"∀ a b : ℤ, (a ≥ 0 ∧ b ≥ 0) → a + b ≥ 0"
|
|
||||||
);
|
|
||||||
assert_eq!(goal.premises(), vec!["a ≥ 0 ∧ b ≥ 0"]);
|
assert_eq!(goal.premises(), vec!["a ≥ 0 ∧ b ≥ 0"]);
|
||||||
assert_eq!(goal.evaluate(&[int(-2), int(1)]), Some(true));
|
assert_eq!(goal.evaluate(&[int(-2), int(1)]), Some(true));
|
||||||
}
|
}
|
||||||
@@ -98,14 +96,23 @@ fn exponent_rules() {
|
|||||||
lean(&goal),
|
lean(&goal),
|
||||||
"∀ mqx0 : Int, ((mqx0 ^ (12 : Nat)) ≥ (0 : Int))"
|
"∀ mqx0 : Int, ((mqx0 ^ (12 : Nat)) ≥ (0 : Int))"
|
||||||
);
|
);
|
||||||
let error = formula::parse("\\forall x\\in\\mathbb{Z},\\quad x^12\\geq0", Span::new(0, 1))
|
let error = formula::parse(
|
||||||
.unwrap_err();
|
"\\forall x\\in\\mathbb{Z},\\quad x^12\\geq0",
|
||||||
|
Span::new(0, 1),
|
||||||
|
)
|
||||||
|
.unwrap_err();
|
||||||
assert_eq!(error.code(), codes::FORMULA_SYNTAX, "{error:?}");
|
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))
|
let error = formula::parse(
|
||||||
.unwrap_err();
|
"\\forall x\\in\\mathbb{Z},\\quad x^{17}\\geq0",
|
||||||
|
Span::new(0, 1),
|
||||||
|
)
|
||||||
|
.unwrap_err();
|
||||||
assert_eq!(error.code(), codes::FORMULA_UNSUPPORTED, "{error:?}");
|
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))
|
let error = formula::parse(
|
||||||
.unwrap_err();
|
"\\forall x\\in\\mathbb{Z},\\quad x^{999999999}\\geq0",
|
||||||
|
Span::new(0, 1),
|
||||||
|
)
|
||||||
|
.unwrap_err();
|
||||||
assert_eq!(error.code(), codes::FORMULA_UNSUPPORTED, "{error:?}");
|
assert_eq!(error.code(), codes::FORMULA_UNSUPPORTED, "{error:?}");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -113,26 +120,53 @@ fn exponent_rules() {
|
|||||||
fn unsupported_and_invalid_inputs_are_rejected() {
|
fn unsupported_and_invalid_inputs_are_rejected() {
|
||||||
let cases: &[(&str, &str)] = &[
|
let cases: &[(&str, &str)] = &[
|
||||||
("x^2\\geq0", codes::FORMULA_FREE_VARIABLE),
|
("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{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}, 2x\\geq0", codes::FORMULA_SYNTAX),
|
||||||
("\\forall x\\in\\mathbb{Z}, 0<x<1", codes::FORMULA_SYNTAX),
|
("\\forall x\\in\\mathbb{Z}, 0<x<1", codes::FORMULA_SYNTAX),
|
||||||
("\\forall x\\in\\mathbb{Z}, x^2\\geq0\\ \\forall y, y\\geq0", codes::FORMULA_UNSUPPORTED),
|
(
|
||||||
("\\forall x\\in\\mathbb{Z}, \\frac{1}{2}\\geq0", codes::FORMULA_UNSUPPORTED),
|
"\\forall x\\in\\mathbb{Z}, x^2\\geq0\\ \\forall y, y\\geq0",
|
||||||
("\\forall x\\in\\mathbb{Z}, \\exists y, y\\geq0", codes::FORMULA_UNSUPPORTED),
|
codes::FORMULA_UNSUPPORTED,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"\\forall x\\in\\mathbb{Z}, \\frac{1}{2}\\geq0",
|
||||||
|
codes::FORMULA_UNSUPPORTED,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"\\forall x\\in\\mathbb{Z}, \\exists y, y\\geq0",
|
||||||
|
codes::FORMULA_UNSUPPORTED,
|
||||||
|
),
|
||||||
("\\forall x\\in\\mathbb{Z}, \\neg x", codes::FORMULA_SYNTAX),
|
("\\forall x\\in\\mathbb{Z}, \\neg x", codes::FORMULA_SYNTAX),
|
||||||
("\\forall x\\in\\mathbb{Z}, x^2", codes::FORMULA_SYNTAX),
|
("\\forall x\\in\\mathbb{Z}, x^2", codes::FORMULA_SYNTAX),
|
||||||
("\\forall x\\in\\mathbb{Z} x^2\\geq0", codes::FORMULA_SYNTAX),
|
("\\forall x\\in\\mathbb{Z} x^2\\geq0", codes::FORMULA_SYNTAX),
|
||||||
("\\forall x,x\\in\\mathbb{Z}, x\\geq0", codes::FORMULA_SYNTAX),
|
(
|
||||||
|
"\\forall x,x\\in\\mathbb{Z}, x\\geq0",
|
||||||
|
codes::FORMULA_SYNTAX,
|
||||||
|
),
|
||||||
("\\forall x\\in\\mathbb{Z},", codes::FORMULA_SYNTAX),
|
("\\forall x\\in\\mathbb{Z},", codes::FORMULA_SYNTAX),
|
||||||
("", codes::FORMULA_SYNTAX),
|
("", codes::FORMULA_SYNTAX),
|
||||||
(" ", codes::FORMULA_SYNTAX),
|
(" ", codes::FORMULA_SYNTAX),
|
||||||
("\\forall x\\in\\mathbb{Z}, (x\\geq0", codes::FORMULA_SYNTAX),
|
("\\forall x\\in\\mathbb{Z}, (x\\geq0", codes::FORMULA_SYNTAX),
|
||||||
("\\forall x\\in\\mathbb{Z}, x\\geq0)", codes::FORMULA_SYNTAX),
|
("\\forall x\\in\\mathbb{Z}, x\\geq0)", codes::FORMULA_SYNTAX),
|
||||||
("\\forall x\\in\\mathbb{Z}, x\\geq0 y\\geq0", codes::FORMULA_SYNTAX),
|
(
|
||||||
("\\forall x\\in\\mathbb{Z}, x\\neq y", codes::FORMULA_FREE_VARIABLE),
|
"\\forall x\\in\\mathbb{Z}, x\\geq0 y\\geq0",
|
||||||
|
codes::FORMULA_SYNTAX,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"\\forall x\\in\\mathbb{Z}, x\\neq y",
|
||||||
|
codes::FORMULA_FREE_VARIABLE,
|
||||||
|
),
|
||||||
("\\frac{1}{2}\\geq0", codes::FORMULA_UNSUPPORTED),
|
("\\frac{1}{2}\\geq0", codes::FORMULA_UNSUPPORTED),
|
||||||
("\\forall x\\in\\mathbb{Z}, \\operatorname{}(x)\\geq0", codes::FORMULA_SYNTAX),
|
(
|
||||||
|
"\\forall x\\in\\mathbb{Z}, \\operatorname{}(x)\\geq0",
|
||||||
|
codes::FORMULA_SYNTAX,
|
||||||
|
),
|
||||||
];
|
];
|
||||||
for (literal, expected) in cases {
|
for (literal, expected) in cases {
|
||||||
let error = formula::parse(literal, Span::new(0, literal.len())).unwrap_err();
|
let error = formula::parse(literal, Span::new(0, literal.len())).unwrap_err();
|
||||||
@@ -192,12 +226,12 @@ fn evaluate_is_exact_arbitrary_precision() {
|
|||||||
assert_eq!(goal.evaluate(&[int(-123456789)]), Some(true));
|
assert_eq!(goal.evaluate(&[int(-123456789)]), Some(true));
|
||||||
let goal = parse("\\forall x\\in\\mathbb{Z},\\quad x^2<0");
|
let goal = parse("\\forall x\\in\\mathbb{Z},\\quad x^2<0");
|
||||||
assert_eq!(goal.evaluate(&[int(0)]), Some(false));
|
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!(
|
assert_eq!(
|
||||||
goal.evaluate(&[int(2), int(3)]),
|
goal.evaluate(&["9".repeat(200).parse().unwrap()]),
|
||||||
Some(true)
|
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;
|
// If the antecedent fails, the conditional proposition is vacuously true;
|
||||||
// this is exactly why reports preserve and display the whole premise.
|
// this is exactly why reports preserve and display the whole premise.
|
||||||
assert_eq!(goal.evaluate(&[int(0), int(3)]), Some(true));
|
assert_eq!(goal.evaluate(&[int(0), int(3)]), Some(true));
|
||||||
@@ -224,7 +258,17 @@ fn typed_ast_is_public_and_structural() {
|
|||||||
fn closed_propositions_are_supported() {
|
fn closed_propositions_are_supported() {
|
||||||
let goal = parse("(2+3)\\cdot4=20");
|
let goal = parse("(2+3)\\cdot4=20");
|
||||||
assert!(goal.vars.is_empty());
|
assert!(goal.vars.is_empty());
|
||||||
assert_eq!(lean(&goal), "((((2 : Int) + (3 : Int)) * (4 : Int)) = (20 : Int))");
|
assert_eq!(
|
||||||
|
lean(&goal),
|
||||||
|
"((((2 : Int) + (3 : Int)) * (4 : Int)) = (20 : Int))"
|
||||||
|
);
|
||||||
assert_eq!(goal.evaluate(&[]), Some(true));
|
assert_eq!(goal.evaluate(&[]), Some(true));
|
||||||
assert_eq!(goal.normal(), "(2 + 3) · 4 = 20");
|
assert_eq!(goal.normal(), "(2 + 3) · 4 = 20");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unsupported_domain_variant_reports_unsupported() {
|
||||||
|
let literal = "\\forall x\\in\\mathbb{R},\\quad x^2\\geq0\n";
|
||||||
|
let error = formula::parse(literal, Span::new(0, 1)).unwrap_err();
|
||||||
|
assert_eq!(error.code(), codes::FORMULA_UNSUPPORTED, "{error:?}");
|
||||||
|
}
|
||||||
Reference in new issue
Block a user