lemmascript 0.6.8 → 0.6.10

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 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
- Each example and case study is verified in Lean 4 and/or Dafny from the same annotated TypeScript source.
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,6 +1,6 @@
1
1
  {
2
2
  "name": "lemmascript",
3
- "version": "0.6.8",
3
+ "version": "0.6.10",
4
4
  "description": "A verification toolchain for TypeScript — generates Lean 4 or Dafny from annotated TS",
5
5
  "type": "module",
6
6
  "engines": {
@@ -43,22 +43,22 @@ export const BUILTINS = {
43
43
  "array.sort": { ret: self, pure: false,
44
44
  hof: { shape: "comparator" } },
45
45
  "array.filter": { ret: self, pure: false,
46
- hof: { shape: "unary" } },
46
+ hof: { shape: "element" } },
47
47
  "array.every": { ret: BOOL, pure: false,
48
- hof: { shape: "unary" } },
48
+ hof: { shape: "element" } },
49
49
  "array.some": { ret: BOOL, pure: false,
50
- hof: { shape: "unary" } },
50
+ hof: { shape: "element" } },
51
51
  "array.reduce": { pure: false,
52
52
  hof: { shape: "reduce" },
53
53
  ret: (_objTy, args) => args.length === 2 ? args[1].ty : UNKNOWN },
54
54
  "array.find": { ret: optElem, pure: false,
55
- hof: { shape: "unary" } },
55
+ hof: { shape: "element" } },
56
56
  "array.findLast": { ret: optElem, pure: false,
57
- hof: { shape: "unary" } },
57
+ hof: { shape: "element" } },
58
58
  "array.findIndex": { ret: INT, pure: false,
59
- hof: { shape: "unary" } },
59
+ hof: { shape: "element" } },
60
60
  "array.findLastIndex": { ret: INT,
61
- pure: false, hof: { shape: "unary" } },
61
+ pure: false, hof: { shape: "element" } },
62
62
  "array.flat": { pure: true,
63
63
  ret: (objTy) => objTy.kind === "array" && objTy.elem.kind === "array"
64
64
  ? { kind: "array", elem: objTy.elem.elem } : UNKNOWN },
@@ -67,7 +67,7 @@ export const BUILTINS = {
67
67
  ret: (objTy) => objTy.kind === "array" && objTy.elem.kind === "string"
68
68
  ? STRING() : UNKNOWN },
69
69
  "array.map": { pure: false,
70
- hof: { shape: "unary" },
70
+ hof: { shape: "element" },
71
71
  // Prefer the lambda's declared return type (handles multi-statement bodies
72
72
  // where body[0] is an `if`, not a `return`); fall back to the body's return.
73
73
  ret: (_objTy, args) => {
@@ -123,3 +123,17 @@ export function recognizeBuiltin(objTy, method) {
123
123
  export function builtinSpec(id) {
124
124
  return BUILTINS[id];
125
125
  }
126
+ /** The actual arguments passed by JavaScript, independently of which ones a
127
+ * callback declares or observes. Array indices are JS numbers (modeled ints). */
128
+ export function callbackArgumentTypes(spec, receiver, initial) {
129
+ if (!spec.hof || receiver.kind !== "array")
130
+ return undefined;
131
+ switch (spec.hof.shape) {
132
+ case "element": return [receiver.elem, { kind: "int" }, receiver];
133
+ case "comparator": return [receiver.elem, receiver.elem];
134
+ case "reduce": return initial ? [initial, receiver.elem, { kind: "int" }, receiver] : undefined;
135
+ }
136
+ }
137
+ export function callbackBaseArity(shape) {
138
+ return shape === "element" ? 1 : 2;
139
+ }
@@ -0,0 +1,67 @@
1
+ import { pCtor, usesNameInStmts } from "./ir.js";
2
+ import { callbackBaseArity } from "./builtins.js";
3
+ import { freshName } from "./names.js";
4
+ const INT = { kind: "int" };
5
+ const INDICES = { kind: "array", elem: INT };
6
+ const variable = (name) => ({ kind: "var", name });
7
+ export function lowerIndexedCallback(receiver, receiverTy, method, args, shape, monadic, id) {
8
+ const callback = args[0];
9
+ if (receiverTy.kind !== "array" || callback?.kind !== "lambda" ||
10
+ callback.params.length <= callbackBaseArity(shape))
11
+ return null;
12
+ const sourceName = freshName(`_callbackSource${id}`);
13
+ const indexName = freshName(`_callbackIndex${id}`);
14
+ const accName = freshName(`_callbackAcc${id}`);
15
+ const source = variable(sourceName), index = variable(indexName);
16
+ const element = { kind: "index", arr: source, idx: { kind: "toNat", expr: index } };
17
+ const values = shape === "reduce" ? [variable(accName), element, index, source] : [element, index, source];
18
+ const elementPosition = shape === "reduce" ? 1 : 0;
19
+ if (receiverTy.elem.kind === "nat" && callback.params[elementPosition].type.kind === "int") {
20
+ values[elementPosition] = { kind: "toInt", expr: element };
21
+ }
22
+ const bindings = callback.params.flatMap((p, i) => usesNameInStmts(callback.body, p.name)
23
+ ? [{ kind: "let", name: p.name, type: p.type, mutable: false, value: values[i] }]
24
+ : []);
25
+ // Keep the body expression-shaped when possible, as required by Dafny's
26
+ // collection operations. These bindings evaluate only already-bound values.
27
+ let body = callback.body;
28
+ if (body.length === 1 && body[0].kind === "return") {
29
+ let value = body[0].value;
30
+ for (const s of [...bindings].reverse()) {
31
+ if (s.kind === "let")
32
+ value = { kind: "let", name: s.name, type: s.type, value: s.value, body: value };
33
+ }
34
+ // Backend collection helpers take total callbacks. Extend the callback
35
+ // outside its actual index domain without evaluating its body there.
36
+ // map and some inline the body under membership/bounds instead.
37
+ if (method !== "map" && method !== "some") {
38
+ const valid = { kind: "binop", op: "∧",
39
+ left: { kind: "binop", op: "≤", left: { kind: "num", value: 0 }, right: index },
40
+ right: { kind: "binop", op: "<", left: index, right: { kind: "field", obj: source, field: "size" } } };
41
+ value = { kind: "if", cond: valid, then: value,
42
+ else: shape === "reduce" ? variable(accName) : { kind: "bool", value: false } };
43
+ }
44
+ body = [{ kind: "return", value }];
45
+ }
46
+ else
47
+ body = [...bindings, ...body];
48
+ const adapted = { kind: "lambda", body, typedParams: true, params: shape === "reduce"
49
+ ? [{ name: accName, type: callback.params[0].type }, { name: indexName, type: INT }]
50
+ : [{ name: indexName, type: INT }] };
51
+ const positions = { kind: "arrayRange", length: { kind: "field", obj: source, field: "size" } };
52
+ let result = { kind: "methodCall", obj: positions, objTy: INDICES,
53
+ method, args: [adapted, ...args.slice(1)], monadic };
54
+ // Selection methods return elements; their index-domain versions return
55
+ // positions. Translate the result back without changing order or witnesses.
56
+ if (method === "filter") {
57
+ result = { kind: "methodCall", obj: result, objTy: INDICES, method: "map", monadic: false,
58
+ args: [{ kind: "lambda", typedParams: true, params: [{ name: indexName, type: INT }], body: [{ kind: "return", value: element }] }] };
59
+ }
60
+ else if (method === "find" || method === "findLast") {
61
+ result = { kind: "match", scrutinee: result, arms: [
62
+ { pattern: pCtor("some", indexName), body: { kind: "constructor", name: "some", args: [element] } },
63
+ { pattern: pCtor("none"), body: { kind: "constructor", name: "none", args: [] } },
64
+ ] };
65
+ }
66
+ return { kind: "let", name: sourceName, type: receiverTy, value: receiver, body: result };
67
+ }
@@ -69,9 +69,11 @@ export function bindPresentFact(f, ctx) {
69
69
  }
70
70
  /** Detect optional checks: `e !== undefined`, `e === undefined`, `!e`, or a
71
71
  * bare optional `e` — for a pure-access-path optional-typed `e`. `!e` and
72
- * bare `e` are truthiness forms. Following TS, only pure access paths
73
- * narrow; complex scrutinees return null. */
72
+ * bare `e` are truthiness forms. `!!c` is the same check as `c`. Following
73
+ * TS, only pure access paths narrow; complex scrutinees return null. */
74
74
  export function presentFact(cond) {
75
+ if (cond.kind === "unop" && cond.op === "!" && cond.expr.kind === "unop" && cond.expr.op === "!")
76
+ return presentFact(cond.expr.expr);
75
77
  // `!e` where e is optional — a truthiness form: false iff e is absent OR its
76
78
  // inner value is itself falsy (so `Some(0)`/`Some("")` count as falsy too).
77
79
  if (cond.kind === "unop" && cond.op === "!" && cond.expr.ty.kind === "optional") {
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Dafny backend commands: gen, check, regen.
3
3
  */
4
- import { existsSync, readFileSync, writeFileSync, copyFileSync, unlinkSync } from "fs";
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";
@@ -187,25 +187,52 @@ export function dafnyRegen(genPath, dfyPath, basePath, text, dir, timeLimit, ext
187
187
  const anchor = existsSync(basePath) ? readFileSync(basePath, "utf-8") : oldGen;
188
188
  // 5. If gen changed, three-way merge
189
189
  if (text !== anchor) {
190
- const savedDfy = readFileSync(dfyPath, "utf-8");
191
190
  if (!existsSync(basePath))
192
191
  writeFileSync(basePath, anchor);
193
192
  const mergedPath = dfyPath + ".merged";
194
193
  console.log("Gen changed. Three-way merging...");
194
+ // -p prints the merge instead of writing it, so the proof file changes
195
+ // only after a clean merge.
196
+ const merge = (flags) => execFileSync("git", ["merge-file", "-p", ...flags, "--", dfyPath, basePath, genPath], { encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: Infinity });
197
+ let merged;
195
198
  try {
196
- execFileSync("git", ["merge-file", dfyPath, basePath, genPath], { stdio: "pipe" });
197
- console.log(`Merged: ${path.basename(dfyPath)}`);
199
+ try {
200
+ // Match the additions-only check: the default diff can misalign
201
+ // unchanged generated lines after a large inserted proof block.
202
+ merged = merge(["--diff-algorithm=minimal"]);
203
+ }
204
+ catch (e) {
205
+ // The other arguments are fixed, so a usage error (129) means this
206
+ // Git predates the option (2.44).
207
+ if (e?.status !== 129)
208
+ throw e;
209
+ console.warn("WARNING: this Git does not support git merge-file --diff-algorithm; retrying with the default algorithm. " +
210
+ "Upgrade to Git 2.44 or later to avoid false conflicts after large proof additions.");
211
+ merged = merge([]);
212
+ }
198
213
  }
199
214
  catch (e) {
200
- if (e.status > 0) {
201
- copyFileSync(dfyPath, mergedPath);
202
- writeFileSync(dfyPath, savedDfy);
215
+ // Git returns a conflict count capped at 127. Usage errors, fatal
216
+ // errors and interrupted/failed processes are not merge conflicts.
217
+ if (e?.status >= 1 && e.status <= 127) {
218
+ writeFileSync(mergedPath, e.stdout);
203
219
  console.error(`CONFLICT: ${path.basename(dfyPath)} — merge had conflicts, dfy restored. See ${path.basename(mergedPath)}`);
204
220
  log?.finish({ stage: "conflict", exit: 1, dfyPath });
205
- process.exit(1);
206
221
  }
207
- throw e;
222
+ else {
223
+ const reason = e?.code === "ENOENT" ? " (git not found on PATH)"
224
+ : e?.code != null ? ` (${e.code})`
225
+ : e?.signal != null ? ` (signal ${e.signal})`
226
+ : typeof e?.status === "number" ? ` (git exited ${e.status})` : "";
227
+ const detail = typeof e?.stderr === "string" ? e.stderr.trim() : "";
228
+ console.error(`ERROR: could not run \`git merge-file\` for ${path.basename(dfyPath)}${reason}; dfy restored` +
229
+ `${detail ? `: ${detail}` : "."}`);
230
+ log?.discard();
231
+ }
232
+ process.exit(1);
208
233
  }
234
+ writeFileSync(dfyPath, merged);
235
+ console.log(`Merged: ${path.basename(dfyPath)}`);
209
236
  }
210
237
  // 6. Check gen invariant (unconditional)
211
238
  if (!dafnyCheckDiff(genPath, dfyPath, log)) {
@@ -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. */
@@ -216,6 +218,21 @@ const OP_MAP = {
216
218
  "∧": "&&", "∨": "||", "¬": "!", "↔": "<==>",
217
219
  "arrayConcat": "+",
218
220
  };
221
+ /** Escape controls and line separators while preserving printable Unicode. */
222
+ function escapeDafnyScalarString(value) {
223
+ return value.replace(/["\\\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, char => {
224
+ switch (char) {
225
+ case '"': return '\\"';
226
+ case "\\": return "\\\\";
227
+ case "\0": return "\\0";
228
+ case "\n": return "\\n";
229
+ case "\r": return "\\r";
230
+ case "\t": return "\\t";
231
+ // Dafny has no short escapes for controls such as backspace or form feed.
232
+ default: return `\\U{${char.charCodeAt(0).toString(16).toUpperCase().padStart(4, "0")}}`;
233
+ }
234
+ });
235
+ }
219
236
  /** Render a JavaScript string without losing its UTF-16 representation.
220
237
  *
221
238
  * JavaScript iteration by index exposes UTF-16 code units, including unpaired
@@ -273,11 +290,9 @@ function emitExpr(e) {
273
290
  case "bigint": return e.value;
274
291
  case "bool": return e.value ? "true" : "false";
275
292
  case "str":
276
- // Under the default profile the literal is written exactly as before;
277
- // only the UTF-16 profile needs code-unit escapes (DESIGN_STRINGS.md §3).
278
293
  return isUtf16()
279
294
  ? `"${escapeDafnyUTF16String(e.value)}"`
280
- : `"${e.value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n')}"`;
295
+ : `"${escapeDafnyScalarString(e.value)}"`;
281
296
  case "constructor": {
282
297
  // Option constructors (Some/None) may appear in inferred positions
283
298
  // (e.g. lambda result) without an explicit `optional<T>` in any
@@ -293,6 +308,9 @@ function emitExpr(e) {
293
308
  if (e.elems.length === 0)
294
309
  return `[]`;
295
310
  return `[${e.elems.map(emitExpr).join(", ")}]`;
311
+ case "arrayRange":
312
+ needPreamble("CallbackIndices");
313
+ return `CallbackIndices(${emitExpr(e.length)})`;
296
314
  case "tupleLiteral": return `(${e.elems.map(emitExpr).join(", ")})`;
297
315
  case "tupleProj": return `${emitExpr(e.obj)}.${e.index}`;
298
316
  case "emptyMap": return `map[]`;
@@ -333,17 +351,15 @@ function emitExpr(e) {
333
351
  // the copy is just the seq itself (the idiom for "copy then mutate").
334
352
  if (e.method === "slice" && args.length === 0)
335
353
  return obj;
336
- if (e.method === "slice" && args.length === 1)
337
- return `${obj}[${args[0]}..]`;
338
- if (e.method === "slice" && args.length === 2) {
354
+ if (e.method === "slice" && (args.length === 1 || args.length === 2)) {
339
355
  // JS slice clamps both bounds; Dafny requires `0 <= lo <= hi <= |s|`.
340
356
  // Direct slice is default (matches existing case studies that wrote
341
357
  // bounded calls). Files needing JS clamping opt in via `//@ safe-slice`.
342
358
  if (_useSafeSlice) {
343
359
  needPreamble("SafeSlice");
344
- return `SafeSlice(${obj}, ${args[0]}, ${args[1]})`;
360
+ return `SafeSlice(${obj}, ${args[0]}, ${args[1] ?? `|${obj}|`})`;
345
361
  }
346
- return `${obj}[${args[0]}..${args[1]}]`;
362
+ return args.length === 1 ? `${obj}[${args[0]}..]` : `${obj}[${args[0]}..${args[1]}]`;
347
363
  }
348
364
  if (e.method === "map") {
349
365
  // Always a seq comprehension: Seq.Map would hide the element access
@@ -355,8 +371,9 @@ function emitExpr(e) {
355
371
  // comprehension mentions it three times, and splicing would make
356
372
  // any closure literal inside it (e.g. a Filter predicate) three
357
373
  // distinct closures, unprovably equal through an opaque callee.
358
- // Name freshness is a local IR-level check until a backend name
359
- // allocator exists.
374
+ // Name freshness is a local IR-level check (`usesName`), not the
375
+ // Dafny-namespace allocator (`escapeGeneratedName`): a user identifier
376
+ // that *escapes* to `i_map`/`s_map` (e.g. `_map`) is still captured.
360
377
  const lam = e.args[0];
361
378
  const fresh = (base, taken) => {
362
379
  let name = base;
@@ -367,6 +384,17 @@ function emitExpr(e) {
367
384
  const taken = (n) => usesName(e.obj, n) || usesName(lam, n) ||
368
385
  (lam.kind === "lambda" && (lam.params.some(pp => pp.name === n) ||
369
386
  usesNameInStmts(lam.body, n)));
387
+ // Mapping over positions (an indexed callback): the comprehension
388
+ // index is the position itself, so no CallbackIndices sequence is
389
+ // needed. Keep the callback's declared type so the binding is `int`.
390
+ if (e.obj.kind === "arrayRange" && lam.kind === "lambda" && lam.params.length === 1 &&
391
+ lam.body.length === 1 && lam.body[0].kind === "return") {
392
+ const n = emitExpr(e.obj.length);
393
+ const idx = fresh("i_map", taken);
394
+ const p = lam.params[0];
395
+ const ty = lam.typedParams ? tyToDafny(p.type) : "int";
396
+ return `seq(${n}, ${idx} requires 0 <= ${idx} < ${n} => var ${escapeName(p.name)}: ${ty} := ${idx}; ${emitExpr(lam.body[0].value)})`;
397
+ }
370
398
  const bind = e.obj.kind !== "var";
371
399
  const s = bind ? fresh("s_map", taken) : obj;
372
400
  const idx = fresh("i_map", n => taken(n) || n === s);
@@ -460,6 +488,14 @@ function emitExpr(e) {
460
488
  }
461
489
  return `StringIndexOf(${obj}, ${args[0]})`;
462
490
  }
491
+ if (e.method === "lastIndexOf") {
492
+ needPreamble("StringLastIndexOf");
493
+ if (args.length === 2) {
494
+ needPreamble("StringSearchPosition");
495
+ return `StringLastIndexOfFrom(${obj}, ${args[0]}, StringSearchPosition(${obj}, ${args[1]}))`;
496
+ }
497
+ return `StringLastIndexOf(${obj}, ${args[0]})`;
498
+ }
463
499
  if (e.method === "split") {
464
500
  needPreamble("StringSplit");
465
501
  return `StringSplit(${obj}, ${args[0]})`;
@@ -685,6 +721,12 @@ function emitExpr(e) {
685
721
  needPreamble("MathMin");
686
722
  if (e.fn === "MathMax")
687
723
  needPreamble("MathMax");
724
+ if (e.fn === "MathAbsReal")
725
+ needPreamble("MathAbsReal");
726
+ if (e.fn === "MathMinReal")
727
+ needPreamble("MathMinReal");
728
+ if (e.fn === "MathMaxReal")
729
+ needPreamble("MathMaxReal");
688
730
  if (e.fn === "MaxOfSeq") {
689
731
  needPreamble("MathMax");
690
732
  needPreamble("MaxOfSeq");
@@ -733,6 +775,7 @@ function emitExpr(e) {
733
775
  case "toNat":
734
776
  // Dafny doesn't need toNat — just emit the inner expression
735
777
  return emitExpr(e.expr);
778
+ case "toInt": return emitExpr(e.expr);
736
779
  case "toReal":
737
780
  return `(${emitExpr(e.expr)} as real)`;
738
781
  case "index": {
@@ -809,7 +852,7 @@ function emitExpr(e) {
809
852
  }
810
853
  case "forall": return emitQuantifier(e, "forall");
811
854
  case "exists": return emitQuantifier(e, "exists");
812
- case "let": return `(var ${escapeName(e.name)} := ${emitExpr(e.value)}; ${emitExpr(e.body)})`;
855
+ case "let": return `(var ${escapeName(e.name)}${e.type ? `: ${tyToDafny(e.type)}` : ""} := ${emitExpr(e.value)}; ${emitExpr(e.body)})`;
813
856
  case "havoc": return "*";
814
857
  // No Dafny producer: the only `default` source is the Lean return-in-loop
815
858
  // rewrite, which never runs on the Dafny path (native in-loop returns).
@@ -833,7 +876,7 @@ function emitPureExpr(e, indent) {
833
876
  return lines.join("\n");
834
877
  }
835
878
  case "let":
836
- return `${pad}var ${escapeName(e.name)} := ${emitExpr(e.value)};\n${emitPureExpr(e.body, indent)}`;
879
+ return `${pad}var ${escapeName(e.name)}${e.type ? `: ${tyToDafny(e.type)}` : ""} := ${emitExpr(e.value)};\n${emitPureExpr(e.body, indent)}`;
837
880
  default:
838
881
  return `${pad}${emitExpr(e)}`;
839
882
  }
@@ -1003,12 +1046,22 @@ function emitDecl(d) {
1003
1046
  }
1004
1047
  case "def-by-method": {
1005
1048
  const tp = d.typeParams.length > 0 ? `<${d.typeParams.join(", ")}>` : "";
1006
- const lines = [`function ${escapeName(d.name)}${tp}(${paramList(d.params)}): ${tyToDafny(d.returnType)}`];
1007
- for (const r of d.requires)
1008
- lines.push(` requires ${emitExpr(r)}`);
1049
+ const signature = `${tp}(${paramList(d.params)}): ${tyToDafny(d.returnType)}`;
1050
+ const requires = d.requires.map(r => ` requires ${emitExpr(r)}`);
1051
+ // The functional specification is the proof author's to write: a bodyless
1052
+ // `<name>_fun_spec` stub, which the .dfy completes by adding a body after its
1053
+ // signature. The generated file parses and resolves on its own (an empty
1054
+ // function body would not), and the proof adds lines instead of editing
1055
+ // between generated braces.
1056
+ const spec = escapeGeneratedName(`${d.name}${SPEC_FUNCTION_SUFFIX}`);
1057
+ const lines = [
1058
+ `function ${spec}${signature}`, ...requires, "",
1059
+ `function ${escapeName(d.name)}${signature}`, ...requires,
1060
+ ];
1009
1061
  if (d.decreases)
1010
1062
  lines.push(` decreases ${emitExpr(d.decreases)}`);
1011
1063
  lines.push(`{`);
1064
+ lines.push(` ${spec}(${d.params.map(p => escapeName(p.name)).join(", ")})`);
1012
1065
  lines.push(`}`);
1013
1066
  lines.push(`by method {`);
1014
1067
  lines.push(emitStmts(d.methodBody, 1));
@@ -1153,6 +1206,13 @@ const CEIL_REAL = `function CeilReal(x: real): int
1153
1206
  if x == (x.Floor as real) then x.Floor
1154
1207
  else x.Floor + 1
1155
1208
  }`;
1209
+ const CALLBACK_INDICES = `function CallbackIndices(n: nat): (r: seq<int>)
1210
+ ensures |r| == n
1211
+ ensures forall i :: 0 <= i < n ==> r[i] == i
1212
+ ensures forall i :: i in r <==> 0 <= i < n
1213
+ {
1214
+ if n == 0 then [] else CallbackIndices(n - 1) + [n - 1]
1215
+ }`;
1156
1216
  const SEQ_FILTER_SOME = `function SeqFilterSome<T>(xs: seq<Option<T>>): seq<T>
1157
1217
  ensures |SeqFilterSome(xs)| <= |xs|
1158
1218
  {
@@ -1162,12 +1222,14 @@ const SEQ_FILTER_SOME = `function SeqFilterSome<T>(xs: seq<Option<T>>): seq<T>
1162
1222
  const SEQ_FILTER = `function SeqFilter<T(!new)>(p: T -> bool, xs: seq<T>): seq<T>
1163
1223
  ensures |SeqFilter(p, xs)| <= |xs|
1164
1224
  ensures forall x :: x in SeqFilter(p, xs) <==> x in xs && p(x)
1225
+ ensures forall i :: 0 <= i < |SeqFilter(p, xs)| ==> SeqFilter(p, xs)[i] in xs
1165
1226
  decreases |xs|
1166
1227
  {
1167
1228
  if |xs| == 0 then []
1168
1229
  else (if p(xs[0]) then [xs[0]] else []) + SeqFilter(p, xs[1..])
1169
1230
  }`;
1170
1231
  const SEQ_ALL = `predicate SeqAll<T>(xs: seq<T>, p: T -> bool)
1232
+ ensures SeqAll(xs, p) <==> (forall x :: x in xs ==> p(x))
1171
1233
  decreases |xs|
1172
1234
  {
1173
1235
  |xs| == 0 || (p(xs[0]) && SeqAll(xs[1..], p))
@@ -1330,6 +1392,36 @@ function StringIndexOfFromN(s: string, sub: string, from: nat): int
1330
1392
  else if s[from..from + |sub|] == sub then from as int
1331
1393
  else StringIndexOfFromN(s, sub, from + 1)
1332
1394
  }`;
1395
+ // JS `s.lastIndexOf(sub, position)` searches backward from the clamped
1396
+ // position for the last match starting at or before it. An empty `sub` matches
1397
+ // at that position. The postconditions also state that no later match exists,
1398
+ // which is what lets callers reason about the not-found result.
1399
+ const STRING_LAST_INDEX_OF = `predicate StringMatchesAt(s: string, sub: string, j: int)
1400
+ {
1401
+ 0 <= j && j + |sub| <= |s| && s[j..j + |sub|] == sub
1402
+ }
1403
+
1404
+ function StringLastIndexOf(s: string, sub: string): int
1405
+ ensures StringLastIndexOf(s, sub) == -1
1406
+ || (0 <= StringLastIndexOf(s, sub) <= |s| - |sub| && StringMatchesAt(s, sub, StringLastIndexOf(s, sub)))
1407
+ ensures forall j {:trigger StringMatchesAt(s, sub, j)} ::
1408
+ StringLastIndexOf(s, sub) < j ==> !StringMatchesAt(s, sub, j)
1409
+ {
1410
+ StringLastIndexOfFrom(s, sub, |s|)
1411
+ }
1412
+
1413
+ function StringLastIndexOfFrom(s: string, sub: string, from: nat): int
1414
+ decreases from
1415
+ ensures StringLastIndexOfFrom(s, sub, from) == -1
1416
+ || (0 <= StringLastIndexOfFrom(s, sub, from) <= from
1417
+ && StringMatchesAt(s, sub, StringLastIndexOfFrom(s, sub, from)))
1418
+ ensures forall j {:trigger StringMatchesAt(s, sub, j)} ::
1419
+ StringLastIndexOfFrom(s, sub, from) < j <= from ==> !StringMatchesAt(s, sub, j)
1420
+ {
1421
+ if StringMatchesAt(s, sub, from) then from as int
1422
+ else if from == 0 then -1
1423
+ else StringLastIndexOfFrom(s, sub, from - 1)
1424
+ }`;
1333
1425
  // `s.split(d)` in TS returns a non-empty sequence of segments. Modeled here as
1334
1426
  // an axiom — defining it recursively would force StringIndexOf to grow ensures
1335
1427
  // clauses that callers don't need. The two ensures cover what verification
@@ -1445,6 +1537,8 @@ const STRING_REPEAT = `function StringRepeat(s: string, n: int): string
1445
1537
  }`;
1446
1538
  const MATH_MIN = `function MathMin(a: int, b: int): int { if a <= b then a else b }`;
1447
1539
  const MATH_MAX = `function MathMax(a: int, b: int): int { if a >= b then a else b }`;
1540
+ const MATH_MIN_REAL = `function MathMinReal(a: real, b: real): real { if a <= b then a else b }`;
1541
+ const MATH_MAX_REAL = `function MathMaxReal(a: real, b: real): real { if a >= b then a else b }`;
1448
1542
  const MAX_OF_SEQ = `function MaxOfSeq(s: seq<int>): int
1449
1543
  requires |s| > 0
1450
1544
  ensures forall i: nat :: i < |s| ==> s[i] <= MaxOfSeq(s)
@@ -1504,6 +1598,7 @@ const INT_TO_STRING = `function IntToString(n: int): string
1504
1598
  if n < 0 then "-" + NatToString(-n) else NatToString(n)
1505
1599
  }`;
1506
1600
  const MATH_ABS = `function MathAbs(x: int): nat { if x >= 0 then x else -x }`;
1601
+ const MATH_ABS_REAL = `function MathAbsReal(x: real): real { if x >= 0.0 then x else -x }`;
1507
1602
  // perm(a, b) — `a` and `b` are reorderings of each other (equal as multisets).
1508
1603
  // Transparent (Dafny unfolds it), so hand-proofs can reason with `multiset`
1509
1604
  // directly. The `(==)` bound requires the element type to support equality.
@@ -1551,12 +1646,14 @@ const PREAMBLE_CODE = [
1551
1646
  ["SeqAll", SEQ_ALL],
1552
1647
  ["SeqFoldLeft", SEQ_FOLD_LEFT],
1553
1648
  ["SeqFilterSome", SEQ_FILTER_SOME],
1649
+ ["CallbackIndices", CALLBACK_INDICES],
1554
1650
  ["SeqFind", SEQ_FIND],
1555
1651
  ["SeqFindLast", SEQ_FIND_LAST],
1556
1652
  ["SeqFlatten", SEQ_FLATTEN],
1557
1653
  ["SeqJoin", SEQ_JOIN],
1558
1654
  ["SafeSlice", SAFE_SLICE],
1559
1655
  ["StringIndexOf", STRING_INDEX_OF],
1656
+ ["StringLastIndexOf", STRING_LAST_INDEX_OF],
1560
1657
  ["StringSearchPosition", STRING_SEARCH_POSITION],
1561
1658
  ["StringStartsWithAt", STRING_STARTS_WITH_AT],
1562
1659
  ["StringEndsWithAt", STRING_ENDS_WITH_AT],
@@ -1573,6 +1670,9 @@ const PREAMBLE_CODE = [
1573
1670
  ["MathAbs", MATH_ABS],
1574
1671
  ["MathMin", MATH_MIN],
1575
1672
  ["MathMax", MATH_MAX],
1673
+ ["MathAbsReal", MATH_ABS_REAL],
1674
+ ["MathMinReal", MATH_MIN_REAL],
1675
+ ["MathMaxReal", MATH_MAX_REAL],
1576
1676
  ["MaxOfSeq", MAX_OF_SEQ],
1577
1677
  ["MinOfSeq", MIN_OF_SEQ],
1578
1678
  ["Perm", PERM],