lemmascript 0.6.9 → 0.6.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -28
- package/package.json +1 -1
- package/tools/dist/dafny-commands.js +45 -9
- package/tools/dist/dafny-emit.js +146 -19
- package/tools/dist/dafny-proof-additions.js +197 -0
- package/tools/dist/extract.js +33 -3
- package/tools/dist/ir.js +1 -0
- package/tools/dist/lean-emit.js +15 -7
- package/tools/dist/peephole.js +6 -3
- package/tools/dist/resolve.js +86 -17
- package/tools/dist/transform.js +138 -8
- package/tools/dist/types.js +2 -2
package/README.md
CHANGED
|
@@ -12,34 +12,7 @@ See our [blog post](https://midspiral.com/blog/lemmascript-a-verification-toolch
|
|
|
12
12
|
|
|
13
13
|
## Examples and Case Studies
|
|
14
14
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
See the internal [examples](examples).
|
|
18
|
-
|
|
19
|
-
See the external [case studies](https://github.com/search?q=topic%3Alemmascript+topic%3Acase-study&type=repositories):
|
|
20
|
-
- **[collab-todo-lemmascript](https://github.com/midspiral/collab-todo-lemmascript/)** — collaborative task management web app (React + Supabase) with a verified domain model. Single `domain.ts` imported directly by the UI, hooks, and edge functions — no adapter layer. 123 Dafny lemmas (120 in a separate `domain.proofs.dfy`): 16-conjunct invariant preserved across 25 single-project + 3 cross-project actions, NoOp completeness/soundness, initialization. Dafny only.
|
|
21
|
-
- **[colorwheel-lemmascript](https://github.com/midspiral/colorwheel-lemmascript/)** — verified color palette generator with mood + harmony constraints. 31 Lean proofs + 18 behavioral properties, 115 Dafny lemmas (invariant preservation, commutativity, NoOp completeness).
|
|
22
|
-
- **[clear-split-lemmascript](https://github.com/midspiral/clear-split-lemmascript/)** — greenfield verified expense splitting web app. Conservation theorem, invariant preservation, delta laws — all proven in both Lean (no sorry) and Dafny (56 lemmas).
|
|
23
|
-
- **[eventab-lemmascript](https://github.com/midspiral/eventab-lemmascript/)** — greenfield verified group bill-splitter, shipped as a single self-contained client-side page. Largest-remainder allocation in integer cents proves the money never leaks: per-person shares sum exactly to the tab, non-claimers pay nothing, and the settlement nets to zero even when payments are rounded to the dollar (the payer absorbs the difference). Dafny only.
|
|
24
|
-
- **[github-star-checker-lemmascript](https://github.com/midspiral/github-star-checker-lemmascript/)** — small verified CLI that tracks GitHub star counts across repos and reports per-run deltas. Verifies: per-row diff correctness and `totalDiff == sumDiffs(rows)` (via an inductive `SumDiffs_append` lemma); three sign-classified extractors (gainers / losers / unchanged) with soundness, completeness, **ordered completeness** (gainers appear in the notification in the same order they were listed on the command line), and count/sum equalities against prefix-indexed `upTo` helpers; conservation theorem `decompose(r)` — the three splits partition every row exactly once, and `sumDiffs(increases) + sumDiffs(decreases) == totalDiff`. 33 Dafny VCs, 0 errors; proof additions include a head/tail bridge (`sumDiffs` ↔ `sumDiffsUpTo`) and two partition-on-n inductions. Dafny only.
|
|
25
|
-
- **[equality-game-lemmascript](https://github.com/midspiral/equality-game-lemmascript/)** — greenfield verified arithmetic equality card game (React + Tailwind). Sound + complete decision procedure for "can these two card lists be combined into equal expressions": `canEqualize(L, R) ⟺ ∃ eL, eR. eval(eL) == eval(eR) ∧ multiset(leaves(eL)) == multiset(L) ∧ same for R`. Algorithm is subset-DP over a bitmask `m ∈ [1, 2^n − 1)`; the proof composes a `PopCount` upper/lower bound chain (with stdlib `LemmaDivDenominator` / `LemmaFundamentalDivModConverse`), a `splitLeft`/`splitRight` ↔ imperative-loop connection, a `WitnessCombine` lemma threading existential `Expr` witnesses through the cross-product loops, and a `ChooseMask` combinatorial constructor that, given any sub-multiset of `cards`, produces the realizing mask. Capped by `CompletenessFromMaskCoverage`. 753 verification conditions, 0 errors, 0 `assume`s, 0 axioms under `--isolate-assertions --verification-time-limit 180`. Dafny only.
|
|
26
|
-
- **[talktimer-lemmascript](https://github.com/midspiral/talktimer-lemmascript/)** — verified talk timer React app, ported from a Dafny-only [`talktimer-lemmafit`](https://github.com/midspiral/talktimer-lemmafit/) twin. 17-variant `Action` state machine + verified `History` (undo/redo/preview/commitFrom) all in one `domain.ts` — the original Dafny's `Domain refines Kernel` abstract-module pattern inlined since LS has no abstract modules. 108 VCs in `domain.dfy` (invariant preservation) + 123 in `domain.proofs.dfy` (behavioral lemmas + Kernel round-trip). Dafny only.
|
|
27
|
-
- **[node-casbin-lemmascript](https://github.com/midspiral/node-casbin-lemmascript/blob/lemmascript/README_LemmaScript.md)** — brownfield verification of [node-casbin](https://github.com/casbin/node-casbin). 5 functions verified, 217 existing tests pass. End-to-end correctness and order independence for all 4 effect modes in both Lean and Dafny (39 lemmas).
|
|
28
|
-
- **[hono-lemmascript](https://github.com/midspiral/hono-lemmascript/blob/lemmascript/README_LemmaScript.md)** — brownfield verification of [hono](https://github.com/honojs/hono)'s security middleware. Four CVEs covered: IP restriction bypass ([CVE-2026-39409](https://github.com/honojs/hono/security/advisories/GHSA-3mpf-rcc7-5347)) and cookie name bypass ([CVE-2026-39410](https://github.com/honojs/hono/security/advisories/GHSA-r5rp-j6wh-rvv4)) — 51 Dafny lemmas, [cookie verification **in-place**](https://github.com/midspiral/hono-lemmascript/blob/lemmascript/src/utils/cookie.ts#L79); plus `serveStatic`'s URL-encoded directory traversal ([CVE-2024-32869](https://github.com/honojs/hono/security/advisories/GHSA-q5w7-8mq6-2hxq)) + repeated-slash bypass ([CVE-2026-39407](https://github.com/honojs/hono/security/advisories/GHSA-jw53-c2g8-vmwm)), proved as a *composition* — `decode(rawPath)` before `check(decoded)`, so a buggy implementation that reordered the steps would fail the proof. First use of `//@ assume` + `//@ havoc`-on-assign. Dafny only.
|
|
29
|
-
- **[hono-rate-limiter-with-lemmascript](https://github.com/midspiral/hono-rate-limiter-with-lemmascript)** — a greenfield verified feature shipped through a brownfield host's *middleware seam*: a standalone [Hono](https://hono.dev) sliding-window rate-limit middleware whose admission decision is a machine-checked theorem. `SlidingWindowBound` proves no half-open window `(s, s+W]` ever admits more than `limit`, so the boundary-straddling 2× burst that every fixed-window limiter leaks is *impossible* (the naive cousin is refuted in the same file, `FixedWindowLeaks`); the proof is wired into a live Hono server, with the clock's monotonicity and the per-key store's atomicity as the named trust boundary. 23 Dafny VCs, 0 errors. Dafny only.
|
|
30
|
-
- **[charmchat](https://github.com/CHARM-BDF/charmchat/blob/lemma/README_LemmaScript.md)** — brownfield verification of an AI agent orchestration backend. `isEmptyResult` (string emptiness predicate, 8 postconditions, <1s) and `topologicalSort` (Kahn's algorithm — memory safety, output bounds, completeness via acyclicity ranking witness, termination). Full completeness proof: 23 helper lemmas, 14 opaque ghost predicates, 115 loop invariants; 736 VCs verified under `--isolate-assertions --verification-time-limit 600`. Key technique: snapshot-based inner invariants (`ghost var originalRemDeps := remDeps`) replace the mid-iteration SEEN/UNSEEN split so preservation is frame reasoning against a ghost-constant rather than set-subtraction against mutating state. Dafny only.
|
|
31
|
-
- **[xyflow-lemmascript](https://github.com/midspiral/xyflow-lemmascript/blob/lemmascript/README_LemmaScript.md)** — brownfield verification of [xyflow](https://github.com/xyflow/xyflow)'s core edge and geometry utilities. 9 functions verified: `addEdge` (dedup — never loses edges, adds at most one), `reconnectEdge` (semantic: under a unique-id precondition, the result is in-place — `|result| ≤ |edges|`, no insertion — *and* when a matching edge existed with non-empty new endpoints, the output contains an edge with those endpoints. Uses `//@ assume` to characterize destructuring, `find`, and the constructed edge), `connectionExists`, `getEdgeCenter` (midpoint correctness), `clamp` (bounds), `rectToBox`/`boxToRect` (field arithmetic), `getBoundsOfBoxes` (enclosure), `getOverlappingArea` (non-negative), `areSetsEqual` (subset + same size). 14 Dafny proof obligations. Also adds a new verified feature — a **DAG connection gate**: `canReach` decides reachability soundly *and* completely, and `wouldCreateCycle` gates both new connections and edge reconnections so the graph is proven to stay acyclic, with `isAcyclic` (sound + complete) establishing the base case and a topological-rank witness giving a safe evaluation order (+29 obligations), shown live in a React Flow demo that refuses cycle-closing edges — extending the case study from verifying existing code to adding a verified feature. Dafny only.
|
|
32
|
-
- **[rallly-lemmascript](https://github.com/midspiral/rallly-lemmascript/blob/lemmascript/README_LemmaScript.md)** — brownfield verification of [rallly](https://github.com/lukevella/rallly)'s meeting-poll Next.js app. 2 functions: `validateRedirectUrl` (in-place — open-redirect predicate; non-`undefined` outputs start with `/` but not `//`) and `scorePoll` (extracted ranking core — length preservation, score bounds, top-choice characterization, score-formula equality, within-poll monotonicity, tiebreaker injectivity). The injectivity proof surfaced a real spec-level constraint on the existing `(yes + ifNeedBe) * 1000 + yes` encoding: it overflows when an option has ≥ 1000 yes votes. 10 Dafny VCs, 0 errors. Drove four toolchain additions: `s.startsWith()`, `T | null` nullability, `\result` narrowing under `==>`, `Math.max(...arr)` spread. Dafny only.
|
|
33
|
-
- **[opencode-lemmascript](https://github.com/midspiral/opencode-lemmascript/blob/lemmascript/README_LemmaScript.md)** — brownfield verification of [opencode](https://github.com/anomalyco/opencode)'s permission system and unified-diff patch parser. Highlights: (1) `Patch.parsePatch` carries conservation loop invariants over local ghost state — a parser bug here would silently corrupt user files when an AI applies a patch, and (2) the permission-engine work mechanically closes opencode bug #26514 (subagents bypassing Plan Mode's file-edit restrictions). 9 functions verified in-place, 0 errors. Dafny only.
|
|
34
|
-
- **[pi-lemmascript](https://github.com/midspiral/pi-lemmascript/blob/lemmascript/README_LemmaScript.md)** — brownfield, **in-place** verification of the context-compaction cut-point selector in **pi** (the [earendil-works](https://pi.dev) agent harness). When the context window fills, pi discards history before a chosen cut; a provider API rejects a retained prefix containing an orphaned `toolResult` (a tool result whose tool call was cut away). Both selector functions proven: the cut never lets the kept suffix *start with* — nor *split a tool-use/tool-result run* into — an orphaned tool result, even across the backward metadata snap. The no-orphan result forced the session tree's tool-pairing ordering into an explicit `requires`. 4 VCs, 0 errors. Drove five toolchain additions, headlined by an **opaque fall-through type**: a union LemmaScript can't discriminate (here an array-element union of unreachable imports) becomes a single opaque `type` — the field stays present so distinct values stay distinct, and with no constructor or tag predicate it can only be passed through, never unsoundly observed. **Dafny + Lean**: the no-orphan theorem, the changelog semver core, and both tool-output truncators also carry Lean 4 (Velvet 2) proofs from the same annotated source, zero `sorry`; the Lean port drove the backend's brownfield batch (cross-file externs, union destructor lowering, Bool-vs-Prop contexts, `return`-in-loop elimination).
|
|
35
|
-
- **[flue-lemmascript](https://github.com/midspiral/flue-lemmascript/blob/lemmascript/README_LemmaScript.md)** — brownfield, **in-place** verification of pure logic in **Flue** ([withastro/flue](https://github.com/withastro/flue)), Astro's agent harness — crash-recovery and context-compaction functions proven byte-identical. What it drove into the toolchain: native Dafny `continue`, bounds-guarded `noUncheckedIndexedAccess` optional indexing, optional narrowing past an `opt?.disc` guard composing with discriminated-union matching, and object truthiness. Dafny only.
|
|
36
|
-
- **[balanced-match-lemmascript](https://github.com/midspiral/balanced-match-lemmascript/blob/lemmascript/README_LemmaScript.md)** — brownfield, **in-place** verification of [balanced-match](https://github.com/juliangruber/balanced-match), the ~70-line balanced-bracket finder pulled in by `npm`, `webpack`, and most of the JS tooling stack (1B+ downloads/month). The stack-based `range` core is verified by **refinement**: a pure recursive spec `range_spec` mirrors the loop one branch per recursive case, so the single equivalence `range == range_spec` transfers every property automatically — including an unconditional Dyck body-balance theorem for the interior of every returned pair. 2233 VCs, 0 errors under `--isolate-assertions` (registered on the `dafny-slow` track). Dafny only.
|
|
37
|
-
- **[guardians-lemmascript](https://github.com/midspiral/guardians-lemmascript)** — greenfield verification of the core safety argument behind [Guardians](https://github.com/metareflection/guardians) (Erik Meijer, "Guardians of the Agents", CACM Jan 2026), a generate-verify-execute checker for AI-agent workflows. Instead of verifying an app, it proves the agent *guardrail itself sound* — that a static taint/automaton check over the real recursive workflow AST can never admit an unsafe plan. Highlights: taint over **nested conditionals** as a sound branch-union over-approximation; per-source **provenance** with a join (a multi-input tool is tainted if *any* input was); **unbounded loops** discharged by a one-step pre-fixpoint (`sat = t0 ‖ bodyTaint(t0)`) that bounds taint over any iteration count without iterating to a fixpoint; and a **unified capstone** (`verifyWfSound`) — one clean verdict rules out, on *every* path, both a tainted-data-to-sink leak and a security-automaton error. 54 Dafny obligations, 0 errors. The verified cores are reached from a Guardians-style `Workflow`/`Policy` through a thin *unverified* adapter, differentially tested against the real Python Guardians (used as the oracle, not a porting target). Dafny only.
|
|
38
|
-
- **[quorum-lemmascript](https://github.com/midspiral/quorum-lemmascript)** — greenfield verified when2meet/Doodle-style group scheduler (React + Cloudflare Durable Objects), with one `domain.ts` running unchanged in the browser, the in-app query, and the server. The standout is that **the proof licenses the architecture**: `countFree` is a homomorphism from participant-list concatenation to integer addition (so the heatmap is order-independent) plus same-participant last-writer-wins convergence — which is exactly what makes the lock-free, no-login, *optimistic* multi-device backend safe, with the Durable Object and the browser applying the **same** verified `applyOp` (server-authoritatively, client-optimistically) with no rollback or operational transform. Also: heatmap is exactly the per-slot count and `isBest` exactly its argmax; monotonicity; invariant-preserving mutations + op-log `replay`; a sparse export codec round-trip; an in-app `whoIsFree(e, s)` whose length provably equals the cell's count; and a separate `grid.ts` proving the `(day, time) → slot` map in-range + injective — which makes specific-dates-vs-days-of-the-week pure shell labeling at zero proof cost; and full element-level permutation invariance (`heatmapPermInvariant` — the heatmap depends only on the *multiset* of participant rows), which drove the `perm(...)` spec predicate into LemmaScript itself. 100 Dafny VCs (90 + 10), 0 errors. The *aggregate* is proven; the React UI, WebSocket/DO I/O, and timezone labeling are the stated trust boundary. Dafny only.
|
|
39
|
-
- **[quota-lemmascript](https://github.com/midspiral/quota-lemmascript)** — greenfield verified booking app: providers publish a page of limited-capacity *featured slots*, signed-in users grab them (React + Cloudflare Durable Objects + D1). The deliberate **inverse** of [quorum-lemmascript](https://github.com/midspiral/quorum-lemmascript): bookings **contend** for shared inventory, so the invariant is a **bound** — for every slot `j`, `confirmedCount(bookings, j) <= slots[j].capacity` — and the *same* `domain.ts` runs in the browser and the Durable Object **server-authoritatively**, never overselling under contention (no optimistic client apply). Proven: no overbooking across `tryBook`/cancel, accept-iff-room, an **idempotent three-way `tryBook`** (a retry reads as success, not rejection), cancellation frees seats, replay determinism, and order-invariance — `confirmedCountPerm` / `hasRoomPermInvariant` show availability depends only on the *multiset* of the booking log, via the same `perm(...)` predicate Quorum drove into LemmaScript. 80 Dafny VCs, 0 errors. Trust boundary: auth, the React UI, WebSocket/DO/D1 I/O, email, slot date/time labeling, and abuse/rate-limiting. Dafny only.
|
|
40
|
-
- **[henri-lemmascript](https://github.com/midspiral/henri-lemmascript)** — a runnable TypeScript coding-agent CLI (a port of [henri](https://github.com/metareflection/henri/); multi-provider, Anthropic + AWS Bedrock) whose security- and protocol-critical core is verified and **imported directly by the live agent** — `decide()` gates every real tool call and the conversation invariant is asserted on every turn (it streams end-to-end against Bedrock). Three modules, 48 Dafny VCs, 0 errors. (1) **Permission gate**: soundness (`decide == Allow ⟺ isAllowed`), **path-traversal containment** — auto-allow-in-cwd can never resolve outside cwd, with `.`/`..` normalization proved in-core so the shell is trusted only to `resolve().split('/')` — grant monotonicity, and `rejectPrompts` is deny-only. (2) **Conversation protocol**: tool-call/result pairing plus the [pi-lemmascript](https://github.com/midspiral/pi-lemmascript)-style **no-orphaned-`tool_result`** property, proved as an invariant *preserved by the loop* — `wellFormed(msgs + [assistant(calls), tool(makeResults(calls))])` — not checked after the fact. (3) **Hook/config merge**: removal, **tool-name uniqueness — a fix** (henri concatenated hook tool lists with no dedup, so two hooks could shadow a name), order-independence, and additivity composed **cross-module** with the gate's monotonicity (merging only grows the allow-sets, which by P3 never revokes an `Allow`). The merge is verified **in place** via `//@ declare-type Tool { name: string }`, shadowing the real `Tool`'s function-valued `execute` so the actual `mergeTools(Tool[])` is the proof target rather than a parallel model. Dafny only.
|
|
41
|
-
- **[eslint-plugin-with-lemmascript](https://github.com/midspiral/eslint-plugin-with-lemmascript)** — a greenfield verified feature shipped through a brownfield host's *extension API*: a real, npm-published [ESLint](https://eslint.org) flat-config plugin whose rule decision is a machine-checked theorem. `no-forbidden-reach` enforces architecture boundaries — "the UI must never reach the DB layer" — through **any** import chain, catching the *laundered* `ui → service → db` violation that every one-hop incumbent (`import/no-restricted-paths`, `eslint-plugin-boundaries`, Nx module boundaries) silently passes. The verified core decides reachability soundly *and* completely (`reachesAny` / `violates`) and **constructs** the offending chain in proven code (`findReachPath` — a path-carrying BFS proven sound + complete by mirroring the frontier's endpoints in a ghost seq, so completeness reduces to the same closure argument as the reachability search; the chain printed in the lint error is therefore itself a *verified* import path, not a heuristic guess). The headline is a meta-theorem — `Domination` + `Strictness` — proving the transitive check **strictly dominates** one-hop checking: every direct violation is caught, *and* there provably exist laundered violations that direct-edge checks miss. 30 Dafny VCs, 0 errors. The reachability decision and the witness are proven; the import-graph extraction (which edges exist) is the stated trust boundary, and `dist/*.js` is `tsc`'s erasure of the verified source it ships alongside. Dafny only.
|
|
42
|
-
- **[infisical-lemmascript](https://github.com/midspiral/infisical-lemmascript/blob/lemmascript/README_LemmaScript.md)** — brownfield, **in-place** verification of the permission-boundary glob set-containment check in [Infisical](https://github.com/Infisical/infisical) — the privilege-escalation guard that stops a role from delegating broader secret-path access than it holds. The loop-bearing `segmentMatch` compiles to a Dafny `method` (unnameable in specs), so soundness is proven by **refinement**: the method certifies `result == segMatchSpec` (a pure mirror), and a standalone lemma proves that spec sound against a hand-written segment-glob semantics — *if it returns true, every path the subset glob matches, the parent matches too*. 12 Dafny VCs, 0 errors; drove a toolchain fix (recursive `method`s now carry a method-level `//@ decreases`). Dafny only.
|
|
15
|
+
See the [examples](examples) and [case studies](CASE_STUDIES.md) for verified TypeScript programs, libraries, and apps.
|
|
43
16
|
|
|
44
17
|
## Setup
|
|
45
18
|
|
package/package.json
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Dafny backend commands: gen, check, regen.
|
|
3
3
|
*/
|
|
4
|
-
import { existsSync, readFileSync, writeFileSync,
|
|
4
|
+
import { existsSync, readFileSync, writeFileSync, unlinkSync } from "fs";
|
|
5
5
|
import { execFileSync } from "child_process";
|
|
6
6
|
import path from "path";
|
|
7
7
|
import { DEFAULT_OPTIONS, parseOptionValue } from "./config.js";
|
|
8
|
+
import { proofAdditionViolations } from "./dafny-proof-additions.js";
|
|
8
9
|
function writeGen(genPath, text) {
|
|
9
10
|
writeFileSync(genPath, text);
|
|
10
11
|
console.log(`Generated: ${genPath}`);
|
|
@@ -78,6 +79,14 @@ function additionsOnly(genPath, dfyPath) {
|
|
|
78
79
|
console.error(" " + d);
|
|
79
80
|
return false;
|
|
80
81
|
}
|
|
82
|
+
// Added lines must not bypass the verifier or change its options.
|
|
83
|
+
const violations = proofAdditionViolations(readFileSync(genPath, "utf-8"), readFileSync(dfyPath, "utf-8"), path.basename(dfyPath));
|
|
84
|
+
if (violations.length > 0) {
|
|
85
|
+
console.error(`ERROR: ${path.basename(dfyPath)} has proof additions that bypass verification:`);
|
|
86
|
+
for (const v of violations)
|
|
87
|
+
console.error(" " + v);
|
|
88
|
+
return false;
|
|
89
|
+
}
|
|
81
90
|
return true;
|
|
82
91
|
}
|
|
83
92
|
/** Read the saved model, rejecting ambiguous headers before verification. */
|
|
@@ -187,25 +196,52 @@ export function dafnyRegen(genPath, dfyPath, basePath, text, dir, timeLimit, ext
|
|
|
187
196
|
const anchor = existsSync(basePath) ? readFileSync(basePath, "utf-8") : oldGen;
|
|
188
197
|
// 5. If gen changed, three-way merge
|
|
189
198
|
if (text !== anchor) {
|
|
190
|
-
const savedDfy = readFileSync(dfyPath, "utf-8");
|
|
191
199
|
if (!existsSync(basePath))
|
|
192
200
|
writeFileSync(basePath, anchor);
|
|
193
201
|
const mergedPath = dfyPath + ".merged";
|
|
194
202
|
console.log("Gen changed. Three-way merging...");
|
|
203
|
+
// -p prints the merge instead of writing it, so the proof file changes
|
|
204
|
+
// only after a clean merge.
|
|
205
|
+
const merge = (flags) => execFileSync("git", ["merge-file", "-p", ...flags, "--", dfyPath, basePath, genPath], { encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: Infinity });
|
|
206
|
+
let merged;
|
|
195
207
|
try {
|
|
196
|
-
|
|
197
|
-
|
|
208
|
+
try {
|
|
209
|
+
// Match the additions-only check: the default diff can misalign
|
|
210
|
+
// unchanged generated lines after a large inserted proof block.
|
|
211
|
+
merged = merge(["--diff-algorithm=minimal"]);
|
|
212
|
+
}
|
|
213
|
+
catch (e) {
|
|
214
|
+
// The other arguments are fixed, so a usage error (129) means this
|
|
215
|
+
// Git predates the option (2.44).
|
|
216
|
+
if (e?.status !== 129)
|
|
217
|
+
throw e;
|
|
218
|
+
console.warn("WARNING: this Git does not support git merge-file --diff-algorithm; retrying with the default algorithm. " +
|
|
219
|
+
"Upgrade to Git 2.44 or later to avoid false conflicts after large proof additions.");
|
|
220
|
+
merged = merge([]);
|
|
221
|
+
}
|
|
198
222
|
}
|
|
199
223
|
catch (e) {
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
224
|
+
// Git returns a conflict count capped at 127. Usage errors, fatal
|
|
225
|
+
// errors and interrupted/failed processes are not merge conflicts.
|
|
226
|
+
if (e?.status >= 1 && e.status <= 127) {
|
|
227
|
+
writeFileSync(mergedPath, e.stdout);
|
|
203
228
|
console.error(`CONFLICT: ${path.basename(dfyPath)} — merge had conflicts, dfy restored. See ${path.basename(mergedPath)}`);
|
|
204
229
|
log?.finish({ stage: "conflict", exit: 1, dfyPath });
|
|
205
|
-
process.exit(1);
|
|
206
230
|
}
|
|
207
|
-
|
|
231
|
+
else {
|
|
232
|
+
const reason = e?.code === "ENOENT" ? " (git not found on PATH)"
|
|
233
|
+
: e?.code != null ? ` (${e.code})`
|
|
234
|
+
: e?.signal != null ? ` (signal ${e.signal})`
|
|
235
|
+
: typeof e?.status === "number" ? ` (git exited ${e.status})` : "";
|
|
236
|
+
const detail = typeof e?.stderr === "string" ? e.stderr.trim() : "";
|
|
237
|
+
console.error(`ERROR: could not run \`git merge-file\` for ${path.basename(dfyPath)}${reason}; dfy restored` +
|
|
238
|
+
`${detail ? `: ${detail}` : "."}`);
|
|
239
|
+
log?.discard();
|
|
240
|
+
}
|
|
241
|
+
process.exit(1);
|
|
208
242
|
}
|
|
243
|
+
writeFileSync(dfyPath, merged);
|
|
244
|
+
console.log(`Merged: ${path.basename(dfyPath)}`);
|
|
209
245
|
}
|
|
210
246
|
// 6. Check gen invariant (unconditional)
|
|
211
247
|
if (!dafnyCheckDiff(genPath, dfyPath, log)) {
|
package/tools/dist/dafny-emit.js
CHANGED
|
@@ -7,6 +7,8 @@ import { renameFreeVar } from "./transform.js";
|
|
|
7
7
|
import { DEFAULT_OPTIONS, resolveOptions } from "./config.js";
|
|
8
8
|
/** Appended to a function's name for the lemma that carries its `//@ ensures`. */
|
|
9
9
|
export const ENSURES_LEMMA_SUFFIX = "_ensures";
|
|
10
|
+
/** `function by method` bodies delegate to a proof-defined `<name>_fun_spec`. */
|
|
11
|
+
export const SPEC_FUNCTION_SUFFIX = "_fun_spec";
|
|
10
12
|
/** Fresh binder for a comprehension wrapping the given subexpressions: `base`
|
|
11
13
|
* verbatim unless one of them references it, then primed until free. A *local*
|
|
12
14
|
* check — a same-named name elsewhere in the module keeps the plain binder. */
|
|
@@ -178,12 +180,13 @@ function isEmittedUserName(name) {
|
|
|
178
180
|
* namespace so it can't collapse onto an escaped user name. Bypasses the user
|
|
179
181
|
* map on purpose: the raw name is synthesized, so it must be freshened *away
|
|
180
182
|
* from* a same-spelled user name, not aliased onto it. Cached so a declaration
|
|
181
|
-
* and its references render identically.
|
|
182
|
-
|
|
183
|
+
* and its references render identically. An optional base changes the candidate
|
|
184
|
+
* spelling without changing the original name used as the cache key. */
|
|
185
|
+
function escapeGeneratedName(name, base = name) {
|
|
183
186
|
const cached = _generatedDafnyNames.get(name);
|
|
184
187
|
if (cached !== undefined)
|
|
185
188
|
return cached;
|
|
186
|
-
const emitted = freshDafnyName(dafnyBaseName(
|
|
189
|
+
const emitted = freshDafnyName(dafnyBaseName(base));
|
|
187
190
|
_generatedDafnyNames.set(name, emitted);
|
|
188
191
|
_takenDafnyNames.add(emitted);
|
|
189
192
|
return emitted;
|
|
@@ -357,7 +360,19 @@ function emitExpr(e) {
|
|
|
357
360
|
needPreamble("SafeSlice");
|
|
358
361
|
return `SafeSlice(${obj}, ${args[0]}, ${args[1] ?? `|${obj}|`})`;
|
|
359
362
|
}
|
|
360
|
-
|
|
363
|
+
// JS negative index: xs.slice(0, -N) → xs[0..|xs|-N].
|
|
364
|
+
// Same rewrite the string branch uses.
|
|
365
|
+
const negVal = (a) => {
|
|
366
|
+
const v = exactIntegerLiteral(a);
|
|
367
|
+
return v !== null && v < 0n ? (-v).toString(10) : null;
|
|
368
|
+
};
|
|
369
|
+
const loN = negVal(e.args[0]);
|
|
370
|
+
const loEx = loN !== null ? `|${obj}|-${loN}` : args[0];
|
|
371
|
+
if (args.length === 1)
|
|
372
|
+
return `${obj}[${loEx}..]`;
|
|
373
|
+
const hiN = negVal(e.args[1]);
|
|
374
|
+
const hiEx = hiN !== null ? `|${obj}|-${hiN}` : args[1];
|
|
375
|
+
return `${obj}[${loEx}..${hiEx}]`;
|
|
361
376
|
}
|
|
362
377
|
if (e.method === "map") {
|
|
363
378
|
// Always a seq comprehension: Seq.Map would hide the element access
|
|
@@ -541,10 +556,12 @@ function emitExpr(e) {
|
|
|
541
556
|
return `StringTrimLeft(${obj})`;
|
|
542
557
|
}
|
|
543
558
|
if (e.method === "toLowerCase") {
|
|
559
|
+
needPreamble("StringIsAscii");
|
|
544
560
|
needPreamble("StringToLower");
|
|
545
561
|
return `StringToLower(${obj})`;
|
|
546
562
|
}
|
|
547
563
|
if (e.method === "toUpperCase") {
|
|
564
|
+
needPreamble("StringIsAscii");
|
|
548
565
|
needPreamble("StringToUpper");
|
|
549
566
|
return `StringToUpper(${obj})`;
|
|
550
567
|
}
|
|
@@ -705,6 +722,8 @@ function emitExpr(e) {
|
|
|
705
722
|
needPreamble("CeilReal");
|
|
706
723
|
if (e.fn === "FloorReal")
|
|
707
724
|
needPreamble("FloorReal");
|
|
725
|
+
if (e.fn === "TruncReal")
|
|
726
|
+
needPreamble("TruncReal");
|
|
708
727
|
if (e.fn === "StringFromCharCode")
|
|
709
728
|
needPreamble("StringFromCharCode");
|
|
710
729
|
if (e.fn === "NatToString")
|
|
@@ -719,6 +738,8 @@ function emitExpr(e) {
|
|
|
719
738
|
needPreamble("MathMin");
|
|
720
739
|
if (e.fn === "MathMax")
|
|
721
740
|
needPreamble("MathMax");
|
|
741
|
+
if (e.fn === "IsSafeIntegerReal")
|
|
742
|
+
needPreamble("IsSafeIntegerReal");
|
|
722
743
|
if (e.fn === "MathAbsReal")
|
|
723
744
|
needPreamble("MathAbsReal");
|
|
724
745
|
if (e.fn === "MathMinReal")
|
|
@@ -733,6 +754,16 @@ function emitExpr(e) {
|
|
|
733
754
|
needPreamble("MathMin");
|
|
734
755
|
needPreamble("MinOfSeq");
|
|
735
756
|
}
|
|
757
|
+
if (e.fn === "MaxOfSeqReal") {
|
|
758
|
+
needPreamble("MathMaxReal");
|
|
759
|
+
needPreamble("MaxOfSeqReal");
|
|
760
|
+
}
|
|
761
|
+
if (e.fn === "MinOfSeqReal") {
|
|
762
|
+
needPreamble("MathMinReal");
|
|
763
|
+
needPreamble("MinOfSeqReal");
|
|
764
|
+
}
|
|
765
|
+
if (e.fn === "SeqIntToReal")
|
|
766
|
+
needPreamble("SeqIntToReal");
|
|
736
767
|
if (e.fn === "Perm")
|
|
737
768
|
needPreamble("Perm");
|
|
738
769
|
if (e.fn === "SetFromSeq")
|
|
@@ -776,6 +807,10 @@ function emitExpr(e) {
|
|
|
776
807
|
case "toInt": return emitExpr(e.expr);
|
|
777
808
|
case "toReal":
|
|
778
809
|
return `(${emitExpr(e.expr)} as real)`;
|
|
810
|
+
case "stringIndex":
|
|
811
|
+
// TS indexing returns a string; Dafny's native string subscript is a
|
|
812
|
+
// char. The singleton sequence preserves the native bounds obligation.
|
|
813
|
+
return `[${emitExpr(e.str)}[${emitExpr(e.idx)}]]`;
|
|
779
814
|
case "index": {
|
|
780
815
|
const obj = emitExpr(e.arr);
|
|
781
816
|
const idx = emitExpr(e.idx);
|
|
@@ -1044,12 +1079,22 @@ function emitDecl(d) {
|
|
|
1044
1079
|
}
|
|
1045
1080
|
case "def-by-method": {
|
|
1046
1081
|
const tp = d.typeParams.length > 0 ? `<${d.typeParams.join(", ")}>` : "";
|
|
1047
|
-
const
|
|
1048
|
-
|
|
1049
|
-
|
|
1082
|
+
const signature = `${tp}(${paramList(d.params)}): ${tyToDafny(d.returnType)}`;
|
|
1083
|
+
const requires = d.requires.map(r => ` requires ${emitExpr(r)}`);
|
|
1084
|
+
// The functional specification is the proof author's to write: a bodyless
|
|
1085
|
+
// `<name>_fun_spec` stub, which the .dfy completes by adding a body after its
|
|
1086
|
+
// signature. The generated file parses and resolves on its own (an empty
|
|
1087
|
+
// function body would not), and the proof adds lines instead of editing
|
|
1088
|
+
// between generated braces.
|
|
1089
|
+
const spec = escapeGeneratedName(`${d.name}${SPEC_FUNCTION_SUFFIX}`);
|
|
1090
|
+
const lines = [
|
|
1091
|
+
`function ${spec}${signature}`, ...requires, "",
|
|
1092
|
+
`function ${escapeName(d.name)}${signature}`, ...requires,
|
|
1093
|
+
];
|
|
1050
1094
|
if (d.decreases)
|
|
1051
1095
|
lines.push(` decreases ${emitExpr(d.decreases)}`);
|
|
1052
1096
|
lines.push(`{`);
|
|
1097
|
+
lines.push(` ${spec}(${d.params.map(p => escapeName(p.name)).join(", ")})`);
|
|
1053
1098
|
lines.push(`}`);
|
|
1054
1099
|
lines.push(`by method {`);
|
|
1055
1100
|
lines.push(emitStmts(d.methodBody, 1));
|
|
@@ -1194,6 +1239,16 @@ const CEIL_REAL = `function CeilReal(x: real): int
|
|
|
1194
1239
|
if x == (x.Floor as real) then x.Floor
|
|
1195
1240
|
else x.Floor + 1
|
|
1196
1241
|
}`;
|
|
1242
|
+
const IS_SAFE_INTEGER_REAL = `predicate IsSafeIntegerReal(x: real)
|
|
1243
|
+
{
|
|
1244
|
+
x.Floor as real == x && -9007199254740991 <= x.Floor <= 9007199254740991
|
|
1245
|
+
}`;
|
|
1246
|
+
const TRUNC_REAL = `function TruncReal(x: real): (t: int)
|
|
1247
|
+
ensures x >= 0.0 ==> t as real <= x < t as real + 1.0
|
|
1248
|
+
ensures x < 0.0 ==> t as real - 1.0 < x <= t as real
|
|
1249
|
+
{
|
|
1250
|
+
if x >= 0.0 then x.Floor else -((-x).Floor)
|
|
1251
|
+
}`;
|
|
1197
1252
|
const CALLBACK_INDICES = `function CallbackIndices(n: nat): (r: seq<int>)
|
|
1198
1253
|
ensures |r| == n
|
|
1199
1254
|
ensures forall i :: 0 <= i < n ==> r[i] == i
|
|
@@ -1479,26 +1534,42 @@ function StringTrim(s: string): string
|
|
|
1479
1534
|
// The same predicate and trims under `--unicode-char:true`, which the
|
|
1480
1535
|
// `unicode-scalar` profile verifies under: byte-identical to what was always emitted.
|
|
1481
1536
|
const STRING_TRIM_SCALAR = STRING_TRIM.replace(/\\u([0-9A-F]{4})/g, "\\U{$1}");
|
|
1482
|
-
|
|
1483
|
-
|
|
1537
|
+
// `s.toLowerCase()` / `s.toUpperCase()` apply JavaScript's full Unicode case
|
|
1538
|
+
// mapping (UnicodeData plus SpecialCasing): non-ASCII letters change and the
|
|
1539
|
+
// length can change ("ß".toUpperCase() is "SS", "İ".toLowerCase() has length 2).
|
|
1540
|
+
// The helpers are therefore axioms that fix only the all-ASCII case, where
|
|
1541
|
+
// JavaScript maps exactly A-Z <-> a-z and leaves every other character alone.
|
|
1542
|
+
// Any other input has an unconstrained (but deterministic) result.
|
|
1543
|
+
const STRING_IS_ASCII = `predicate StringIsAscii(s: string)
|
|
1544
|
+
{
|
|
1545
|
+
forall i :: 0 <= i < |s| ==> (s[i] as int) < 128
|
|
1546
|
+
}`;
|
|
1547
|
+
const STRING_TO_LOWER = `function AsciiToLower(s: string): string
|
|
1548
|
+
ensures |AsciiToLower(s)| == |s|
|
|
1484
1549
|
decreases |s|
|
|
1485
1550
|
{
|
|
1486
1551
|
if |s| == 0 then ""
|
|
1487
1552
|
else
|
|
1488
1553
|
var c := s[0];
|
|
1489
1554
|
var lower := if 'A' <= c <= 'Z' then (c - 'A' + 'a') as char else c;
|
|
1490
|
-
[lower] +
|
|
1491
|
-
}
|
|
1492
|
-
|
|
1493
|
-
|
|
1555
|
+
[lower] + AsciiToLower(s[1..])
|
|
1556
|
+
}
|
|
1557
|
+
|
|
1558
|
+
function {:axiom} StringToLower(s: string): string
|
|
1559
|
+
ensures StringIsAscii(s) ==> StringToLower(s) == AsciiToLower(s)`;
|
|
1560
|
+
const STRING_TO_UPPER = `function AsciiToUpper(s: string): string
|
|
1561
|
+
ensures |AsciiToUpper(s)| == |s|
|
|
1494
1562
|
decreases |s|
|
|
1495
1563
|
{
|
|
1496
1564
|
if |s| == 0 then ""
|
|
1497
1565
|
else
|
|
1498
1566
|
var c := s[0];
|
|
1499
1567
|
var upper := if 'a' <= c <= 'z' then (c - 'a' + 'A') as char else c;
|
|
1500
|
-
[upper] +
|
|
1501
|
-
}
|
|
1568
|
+
[upper] + AsciiToUpper(s[1..])
|
|
1569
|
+
}
|
|
1570
|
+
|
|
1571
|
+
function {:axiom} StringToUpper(s: string): string
|
|
1572
|
+
ensures StringIsAscii(s) ==> StringToUpper(s) == AsciiToUpper(s)`;
|
|
1502
1573
|
// `String.fromCharCode(n)` — the inverse of `s.charCodeAt(i)`'s `(s[i] as int)`
|
|
1503
1574
|
// in the UTF-16 code-unit model selected by dafny-commands.ts. LemmaScript
|
|
1504
1575
|
// currently admits the direct 16-bit range; JavaScript's wider ToUint16 coercion
|
|
@@ -1574,6 +1645,56 @@ lemma MinOfSeqConcat(a: seq<int>, b: seq<int>)
|
|
|
1574
1645
|
assert (a + b)[|a| + i] == b[i];
|
|
1575
1646
|
}
|
|
1576
1647
|
}`;
|
|
1648
|
+
const MAX_OF_SEQ_REAL = `function MaxOfSeqReal(s: seq<real>): real
|
|
1649
|
+
requires |s| > 0
|
|
1650
|
+
ensures forall i: nat :: i < |s| ==> s[i] <= MaxOfSeqReal(s)
|
|
1651
|
+
ensures exists i: nat :: i < |s| && s[i] == MaxOfSeqReal(s)
|
|
1652
|
+
decreases |s|
|
|
1653
|
+
{
|
|
1654
|
+
if |s| == 1 then s[0]
|
|
1655
|
+
else MathMaxReal(s[0], MaxOfSeqReal(s[1..]))
|
|
1656
|
+
}
|
|
1657
|
+
|
|
1658
|
+
lemma MaxOfSeqRealConcat(a: seq<real>, b: seq<real>)
|
|
1659
|
+
requires |a| + |b| > 0
|
|
1660
|
+
ensures forall i: nat :: i < |a| ==> a[i] <= MaxOfSeqReal(a + b)
|
|
1661
|
+
ensures forall i: nat :: i < |b| ==> b[i] <= MaxOfSeqReal(a + b)
|
|
1662
|
+
{
|
|
1663
|
+
forall i: nat | i < |a| ensures a[i] <= MaxOfSeqReal(a + b) {
|
|
1664
|
+
assert (a + b)[i] == a[i];
|
|
1665
|
+
}
|
|
1666
|
+
forall i: nat | i < |b| ensures b[i] <= MaxOfSeqReal(a + b) {
|
|
1667
|
+
assert (a + b)[|a| + i] == b[i];
|
|
1668
|
+
}
|
|
1669
|
+
}`;
|
|
1670
|
+
const MIN_OF_SEQ_REAL = `function MinOfSeqReal(s: seq<real>): real
|
|
1671
|
+
requires |s| > 0
|
|
1672
|
+
ensures forall i: nat :: i < |s| ==> MinOfSeqReal(s) <= s[i]
|
|
1673
|
+
ensures exists i: nat :: i < |s| && s[i] == MinOfSeqReal(s)
|
|
1674
|
+
decreases |s|
|
|
1675
|
+
{
|
|
1676
|
+
if |s| == 1 then s[0]
|
|
1677
|
+
else MathMinReal(s[0], MinOfSeqReal(s[1..]))
|
|
1678
|
+
}
|
|
1679
|
+
|
|
1680
|
+
lemma MinOfSeqRealConcat(a: seq<real>, b: seq<real>)
|
|
1681
|
+
requires |a| + |b| > 0
|
|
1682
|
+
ensures forall i: nat :: i < |a| ==> MinOfSeqReal(a + b) <= a[i]
|
|
1683
|
+
ensures forall i: nat :: i < |b| ==> MinOfSeqReal(a + b) <= b[i]
|
|
1684
|
+
{
|
|
1685
|
+
forall i: nat | i < |a| ensures MinOfSeqReal(a + b) <= a[i] {
|
|
1686
|
+
assert (a + b)[i] == a[i];
|
|
1687
|
+
}
|
|
1688
|
+
forall i: nat | i < |b| ensures MinOfSeqReal(a + b) <= b[i] {
|
|
1689
|
+
assert (a + b)[|a| + i] == b[i];
|
|
1690
|
+
}
|
|
1691
|
+
}`;
|
|
1692
|
+
const SEQ_INT_TO_REAL = `function SeqIntToReal(s: seq<int>): seq<real>
|
|
1693
|
+
ensures |SeqIntToReal(s)| == |s|
|
|
1694
|
+
ensures forall i: nat :: i < |s| ==> SeqIntToReal(s)[i] == (s[i] as real)
|
|
1695
|
+
{
|
|
1696
|
+
seq(|s|, i requires 0 <= i < |s| => s[i] as real)
|
|
1697
|
+
}`;
|
|
1577
1698
|
const NAT_TO_STRING = `function NatToString(n: nat): string
|
|
1578
1699
|
decreases n
|
|
1579
1700
|
{
|
|
@@ -1627,6 +1748,8 @@ const PREAMBLE_CODE = [
|
|
|
1627
1748
|
["JSStringLt", JS_STRING_LT],
|
|
1628
1749
|
["CeilReal", CEIL_REAL],
|
|
1629
1750
|
["FloorReal", FLOOR_REAL],
|
|
1751
|
+
["IsSafeIntegerReal", IS_SAFE_INTEGER_REAL],
|
|
1752
|
+
["TruncReal", TRUNC_REAL],
|
|
1630
1753
|
["SeqIndexOf", SEQ_INDEX_OF],
|
|
1631
1754
|
["SeqFindIndex", SEQ_FIND_INDEX],
|
|
1632
1755
|
["SeqFindLastIndex", SEQ_FIND_LAST_INDEX],
|
|
@@ -1649,6 +1772,7 @@ const PREAMBLE_CODE = [
|
|
|
1649
1772
|
["SeqSort", SEQ_SORT],
|
|
1650
1773
|
["SeqSortBy", SEQ_SORT_BY],
|
|
1651
1774
|
["StringTrim", () => isUtf16() ? STRING_TRIM : STRING_TRIM_SCALAR],
|
|
1775
|
+
["StringIsAscii", STRING_IS_ASCII],
|
|
1652
1776
|
["StringToLower", STRING_TO_LOWER],
|
|
1653
1777
|
["StringToUpper", STRING_TO_UPPER],
|
|
1654
1778
|
["StringFromCharCode", () => isUtf16() ? STRING_FROM_CHAR_CODE : STRING_FROM_CHAR_CODE_SCALAR],
|
|
@@ -1663,6 +1787,9 @@ const PREAMBLE_CODE = [
|
|
|
1663
1787
|
["MathMaxReal", MATH_MAX_REAL],
|
|
1664
1788
|
["MaxOfSeq", MAX_OF_SEQ],
|
|
1665
1789
|
["MinOfSeq", MIN_OF_SEQ],
|
|
1790
|
+
["MaxOfSeqReal", MAX_OF_SEQ_REAL],
|
|
1791
|
+
["MinOfSeqReal", MIN_OF_SEQ_REAL],
|
|
1792
|
+
["SeqIntToReal", SEQ_INT_TO_REAL],
|
|
1666
1793
|
["Perm", PERM],
|
|
1667
1794
|
["SetFromSeq", SET_FROM_SEQ],
|
|
1668
1795
|
];
|
|
@@ -1763,11 +1890,11 @@ function resolveTy(ty) {
|
|
|
1763
1890
|
}
|
|
1764
1891
|
/** Constructor names come from source strings (string-union values like
|
|
1765
1892
|
* "spec-pure", discriminated-union tags), which may contain characters no
|
|
1766
|
-
* TS identifier has
|
|
1767
|
-
*
|
|
1768
|
-
*
|
|
1893
|
+
* TS identifier has. Sanitize only the candidate spelling, keeping the original
|
|
1894
|
+
* literal as the cache key so distinct literals cannot collapse onto one entry.
|
|
1895
|
+
* Identifier-shaped tags retain their existing source-name mapping. */
|
|
1769
1896
|
function dafnyCtorName(name) {
|
|
1770
|
-
return
|
|
1897
|
+
return _userDafnyNames.get(name) ?? escapeGeneratedName(name, name.replace(/[^A-Za-z0-9_'?]/g, "_"));
|
|
1771
1898
|
}
|
|
1772
1899
|
function qualifyCtor(name, type) {
|
|
1773
1900
|
const rawName = name.replace(/^\./, "");
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Check the lines a `.dfy` proof adds to its `.dfy.gen` companion for
|
|
3
|
+
* constructs that bypass verification.
|
|
4
|
+
*
|
|
5
|
+
* Added lines may not contain `assume` statements or `{:axiom}` / `@Axiom`
|
|
6
|
+
* attributes. Text inside comments (including nested block comments),
|
|
7
|
+
* strings (including verbatim strings), and character literals is ignored.
|
|
8
|
+
* Separately, added lines may not introduce an `// lsc options:` header,
|
|
9
|
+
* because verifier flags are read from that header in the proof, and may not
|
|
10
|
+
* contain line breaks other than `\n` (Dafny ends a `//` comment at `\r`).
|
|
11
|
+
* A generated line kept in the proof must lex to the same tokens it has in
|
|
12
|
+
* the generated file, so added comments or strings cannot disable it, and an
|
|
13
|
+
* added line may not repeat a generated `assume` / axiom line.
|
|
14
|
+
*/
|
|
15
|
+
const OPERATORS = ["<==>", "==>", "<==", "==", "!=", "<=", ">=", ":=", "::", "->", "=>", "&&", "||", ".."];
|
|
16
|
+
/** Dafny identifiers may start with `'` or `?` (`?x` and `'x` are names). */
|
|
17
|
+
function isWordStart(ch) {
|
|
18
|
+
return /[A-Za-z0-9_'?]/.test(ch);
|
|
19
|
+
}
|
|
20
|
+
function isWordChar(ch) {
|
|
21
|
+
return /[A-Za-z0-9_'?]/.test(ch);
|
|
22
|
+
}
|
|
23
|
+
/** Tokenize Dafny source, dropping comments and collapsing literals to single tokens. */
|
|
24
|
+
export function lexDafny(text) {
|
|
25
|
+
const tokens = [];
|
|
26
|
+
let line = 0;
|
|
27
|
+
let i = 0;
|
|
28
|
+
const advance = (to) => {
|
|
29
|
+
for (; i < to && i < text.length; i++)
|
|
30
|
+
if (text[i] === "\n")
|
|
31
|
+
line++;
|
|
32
|
+
};
|
|
33
|
+
while (i < text.length) {
|
|
34
|
+
const ch = text[i];
|
|
35
|
+
const next = text[i + 1];
|
|
36
|
+
if (/\s/.test(ch)) {
|
|
37
|
+
advance(i + 1);
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
if (ch === "/" && next === "/") {
|
|
41
|
+
const end = text.indexOf("\n", i);
|
|
42
|
+
advance(end < 0 ? text.length : end);
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
if (ch === "/" && next === "*") {
|
|
46
|
+
let depth = 0;
|
|
47
|
+
let j = i;
|
|
48
|
+
while (j < text.length) {
|
|
49
|
+
if (text[j] === "/" && text[j + 1] === "*") {
|
|
50
|
+
depth++;
|
|
51
|
+
j += 2;
|
|
52
|
+
}
|
|
53
|
+
else if (text[j] === "*" && text[j + 1] === "/") {
|
|
54
|
+
depth--;
|
|
55
|
+
j += 2;
|
|
56
|
+
if (depth === 0)
|
|
57
|
+
break;
|
|
58
|
+
}
|
|
59
|
+
else
|
|
60
|
+
j++;
|
|
61
|
+
}
|
|
62
|
+
advance(j);
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
const start = line;
|
|
66
|
+
if (ch === "@" && next === "\"") {
|
|
67
|
+
let j = i + 2;
|
|
68
|
+
while (j < text.length) {
|
|
69
|
+
if (text[j] === "\"" && text[j + 1] === "\"")
|
|
70
|
+
j += 2;
|
|
71
|
+
else if (text[j] === "\"") {
|
|
72
|
+
j++;
|
|
73
|
+
break;
|
|
74
|
+
}
|
|
75
|
+
else
|
|
76
|
+
j++;
|
|
77
|
+
}
|
|
78
|
+
tokens.push({ text: "\"\"", line: start });
|
|
79
|
+
advance(j);
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
if (ch === "\"") {
|
|
83
|
+
let j = i + 1;
|
|
84
|
+
while (j < text.length && text[j] !== "\"" && text[j] !== "\n")
|
|
85
|
+
j += text[j] === "\\" ? 2 : 1;
|
|
86
|
+
tokens.push({ text: "\"\"", line: start });
|
|
87
|
+
advance(j + 1);
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
if (ch === "'") {
|
|
91
|
+
const literal = /^'(?:\\u\{[0-9A-Fa-f_]+\}|\\U\{[0-9A-Fa-f_]+\}|\\u[0-9A-Fa-f]{4}|\\.|[^'\\\n])'/u.exec(text.slice(i));
|
|
92
|
+
if (literal) {
|
|
93
|
+
tokens.push({ text: "''", line: start });
|
|
94
|
+
advance(i + literal[0].length);
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
if (isWordStart(ch)) {
|
|
99
|
+
let j = i + 1;
|
|
100
|
+
while (j < text.length && isWordChar(text[j]))
|
|
101
|
+
j++;
|
|
102
|
+
tokens.push({ text: text.slice(i, j), line: start });
|
|
103
|
+
advance(j);
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
if (ch === "{" && next === ":") {
|
|
107
|
+
tokens.push({ text: "{:", line: start });
|
|
108
|
+
advance(i + 2);
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
const op = OPERATORS.find(o => text.startsWith(o, i));
|
|
112
|
+
tokens.push({ text: op ?? ch, line: start });
|
|
113
|
+
advance(i + (op?.length ?? 1));
|
|
114
|
+
}
|
|
115
|
+
return tokens;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Map each proof line to the generated line it keeps, or -1 for an added
|
|
119
|
+
* line, matching each generated line to the earliest equal proof line.
|
|
120
|
+
* Returns undefined when the generated lines do not all appear in order.
|
|
121
|
+
*/
|
|
122
|
+
function matchGeneratedLines(genLines, proofLines) {
|
|
123
|
+
const matched = [];
|
|
124
|
+
let g = 0;
|
|
125
|
+
for (const line of proofLines) {
|
|
126
|
+
const generated = g < genLines.length && line === genLines[g];
|
|
127
|
+
matched.push(generated ? g++ : -1);
|
|
128
|
+
}
|
|
129
|
+
return g === genLines.length ? matched : undefined;
|
|
130
|
+
}
|
|
131
|
+
/** Token texts starting on each line, joined with a separator. */
|
|
132
|
+
function tokensByLine(tokens, lineCount) {
|
|
133
|
+
const lines = Array.from({ length: lineCount }, () => []);
|
|
134
|
+
for (const t of tokens)
|
|
135
|
+
lines[t.line]?.push(t.text);
|
|
136
|
+
return lines.map(l => l.join("\u0000"));
|
|
137
|
+
}
|
|
138
|
+
/** Whether a token sequence contains an `assume`, `{:axiom}` or `@Axiom`. */
|
|
139
|
+
function trustsFact(tokens, k) {
|
|
140
|
+
const t = tokens[k].text, following = tokens[k + 1]?.text;
|
|
141
|
+
if (t === "assume")
|
|
142
|
+
return "assume statements are not allowed in proof additions; prove the fact instead";
|
|
143
|
+
if (t === "{:" && following === "axiom")
|
|
144
|
+
return "{:axiom} attributes are not allowed in proof additions; give the declaration a proof or body";
|
|
145
|
+
if (t === "@" && following === "Axiom")
|
|
146
|
+
return "@Axiom attributes are not allowed in proof additions; give the declaration a proof or body";
|
|
147
|
+
return undefined;
|
|
148
|
+
}
|
|
149
|
+
/** Matches the header `dafnyVerifyArgs` reads verifier options from. */
|
|
150
|
+
const LSC_OPTIONS_HEADER = /^\/\/ lsc options:/m;
|
|
151
|
+
/** Line terminators other than `\n` that Dafny or a header regex may honor. */
|
|
152
|
+
const OTHER_LINE_BREAK = /[\r\u2028\u2029]/;
|
|
153
|
+
/**
|
|
154
|
+
* Check the proof additions, returning one diagnostic per rejected construct.
|
|
155
|
+
* Diagnostics name the 1-based proof line, the reason, and the line text.
|
|
156
|
+
*/
|
|
157
|
+
export function proofAdditionViolations(generated, proof, proofName) {
|
|
158
|
+
const proofLines = proof.split("\n");
|
|
159
|
+
const genLines = generated.split("\n");
|
|
160
|
+
const matched = matchGeneratedLines(genLines, proofLines);
|
|
161
|
+
if (!matched)
|
|
162
|
+
return [`${proofName}: generated lines are not contained in order in the proof`];
|
|
163
|
+
const added = matched.map(g => g < 0);
|
|
164
|
+
const violations = [];
|
|
165
|
+
const report = (line, reason) => violations.push(`${proofName}:${line + 1}: ${reason}: ${proofLines[line].trim()}`);
|
|
166
|
+
const tokens = lexDafny(proof);
|
|
167
|
+
for (let k = 0; k < tokens.length; k++) {
|
|
168
|
+
if (!added[tokens[k].line])
|
|
169
|
+
continue;
|
|
170
|
+
const reason = trustsFact(tokens, k);
|
|
171
|
+
if (reason)
|
|
172
|
+
report(tokens[k].line, reason);
|
|
173
|
+
}
|
|
174
|
+
const genTokens = lexDafny(generated);
|
|
175
|
+
const trustedGenLines = new Set();
|
|
176
|
+
for (let k = 0; k < genTokens.length; k++) {
|
|
177
|
+
if (trustsFact(genTokens, k))
|
|
178
|
+
trustedGenLines.add(genLines[genTokens[k].line]);
|
|
179
|
+
}
|
|
180
|
+
const proofLineTokens = tokensByLine(tokens, proofLines.length);
|
|
181
|
+
const genLineTokens = tokensByLine(genTokens, genLines.length);
|
|
182
|
+
proofLines.forEach((text, line) => {
|
|
183
|
+
const g = matched[line];
|
|
184
|
+
if (g >= 0) {
|
|
185
|
+
if (proofLineTokens[line] !== genLineTokens[g])
|
|
186
|
+
report(line, "added text changes how this generated line is read (for example, by placing it inside a comment or string)");
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
if (OTHER_LINE_BREAK.test(text))
|
|
190
|
+
report(line, "added lines may only use `\\n` line breaks; Dafny ends a `//` comment at `\\r`");
|
|
191
|
+
if (LSC_OPTIONS_HEADER.test(text))
|
|
192
|
+
report(line, "an added `// lsc options:` line would change verifier options; options come from the generated file");
|
|
193
|
+
if (trustedGenLines.has(text))
|
|
194
|
+
report(line, "added lines may not repeat a generated assume or axiom line; keep the generated line in place");
|
|
195
|
+
});
|
|
196
|
+
return violations;
|
|
197
|
+
}
|
package/tools/dist/extract.js
CHANGED
|
@@ -566,7 +566,35 @@ function extractExpr(node) {
|
|
|
566
566
|
? p.getType().getText(p) : typeToString(p.getType()) } : {}),
|
|
567
567
|
};
|
|
568
568
|
if (Node.isArrayBindingPattern(nameNode)) {
|
|
569
|
-
|
|
569
|
+
// ([a, , c]) => e binds each named position by index, like the
|
|
570
|
+
// `const [a, , c] = arr` lowering; an elided position binds nothing.
|
|
571
|
+
if (p.getInitializer()) {
|
|
572
|
+
throw new Error(`defaulted array binding pattern in arrow parameter not yet supported: ${p.getText()}`);
|
|
573
|
+
}
|
|
574
|
+
const paramName = freshName(`_lambdaParam${paramIndex}`);
|
|
575
|
+
nameNode.getElements().forEach((el, i) => {
|
|
576
|
+
if (Node.isOmittedExpression(el))
|
|
577
|
+
return;
|
|
578
|
+
if (el.getDotDotDotToken()) {
|
|
579
|
+
throw new Error(`rest element in arrow parameter destructuring not yet supported: ${el.getText()}`);
|
|
580
|
+
}
|
|
581
|
+
if (el.getInitializer()) {
|
|
582
|
+
throw new Error(`default value in arrow parameter destructuring not yet supported: ${el.getText()}`);
|
|
583
|
+
}
|
|
584
|
+
const localNode = el.getNameNode();
|
|
585
|
+
if (!Node.isIdentifier(localNode)) {
|
|
586
|
+
throw new Error(`nested binding pattern in arrow parameter destructuring not yet supported: ${el.getText()}`);
|
|
587
|
+
}
|
|
588
|
+
destructureBindings.push({
|
|
589
|
+
kind: "let",
|
|
590
|
+
name: localNode.getText(),
|
|
591
|
+
mutable: false,
|
|
592
|
+
tsType: null,
|
|
593
|
+
init: { kind: "index", obj: { kind: "var", name: paramName }, idx: { kind: "num", value: i } },
|
|
594
|
+
line: p.getStartLineNumber(),
|
|
595
|
+
});
|
|
596
|
+
});
|
|
597
|
+
return { name: paramName, tsType };
|
|
570
598
|
}
|
|
571
599
|
if (!Node.isObjectBindingPattern(nameNode)) {
|
|
572
600
|
throw new Error(`unsupported arrow parameter binding: ${p.getName()}`);
|
|
@@ -719,9 +747,11 @@ function extractExpr(node) {
|
|
|
719
747
|
return { kind: "emptyCollection", collectionType: name, tsType };
|
|
720
748
|
}
|
|
721
749
|
}
|
|
722
|
-
// As-expression: expr as T — strip the type assertion
|
|
723
750
|
if (Node.isAsExpression(node)) {
|
|
724
|
-
|
|
751
|
+
const expr = extractExpr(node.getExpression());
|
|
752
|
+
return expr.kind === "record" && !expr.spread
|
|
753
|
+
? { ...expr, assertedTsType: typeToString(node.getType()) }
|
|
754
|
+
: expr;
|
|
725
755
|
}
|
|
726
756
|
// delete obj[key] → map delete expression
|
|
727
757
|
if (Node.isDeleteExpression(node)) {
|
package/tools/dist/ir.js
CHANGED
|
@@ -79,6 +79,7 @@ export function anyExpr(e, pred) {
|
|
|
79
79
|
case "app": return e.args.some(a => anyExpr(a, pred));
|
|
80
80
|
case "field": return anyExpr(e.obj, pred);
|
|
81
81
|
case "index": return anyExpr(e.arr, pred) || anyExpr(e.idx, pred);
|
|
82
|
+
case "stringIndex": return anyExpr(e.str, pred) || anyExpr(e.idx, pred);
|
|
82
83
|
case "tupleLiteral": return e.elems.some(x => anyExpr(x, pred));
|
|
83
84
|
case "tupleProj": return anyExpr(e.obj, pred);
|
|
84
85
|
case "implies": return e.premises.some(p => anyExpr(p, pred)) || anyExpr(e.conclusion, pred);
|
package/tools/dist/lean-emit.js
CHANGED
|
@@ -432,13 +432,14 @@ function emitExpr(e, parentPrec) {
|
|
|
432
432
|
: _boolCtx && e.op === "∧" ? "&&"
|
|
433
433
|
: _boolCtx && e.op === "∨" ? "||"
|
|
434
434
|
: e.op;
|
|
435
|
-
// ↔
|
|
436
|
-
|
|
435
|
+
// Comparisons and ↔ do not chain in Lean. In particular, a Boolean
|
|
436
|
+
// postcondition `res = (s = t)` must keep its inner equality grouped.
|
|
437
|
+
const childPrec = ["↔", "=", "≠", "<", "≤", ">", "≥"].includes(e.op)
|
|
438
|
+
? prec(e.op) + 1 : prec(e.op);
|
|
437
439
|
// `-`, `/`, `%` are left-associative and non-associative, so an equal-
|
|
438
440
|
// precedence right operand must be parenthesized: `a - (b - c)` would
|
|
439
441
|
// otherwise emit as `a - b - c`, i.e. `(a - b) - c`.
|
|
440
|
-
const rightPrec =
|
|
441
|
-
: ["-", "/", "%"].includes(e.op) ? prec(e.op) + 1 : childPrec;
|
|
442
|
+
const rightPrec = ["-", "/", "%"].includes(e.op) ? prec(e.op) + 1 : childPrec;
|
|
442
443
|
const s = `${wrapOperand(e.left, childPrec)} ${op} ${wrapOperand(e.right, rightPrec)}`;
|
|
443
444
|
return (parentPrec !== undefined && prec(e.op) < parentPrec) ? `(${s})` : s;
|
|
444
445
|
}
|
|
@@ -453,7 +454,11 @@ function emitExpr(e, parentPrec) {
|
|
|
453
454
|
return parentPrec !== undefined ? `(${s})` : s;
|
|
454
455
|
}
|
|
455
456
|
case "app": {
|
|
456
|
-
|
|
457
|
+
// A bare negative literal argument (`f -7 2`) parses as subtraction in Lean.
|
|
458
|
+
const args = e.args.map(a => {
|
|
459
|
+
const s = emitExpr(a);
|
|
460
|
+
return (a.kind === "binop" || a.kind === "unop" || a.kind === "implies" || a.kind === "app" || a.kind === "methodCall" || s.startsWith("-")) ? `(${s})` : s;
|
|
461
|
+
});
|
|
457
462
|
// Datatype constructor (tagged by transform): Lean needs the qualified name
|
|
458
463
|
// `BaseType.variant`; a bare `variant` is an unknown identifier. (Dafny keeps
|
|
459
464
|
// the bare form, so its output is unaffected.)
|
|
@@ -486,7 +491,7 @@ function emitExpr(e, parentPrec) {
|
|
|
486
491
|
// `perm_append_comm`, and `Perm.count_eq` for the count-invariance payoff).
|
|
487
492
|
if (e.fn === "Perm" && args.length === 2)
|
|
488
493
|
return `(${args[0]}.toList).Perm (${args[1]}.toList)`;
|
|
489
|
-
return `${e.fn} ${args.join(" ")}
|
|
494
|
+
return args.length ? `${e.fn} ${args.join(" ")}` : e.fn;
|
|
490
495
|
}
|
|
491
496
|
case "field": {
|
|
492
497
|
// Union destructor (tagged by transform): `x.field` where x is a
|
|
@@ -518,11 +523,14 @@ function emitExpr(e, parentPrec) {
|
|
|
518
523
|
const wrap = e.expr.kind !== "var" && e.expr.kind !== "num" && e.expr.kind !== "bigint";
|
|
519
524
|
return wrap ? `(${inner}).toNat` : `${inner}.toNat`;
|
|
520
525
|
}
|
|
521
|
-
case "toInt": return `(Int.ofNat ${emitExpr(e.expr)})`;
|
|
526
|
+
case "toInt": return `(Int.ofNat (${emitExpr(e.expr)}))`;
|
|
522
527
|
case "toReal":
|
|
523
528
|
// A real value reached the Lean backend via coercion (e.g. number `/`).
|
|
524
529
|
// Same unsupported-real story as the `real` type case in tyToLean.
|
|
525
530
|
throw new Error("real arithmetic is not supported by the Lean backend (needs noncomputable ℝ / Mathlib).");
|
|
531
|
+
case "stringIndex":
|
|
532
|
+
_needsJSString = true;
|
|
533
|
+
return `(JSString.index (${emitExpr(e.str)}) (${emitExpr(e.idx)}))`;
|
|
526
534
|
case "index": {
|
|
527
535
|
const arr = emitExpr(e.arr);
|
|
528
536
|
// Parenthesize a low-precedence array expr (e.g. a function application)
|
package/tools/dist/peephole.js
CHANGED
|
@@ -152,8 +152,8 @@ const STMT_RULES = [ruleMatchOnMapGetStmt];
|
|
|
152
152
|
// ── Statement-list rules (pairs of adjacent stmts) ──────────
|
|
153
153
|
/** Pair rule: let x = m.get(k); match x { Some(v) => sb, None => nb }
|
|
154
154
|
* → if k in m { var v := m[k]; sb } else { nb }
|
|
155
|
-
* Requires x not referenced in
|
|
156
|
-
* of substituting, to preserve semantics under mutation of m. */
|
|
155
|
+
* Requires x not referenced in either arm or after the match. Bind v once
|
|
156
|
+
* instead of substituting, to preserve semantics under mutation of m. */
|
|
157
157
|
function tryLetMatchOnMapGet(s1, s2, restStmts) {
|
|
158
158
|
if (s1.kind !== "let" || s1.mutable)
|
|
159
159
|
return null;
|
|
@@ -168,7 +168,9 @@ function tryLetMatchOnMapGet(s1, s2, restStmts) {
|
|
|
168
168
|
const arms = getSomeNoneArms(s2.arms);
|
|
169
169
|
if (!arms)
|
|
170
170
|
return null;
|
|
171
|
-
if (usesNameInStmts(
|
|
171
|
+
if (usesNameInStmts(arms.someArm.body, s1.name) ||
|
|
172
|
+
usesNameInStmts(arms.noneArm.body, s1.name) ||
|
|
173
|
+
usesNameInStmts(restStmts, s1.name))
|
|
172
174
|
return null;
|
|
173
175
|
const idx = { kind: "index", arr: get.obj, idx: get.key };
|
|
174
176
|
const valTy = get.objTy.kind === "map" ? get.objTy.value : { kind: "unknown" };
|
|
@@ -246,6 +248,7 @@ function rewriteChildrenExpr(e) {
|
|
|
246
248
|
case "toInt": return { ...e, expr: r(e.expr) };
|
|
247
249
|
case "toReal": return { ...e, expr: r(e.expr) };
|
|
248
250
|
case "index": return { ...e, arr: r(e.arr), idx: r(e.idx) };
|
|
251
|
+
case "stringIndex": return { ...e, str: r(e.str), idx: r(e.idx) };
|
|
249
252
|
case "tupleLiteral": return { ...e, elems: e.elems.map(r) };
|
|
250
253
|
case "tupleProj": return { ...e, obj: r(e.obj) };
|
|
251
254
|
case "record": return { ...e, spread: e.spread ? r(e.spread) : null,
|
package/tools/dist/resolve.js
CHANGED
|
@@ -91,16 +91,21 @@ function conditionalResultTy(thenTy, elseTy) {
|
|
|
91
91
|
}
|
|
92
92
|
return ty;
|
|
93
93
|
}
|
|
94
|
-
/** Contextually type string literals as constructors. Ternary branches inherit
|
|
94
|
+
/** Contextually type string literals as string-union constructors. Ternary branches inherit
|
|
95
95
|
* the ternary's target, and an optional target contributes its payload type —
|
|
96
96
|
* the caller adds the Some wrapper only after the payload has been coerced. */
|
|
97
|
-
function coerceStr(expr, targetTy) {
|
|
97
|
+
function coerceStr(expr, targetTy, typeDecls) {
|
|
98
98
|
const payloadTy = targetTy.kind === "optional" ? targetTy.inner : targetTy;
|
|
99
|
-
if (expr.kind === "str" && payloadTy.kind === "user")
|
|
100
|
-
|
|
99
|
+
if (expr.kind === "str" && payloadTy.kind === "user") {
|
|
100
|
+
const enumTy = expandAlias(payloadTy, typeDecls);
|
|
101
|
+
// A synthesized string/array union has a string payload, not a constructor
|
|
102
|
+
// for each literal. Leave it for coerceToTargetTy to inject into its branch.
|
|
103
|
+
if (enumTy.kind === "user" && declOfDotted(typeDecls, enumTy.name)?.kind === "string-union")
|
|
104
|
+
return { ...expr, ty: payloadTy };
|
|
105
|
+
}
|
|
101
106
|
if (expr.kind === "conditional") {
|
|
102
|
-
const then_ = coerceStr(expr.then, payloadTy);
|
|
103
|
-
const else_ = coerceStr(expr.else, payloadTy);
|
|
107
|
+
const then_ = coerceStr(expr.then, payloadTy, typeDecls);
|
|
108
|
+
const else_ = coerceStr(expr.else, payloadTy, typeDecls);
|
|
104
109
|
return { ...expr, then: then_, else: else_, ty: conditionalResultTy(then_.ty, else_.ty) };
|
|
105
110
|
}
|
|
106
111
|
return expr;
|
|
@@ -128,7 +133,7 @@ function findSynthArrayUnion(name, typeDecls) {
|
|
|
128
133
|
* Returns `value` unchanged if no coercion applies (types already match,
|
|
129
134
|
* source is unknown, or no rule matches). */
|
|
130
135
|
function coerceToTargetTy(value, targetTy, typeDecls) {
|
|
131
|
-
value = coerceStr(value, targetTy);
|
|
136
|
+
value = coerceStr(value, targetTy, typeDecls);
|
|
132
137
|
// Real targets also type integer literals, including negative literals and
|
|
133
138
|
// conditional arms. Coerce optional payloads before adding Some wrappers.
|
|
134
139
|
const payloadTy = targetTy.kind === "optional" ? targetTy.inner : targetTy;
|
|
@@ -151,6 +156,8 @@ function coerceToTargetTy(value, targetTy, typeDecls) {
|
|
|
151
156
|
return wrapSome(value, targetTy);
|
|
152
157
|
}
|
|
153
158
|
if (targetTy.kind === "user") {
|
|
159
|
+
if (value.ty.kind === "user" && value.ty.name === targetTy.name)
|
|
160
|
+
return value;
|
|
154
161
|
const synth = findSynthArrayUnion(targetTy.name, typeDecls);
|
|
155
162
|
if (synth && synth.variants && synth.variants.length === 2) {
|
|
156
163
|
const arrVariant = synth.variants.find(v => v.name === "ArrayBranch");
|
|
@@ -785,6 +792,41 @@ function coerceCallArgs(args, fn, ctx) {
|
|
|
785
792
|
}
|
|
786
793
|
return args;
|
|
787
794
|
}
|
|
795
|
+
/** Join Math.min/max operands without losing bigint or depending on their order. */
|
|
796
|
+
function minMaxNumericTy(types, name) {
|
|
797
|
+
for (const ty of types) {
|
|
798
|
+
if (isBigInt(ty))
|
|
799
|
+
throw new Error(`${name} does not accept bigint operands (JavaScript throws TypeError)`);
|
|
800
|
+
if (ty.kind !== "int" && ty.kind !== "nat" && ty.kind !== "real")
|
|
801
|
+
throw new Error(`${name} requires numeric operands, got ${tyToCanonical(ty)}`);
|
|
802
|
+
}
|
|
803
|
+
return types.some(ty => ty.kind === "real") ? { kind: "real" }
|
|
804
|
+
: types.length > 0 && types.every(ty => ty.kind === "nat") ? { kind: "nat" } : { kind: "int" };
|
|
805
|
+
}
|
|
806
|
+
/** Resolve the concat tree built by extract for Math.min/max spreads. Numeric
|
|
807
|
+
* literal segments are sequences even when their elements mix int/nat/real;
|
|
808
|
+
* ordinary array inference would turn those into heterogeneous tuples.
|
|
809
|
+
* Empty literals contribute no operand type to the surrounding concat. */
|
|
810
|
+
function resolveMinMaxSequence(raw, ctx, name) {
|
|
811
|
+
if (raw.kind === "binop" && raw.op === "arrayConcat") {
|
|
812
|
+
const left = resolveMinMaxSequence(raw.left, ctx, name);
|
|
813
|
+
const right = resolveMinMaxSequence(raw.right, ctx, name);
|
|
814
|
+
const types = [...left.types, ...right.types];
|
|
815
|
+
return { expr: { kind: "binop", op: "arrayConcat", left: left.expr, right: right.expr,
|
|
816
|
+
ty: { kind: "array", elem: minMaxNumericTy(types, name) } }, types };
|
|
817
|
+
}
|
|
818
|
+
if (raw.kind === "arrayLiteral") {
|
|
819
|
+
const elems = raw.elems.map(e => resolveExpr(e, ctx));
|
|
820
|
+
const types = elems.map(e => e.ty);
|
|
821
|
+
return { expr: { kind: "arrayLiteral", elems,
|
|
822
|
+
ty: { kind: "array", elem: minMaxNumericTy(types, name) } }, types };
|
|
823
|
+
}
|
|
824
|
+
const expr = resolveExpr(raw, ctx);
|
|
825
|
+
if (expr.ty.kind !== "array")
|
|
826
|
+
throw new Error(`${name} spread requires a numeric array`);
|
|
827
|
+
minMaxNumericTy([expr.ty.elem], name);
|
|
828
|
+
return { expr, types: [expr.ty.elem] };
|
|
829
|
+
}
|
|
788
830
|
/** Infer return type for collection/string method calls. */
|
|
789
831
|
function inferMethodReturnTy(fn, args, ctx) {
|
|
790
832
|
if (fn.kind !== "field")
|
|
@@ -807,8 +849,15 @@ function inferMethodReturnTy(fn, args, ctx) {
|
|
|
807
849
|
if (fn.obj.kind === "var" && fn.obj.name === "Math") {
|
|
808
850
|
if (fn.field === "abs" && args.length === 1)
|
|
809
851
|
return args[0].ty;
|
|
810
|
-
if (
|
|
811
|
-
|
|
852
|
+
if (fn.field === "min" || fn.field === "max") {
|
|
853
|
+
if (args.length === 0)
|
|
854
|
+
throw new Error(`Math.${fn.field}() with zero arguments returns ${fn.field === "max" ? "-Infinity" : "Infinity"}, which is not supported by the numeric model`);
|
|
855
|
+
return minMaxNumericTy(args.map(a => a.ty), `Math.${fn.field}`);
|
|
856
|
+
}
|
|
857
|
+
// trunc/round are the identity on an integer, so a nat argument stays nat.
|
|
858
|
+
if ((fn.field === "trunc" || fn.field === "round") && args.length === 1 &&
|
|
859
|
+
args[0].ty.kind === "nat")
|
|
860
|
+
return { kind: "nat" };
|
|
812
861
|
if (["floor", "ceil", "round", "trunc"].includes(fn.field))
|
|
813
862
|
return { kind: "int" };
|
|
814
863
|
}
|
|
@@ -1009,8 +1058,8 @@ function resolveExprInner(e, ctx) {
|
|
|
1009
1058
|
}
|
|
1010
1059
|
let right = resolveExpr(rawRight, rightCtx);
|
|
1011
1060
|
if (e.op === "===" || e.op === "!==") {
|
|
1012
|
-
left = coerceStr(left, right.ty);
|
|
1013
|
-
right = coerceStr(right, left.ty);
|
|
1061
|
+
left = coerceStr(left, right.ty, ctx.typeDecls);
|
|
1062
|
+
right = coerceStr(right, left.ty, ctx.typeDecls);
|
|
1014
1063
|
// Spec (`//@`) comparisons are proof-only, so they can't diverge at
|
|
1015
1064
|
// runtime; only warn on executable code.
|
|
1016
1065
|
if (!ctx.inSpec && refEqHazard(left.ty, ctx.typeDecls) && refEqHazard(right.ty, ctx.typeDecls)) {
|
|
@@ -1049,6 +1098,19 @@ function resolveExprInner(e, ctx) {
|
|
|
1049
1098
|
return { kind: "unop", op: e.op, expr, ty };
|
|
1050
1099
|
}
|
|
1051
1100
|
case "call": {
|
|
1101
|
+
// Extract rewrites spread min/max calls to a single sequence argument.
|
|
1102
|
+
if (e.fn.kind === "var" && (e.fn.name === "MaxOfSeq" || e.fn.name === "MinOfSeq") && e.args.length === 1) {
|
|
1103
|
+
const name = e.fn.name === "MaxOfSeq" ? "Math.max" : "Math.min";
|
|
1104
|
+
const { expr, types } = resolveMinMaxSequence(e.args[0], ctx, name);
|
|
1105
|
+
// Integral spreads retain the existing int helper/result, including
|
|
1106
|
+
// empty literals (whose nonemptiness obligation will fail verification).
|
|
1107
|
+
const ty = minMaxNumericTy(types, name).kind === "real" ? { kind: "real" } : { kind: "int" };
|
|
1108
|
+
// Integral helpers keep their historical call classification so method
|
|
1109
|
+
// temporaries in existing proof files remain byte-identical. Real calls
|
|
1110
|
+
// use the specialized lowering that promotes their sequence segments.
|
|
1111
|
+
return { kind: "call", fn: { kind: "var", name: e.fn.name, ty: { kind: "unknown" } },
|
|
1112
|
+
args: [expr], ty, callKind: ty.kind === "real" ? "pure" : classifyCall(e.fn, ctx) };
|
|
1113
|
+
}
|
|
1052
1114
|
// perm(a, b): spec-only permutation predicate — true iff `a` and `b` are
|
|
1053
1115
|
// reorderings of each other (equal as multisets). Lowers to the `Perm`
|
|
1054
1116
|
// preamble (Dafny `multiset(a) == multiset(b)`; Lean `a.toList ~ b.toList`).
|
|
@@ -1172,6 +1234,9 @@ function resolveExprInner(e, ctx) {
|
|
|
1172
1234
|
if (obj.ty.kind === "array") {
|
|
1173
1235
|
idxTy = obj.ty.elem;
|
|
1174
1236
|
}
|
|
1237
|
+
else if (obj.ty.kind === "string") {
|
|
1238
|
+
idxTy = { kind: "string" };
|
|
1239
|
+
}
|
|
1175
1240
|
else if (obj.ty.kind === "tuple") {
|
|
1176
1241
|
// Tuple projection: the position must be a literal — a tuple has a
|
|
1177
1242
|
// distinct type per slot, so a runtime index has no single result type
|
|
@@ -1271,8 +1336,9 @@ function resolveExprInner(e, ctx) {
|
|
|
1271
1336
|
else if (step.kind === "index") {
|
|
1272
1337
|
const idx = resolveExpr(step.idx, ctx);
|
|
1273
1338
|
const idxTy = stepInTy.kind === "array" ? stepInTy.elem
|
|
1274
|
-
: stepInTy.kind === "
|
|
1275
|
-
: { kind: "
|
|
1339
|
+
: stepInTy.kind === "string" ? { kind: "string" }
|
|
1340
|
+
: stepInTy.kind === "map" ? { kind: "optional", inner: stepInTy.value }
|
|
1341
|
+
: { kind: "unknown" };
|
|
1276
1342
|
chain.push({ kind: "index", idx, ty: idxTy });
|
|
1277
1343
|
stepInTy = idxTy;
|
|
1278
1344
|
}
|
|
@@ -1317,7 +1383,10 @@ function resolveExprInner(e, ctx) {
|
|
|
1317
1383
|
}
|
|
1318
1384
|
case "record": {
|
|
1319
1385
|
const spread = e.spread ? resolveExpr(e.spread, ctx) : null;
|
|
1320
|
-
const
|
|
1386
|
+
const asserted = e.assertedTsType && expandAlias(parseTsType(e.assertedTsType), ctx.typeDecls);
|
|
1387
|
+
const assertedUnion = asserted && asserted.kind === "user" &&
|
|
1388
|
+
declOfKind(ctx.typeDecls, asserted.name, "discriminated-union");
|
|
1389
|
+
const ty = spread ? spread.ty : assertedUnion ? asserted : { kind: "unknown" };
|
|
1321
1390
|
// Record literal in map-typed context (e.g. `const M: Record<string, V> = {a: ...}`):
|
|
1322
1391
|
// attach the map type so transform/emit can produce a map literal.
|
|
1323
1392
|
if (!spread && ctx.returnTy.kind === "map") {
|
|
@@ -1487,8 +1556,8 @@ function resolveExprInner(e, ctx) {
|
|
|
1487
1556
|
elseCtx = withInAtoms(elseCtx, extractInAtomsNegated(cond));
|
|
1488
1557
|
let then_ = resolveExpr(e.then, thenCtx);
|
|
1489
1558
|
let else_ = resolveExpr(e.else, elseCtx);
|
|
1490
|
-
then_ = coerceStr(then_, else_.ty);
|
|
1491
|
-
else_ = coerceStr(else_, then_.ty);
|
|
1559
|
+
then_ = coerceStr(then_, else_.ty, ctx.typeDecls);
|
|
1560
|
+
else_ = coerceStr(else_, then_.ty, ctx.typeDecls);
|
|
1492
1561
|
const ty = conditionalResultTy(then_.ty, else_.ty);
|
|
1493
1562
|
return { kind: "conditional", cond, then: then_, else: else_, ty };
|
|
1494
1563
|
}
|
|
@@ -1586,7 +1655,7 @@ function resolveStmt(s, ctx) {
|
|
|
1586
1655
|
// one optional level when consulting returnTy.
|
|
1587
1656
|
const initCtx = (declTy.kind === "user" || declTy.kind === "array" || declTy.kind === "optional")
|
|
1588
1657
|
? { ...ctx, returnTy: declTy } : ctx;
|
|
1589
|
-
let init = coerceStr(resolveExpr(s.init, initCtx), declTy);
|
|
1658
|
+
let init = coerceStr(resolveExpr(s.init, initCtx), declTy, ctx.typeDecls);
|
|
1590
1659
|
// Under noUncheckedIndexedAccess, TS gives `const e = arr[i]` type T | undefined
|
|
1591
1660
|
// while the index expression itself resolves to T. Leave that mismatch intact:
|
|
1592
1661
|
// narrow.ts's ruleOptionalIndexBinding adds the runtime bounds guard and the
|
package/tools/dist/transform.js
CHANGED
|
@@ -4,8 +4,8 @@
|
|
|
4
4
|
* Consumes resolved types and classifications.
|
|
5
5
|
* No type lookups, no string parsing, no re-inference.
|
|
6
6
|
*/
|
|
7
|
-
import { tyEqual } from "./typedir.js";
|
|
8
|
-
import { anyExprInStmts, pWild, pCtor, pLiteral, patternBinders, patternBinds, patternCtor } from "./ir.js";
|
|
7
|
+
import { isBigInt, tyEqual } from "./typedir.js";
|
|
8
|
+
import { anyExpr, anyExprInStmts, pWild, pCtor, pLiteral, patternBinders, patternBinds, patternCtor } from "./ir.js";
|
|
9
9
|
import { parseTsType } from "./types.js";
|
|
10
10
|
import { freshName } from "./names.js";
|
|
11
11
|
import { builtinSpec } from "./builtins.js";
|
|
@@ -44,6 +44,7 @@ function mapExpr(e, f) {
|
|
|
44
44
|
case "toInt": return { ...e, expr: r(e.expr) };
|
|
45
45
|
case "toReal": return { ...e, expr: r(e.expr) };
|
|
46
46
|
case "index": return { ...e, arr: r(e.arr), idx: r(e.idx) };
|
|
47
|
+
case "stringIndex": return { ...e, str: r(e.str), idx: r(e.idx) };
|
|
47
48
|
case "tupleLiteral": return { ...e, elems: e.elems.map(r) };
|
|
48
49
|
case "tupleProj": return { ...e, obj: r(e.obj) };
|
|
49
50
|
case "record": return { ...e, spread: e.spread ? r(e.spread) : null, fields: e.fields.map(fi => ({ ...fi, value: r(fi.value) })) };
|
|
@@ -456,7 +457,44 @@ function buildNestedFieldUpdate(recv, newVal) {
|
|
|
456
457
|
return buildNestedFieldUpdate(recv.obj, upd);
|
|
457
458
|
return null;
|
|
458
459
|
}
|
|
460
|
+
/** Promote every spread segment before concatenation, preserving evaluation
|
|
461
|
+
* order. A seq<int> needs elementwise conversion; it cannot be cast to real. */
|
|
462
|
+
function lowerMinMaxSequence(e, real, binds) {
|
|
463
|
+
if (e.kind === "binop" && e.op === "arrayConcat") {
|
|
464
|
+
return { kind: "binop", op: "arrayConcat",
|
|
465
|
+
left: lowerMinMaxSequence(e.left, real, binds),
|
|
466
|
+
right: lowerMinMaxSequence(e.right, real, binds) };
|
|
467
|
+
}
|
|
468
|
+
if (e.kind === "arrayLiteral") {
|
|
469
|
+
return { kind: "arrayLiteral", elems: e.elems.map(el => {
|
|
470
|
+
const value = lowerExpr(el, binds);
|
|
471
|
+
if (real && isIntegral(el.ty))
|
|
472
|
+
return { kind: "toReal", expr: value };
|
|
473
|
+
return _opts.backend === "lean" && isNat(el.ty) ? { kind: "toInt", expr: value } : value;
|
|
474
|
+
}) };
|
|
475
|
+
}
|
|
476
|
+
const value = lowerExpr(e, binds);
|
|
477
|
+
if (_opts.backend === "lean" && e.ty.kind === "array" && isNat(e.ty.elem)) {
|
|
478
|
+
return { kind: "app", fn: "Array.map", args: [{ kind: "var", name: "Int.ofNat" }, value] };
|
|
479
|
+
}
|
|
480
|
+
return real && e.ty.kind === "array" && isIntegral(e.ty.elem)
|
|
481
|
+
? { kind: "app", fn: "SeqIntToReal", args: [value] } : value;
|
|
482
|
+
}
|
|
459
483
|
function lowerExpr(e, binds) {
|
|
484
|
+
// Lean spreads are checked Option operations. Lift even a syntactically pure
|
|
485
|
+
// call so total correctness requires the combined array to be nonempty.
|
|
486
|
+
if (_opts.backend === "lean" && e.kind === "call" && e.fn.kind === "var" &&
|
|
487
|
+
(e.fn.name === "MaxOfSeq" || e.fn.name === "MinOfSeq") && e.args.length === 1) {
|
|
488
|
+
const name = binds ? freshName(`_t${_liftCounter++}`) : null;
|
|
489
|
+
const value = { kind: "app",
|
|
490
|
+
fn: e.fn.name === "MaxOfSeq" ? "LemmaScript.maxOfArray" : "LemmaScript.minOfArray",
|
|
491
|
+
args: [lowerMinMaxSequence(e.args[0], e.ty.kind === "real", binds)] };
|
|
492
|
+
if (binds && name) {
|
|
493
|
+
binds.push({ kind: "let-bind", name, value });
|
|
494
|
+
return { kind: "var", name };
|
|
495
|
+
}
|
|
496
|
+
return value;
|
|
497
|
+
}
|
|
460
498
|
// Monadic lifting: extract embedded method calls to let-binds.
|
|
461
499
|
// `callKind: "method"` means a global var-fn call (classifyCall returns
|
|
462
500
|
// "method" only for `fn.kind === "var"`). Receiver method calls have
|
|
@@ -813,6 +851,9 @@ function lowerExpr(e, binds) {
|
|
|
813
851
|
}
|
|
814
852
|
return { kind: "field", obj: transformExpr(e.obj), field: e.field, datatypeField: isRecordType(e.obj.ty) };
|
|
815
853
|
case "index": {
|
|
854
|
+
if (e.obj.ty.kind === "string") {
|
|
855
|
+
return { kind: "stringIndex", str: lowerExpr(e.obj, binds), idx: lowerExpr(e.idx, binds) };
|
|
856
|
+
}
|
|
816
857
|
const idx = transformExpr(e.idx);
|
|
817
858
|
if (e.obj.ty.kind === "tuple") {
|
|
818
859
|
// resolve guarantees a numeric-literal index here; project at that slot.
|
|
@@ -829,6 +870,12 @@ function lowerExpr(e, binds) {
|
|
|
829
870
|
return { kind: "index", arr: transformExpr(e.obj), idx: wrappedIdx };
|
|
830
871
|
}
|
|
831
872
|
case "call": {
|
|
873
|
+
if (_opts.backend === "dafny" && e.fn.kind === "var" &&
|
|
874
|
+
(e.fn.name === "MaxOfSeq" || e.fn.name === "MinOfSeq") && e.args.length === 1) {
|
|
875
|
+
const real = e.ty.kind === "real";
|
|
876
|
+
return { kind: "app", fn: real ? `${e.fn.name}Real` : e.fn.name,
|
|
877
|
+
args: [lowerMinMaxSequence(e.args[0], real, binds)] };
|
|
878
|
+
}
|
|
832
879
|
// Array.isArray(x) on a synth array-union (discriminant "__isArray__")
|
|
833
880
|
// → constructor predicate `x.ArrayBranch?`. Used in spec ensures and
|
|
834
881
|
// anywhere `Array.isArray` escapes the narrowing rule (narrow rewrites
|
|
@@ -858,8 +905,20 @@ function lowerExpr(e, binds) {
|
|
|
858
905
|
// model, so the JS bound -(2^53 - 1) <= n <= 2^53 - 1 must be stated.
|
|
859
906
|
if (e.fn.kind === "field" && e.fn.obj.kind === "var" && e.fn.obj.name === "Number" &&
|
|
860
907
|
e.fn.field === "isSafeInteger" && e.args.length === 1 && isIntegral(e.args[0].ty)) {
|
|
861
|
-
if (e.args[0].ty
|
|
862
|
-
|
|
908
|
+
if (isBigInt(e.args[0].ty)) {
|
|
909
|
+
// The result is false, but JS still evaluates the argument. Keep
|
|
910
|
+
// lifted method calls and pure expressions' proof obligations.
|
|
911
|
+
const value = lowerExpr(e.args[0], binds);
|
|
912
|
+
const result = { kind: "bool", value: false };
|
|
913
|
+
if (value.kind === "var" || value.kind === "bigint")
|
|
914
|
+
return result;
|
|
915
|
+
const name = freshName("_safeIntegerArg");
|
|
916
|
+
if (binds) {
|
|
917
|
+
binds.push({ kind: "let", name, type: e.args[0].ty, mutable: false, value });
|
|
918
|
+
return result;
|
|
919
|
+
}
|
|
920
|
+
return { kind: "let", name, type: e.args[0].ty, value, body: result };
|
|
921
|
+
}
|
|
863
922
|
const n = lowerExpr(e.args[0], binds);
|
|
864
923
|
const max = 9007199254740991;
|
|
865
924
|
return {
|
|
@@ -868,19 +927,34 @@ function lowerExpr(e, binds) {
|
|
|
868
927
|
right: { kind: "binop", op: "≤", left: n, right: { kind: "num", value: max } },
|
|
869
928
|
};
|
|
870
929
|
}
|
|
930
|
+
// Number.isSafeInteger(x) on a real: check integrality and safe range via
|
|
931
|
+
// a preamble predicate.
|
|
932
|
+
if (e.fn.kind === "field" && e.fn.obj.kind === "var" && e.fn.obj.name === "Number" &&
|
|
933
|
+
e.fn.field === "isSafeInteger" && e.args.length === 1 && e.args[0].ty.kind === "real") {
|
|
934
|
+
return { kind: "app", fn: "IsSafeIntegerReal", args: [lowerExpr(e.args[0], binds)] };
|
|
935
|
+
}
|
|
871
936
|
// Math.abs/min/max preserve the resolved numeric type. Mixed operands
|
|
872
937
|
// need explicit int/nat→real coercions, just like real binary operations.
|
|
873
938
|
if (e.fn.kind === "field" && e.fn.obj.kind === "var" && e.fn.obj.name === "Math") {
|
|
939
|
+
const minMax = (e.fn.field === "min" || e.fn.field === "max") && e.args.length >= 1;
|
|
874
940
|
const fn = e.fn.field === "abs" && e.args.length === 1 ? "MathAbs"
|
|
875
|
-
: e.fn.field === "min"
|
|
876
|
-
: e.fn.field === "max" && e.args.length === 2 ? "MathMax" : null;
|
|
941
|
+
: minMax ? (e.fn.field === "min" ? "MathMin" : "MathMax") : null;
|
|
877
942
|
if (fn) {
|
|
878
943
|
const real = e.ty.kind === "real";
|
|
879
944
|
const args = e.args.map((arg) => {
|
|
880
945
|
const lowered = lowerExpr(arg, binds);
|
|
881
|
-
|
|
946
|
+
if (real && isIntegral(arg.ty))
|
|
947
|
+
return { kind: "toReal", expr: lowered };
|
|
948
|
+
return _opts.backend === "lean" && minMax && e.ty.kind === "int" && isNat(arg.ty)
|
|
949
|
+
? { kind: "toInt", expr: lowered } : lowered;
|
|
882
950
|
});
|
|
883
|
-
|
|
951
|
+
const helper = real ? `${fn}Real` : _opts.backend === "lean" && minMax
|
|
952
|
+
? `${e.fn.field === "min" ? "Min" : "Max"}.${e.fn.field}` : fn;
|
|
953
|
+
// Unary min/max is identity. Fold positional arguments through the
|
|
954
|
+
// binary helpers so scalar bounds need no sequence/index proofs.
|
|
955
|
+
return minMax
|
|
956
|
+
? args.slice(1).reduce((acc, arg) => ({ kind: "app", fn: helper, args: [acc, arg] }), args[0])
|
|
957
|
+
: { kind: "app", fn: helper, args };
|
|
884
958
|
}
|
|
885
959
|
}
|
|
886
960
|
// Math.ceil(x): CeilReal on real args, identity on int
|
|
@@ -909,6 +983,38 @@ function lowerExpr(e, binds) {
|
|
|
909
983
|
return { kind: "app", fn: "FloorReal", args: [lowerExpr(arg, binds)] };
|
|
910
984
|
return lowerExpr(arg, binds);
|
|
911
985
|
}
|
|
986
|
+
// Math.trunc(x) / Math.round(x):
|
|
987
|
+
// - trunc(a / b) on integral operands → JSTruncDiv (Lean: Int.tdiv),
|
|
988
|
+
// checked first for the same reason as the floor case above
|
|
989
|
+
// - integral arg → identity
|
|
990
|
+
// - real arg (Dafny only) → TruncReal(x) / FloorReal(x + 0.5); JS
|
|
991
|
+
// rounds halfway ties toward +Infinity
|
|
992
|
+
// A bigint argument (a JS TypeError) would otherwise lower to the
|
|
993
|
+
// identity, and a Lean real argument has no lowering, so both are
|
|
994
|
+
// rejected. Other calls fall through to the unsupported-call error.
|
|
995
|
+
if (e.fn.kind === "field" && (e.fn.field === "trunc" || e.fn.field === "round") &&
|
|
996
|
+
e.fn.obj.kind === "var" && e.fn.obj.name === "Math" && e.args.length === 1 &&
|
|
997
|
+
(isIntegral(e.args[0].ty) || e.args[0].ty.kind === "real")) {
|
|
998
|
+
const name = `Math.${e.fn.field}`;
|
|
999
|
+
const arg = e.args[0];
|
|
1000
|
+
if (isBigInt(arg.ty))
|
|
1001
|
+
throw new Error(`${name} does not accept a bigint argument (JavaScript throws TypeError)`);
|
|
1002
|
+
if (e.fn.field === "trunc" && arg.kind === "binop" && arg.op === "/" &&
|
|
1003
|
+
isIntegral(arg.left.ty) && isIntegral(arg.right.ty)) {
|
|
1004
|
+
return { kind: "app", fn: "JSTruncDiv", args: [lowerExpr(arg.left, binds), lowerExpr(arg.right, binds)] };
|
|
1005
|
+
}
|
|
1006
|
+
if (isIntegral(arg.ty))
|
|
1007
|
+
return lowerExpr(arg, binds);
|
|
1008
|
+
if (_opts.backend !== "dafny")
|
|
1009
|
+
throw new Error("real arithmetic is not supported by the Lean backend (needs noncomputable ℝ / Mathlib).");
|
|
1010
|
+
const x = lowerExpr(arg, binds);
|
|
1011
|
+
if (e.fn.field === "trunc")
|
|
1012
|
+
return { kind: "app", fn: "TruncReal", args: [x] };
|
|
1013
|
+
return {
|
|
1014
|
+
kind: "app", fn: "FloorReal",
|
|
1015
|
+
args: [{ kind: "binop", op: "+", left: x, right: { kind: "num", value: 0.5 } }],
|
|
1016
|
+
};
|
|
1017
|
+
}
|
|
912
1018
|
// Method call: receiver.method(args) → methodCall node
|
|
913
1019
|
if (e.fn.kind === "field") {
|
|
914
1020
|
const recv = lowerExpr(e.fn.obj, binds);
|
|
@@ -2548,6 +2654,30 @@ export function transformModule(mod, specImport, moduleBaseOverride) {
|
|
|
2548
2654
|
});
|
|
2549
2655
|
}
|
|
2550
2656
|
}
|
|
2657
|
+
if (_opts.backend === "lean") {
|
|
2658
|
+
// A pure mirror would erase the failure on an empty spread. Keep these
|
|
2659
|
+
// functions and their transitive callers as methods, where WP checks it.
|
|
2660
|
+
const checked = new Set(["LemmaScript.maxOfArray", "LemmaScript.minOfArray"]);
|
|
2661
|
+
let changed = true;
|
|
2662
|
+
while (changed) {
|
|
2663
|
+
changed = false;
|
|
2664
|
+
for (const def of pureDefs) {
|
|
2665
|
+
if (!checked.has(def.name) && anyExpr(def.body, e => {
|
|
2666
|
+
const name = e.kind === "app" ? e.fn : e.kind === "var" ? e.name : "";
|
|
2667
|
+
return checked.has(name.replace(/^Pure\./, ""));
|
|
2668
|
+
})) {
|
|
2669
|
+
checked.add(def.name);
|
|
2670
|
+
changed = true;
|
|
2671
|
+
}
|
|
2672
|
+
}
|
|
2673
|
+
}
|
|
2674
|
+
for (let i = pureDefs.length - 1; i >= 0; i--) {
|
|
2675
|
+
if (checked.has(pureDefs[i].name)) {
|
|
2676
|
+
_pureDefNames.delete(pureDefs[i].name);
|
|
2677
|
+
pureDefs.splice(i, 1);
|
|
2678
|
+
}
|
|
2679
|
+
}
|
|
2680
|
+
}
|
|
2551
2681
|
const base = mod.file.split("/").pop()?.replace(/\.ts$/, "") ?? "module";
|
|
2552
2682
|
// Lean module base — overridable via `//@ lean-module` (see lsc.ts). Only the
|
|
2553
2683
|
// def→types import below reads it; Dafny never passes an override.
|
package/tools/dist/types.js
CHANGED
|
@@ -156,9 +156,9 @@ function tyFromTypeNode(tn) {
|
|
|
156
156
|
return { kind: "int" };
|
|
157
157
|
if ((name === "Array" || name === "ReadonlyArray") && args.length === 1)
|
|
158
158
|
return { kind: "array", elem: tyFromTypeNode(args[0]) };
|
|
159
|
-
if (name === "Set" && args.length === 1)
|
|
159
|
+
if ((name === "Set" || name === "ReadonlySet") && args.length === 1)
|
|
160
160
|
return { kind: "set", elem: tyFromTypeNode(args[0]) };
|
|
161
|
-
if ((name === "Map" || name === "Record") && args.length === 2) {
|
|
161
|
+
if ((name === "Map" || name === "ReadonlyMap" || name === "Record") && args.length === 2) {
|
|
162
162
|
return { kind: "map", key: tyFromTypeNode(args[0]), value: tyFromTypeNode(args[1]) };
|
|
163
163
|
}
|
|
164
164
|
// User-named type: include generic args in the spelled name so callers
|