lemmascript 0.6.10 → 0.6.12

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.
@@ -9,17 +9,23 @@ const MULTI_OPS = ["<==>", "==>", "===", "!==", "==", "!=", ">=", "<=", "&&", "|
9
9
  * allow TypeScript's fractional and exponent forms. */
10
10
  const BIGINT_LITERAL = /^(?:(?:0[xX][0-9a-fA-F](?:_?[0-9a-fA-F])*)|(?:0[bB][01](?:_?[01])*)|(?:0[oO][0-7](?:_?[0-7])*)|(?:[0-9](?:_?[0-9])*))n/;
11
11
  const NUMBER_LITERAL = /^(?:(?:0[xX][0-9a-fA-F](?:_?[0-9a-fA-F])*)|(?:0[bB][01](?:_?[01])*)|(?:0[oO][0-7](?:_?[0-7])*)|(?:(?:[0-9](?:_?[0-9])*)(?:\.(?:[0-9](?:_?[0-9])*)?)?|\.(?:[0-9](?:_?[0-9])*))(?:[eE][+-]?(?:[0-9](?:_?[0-9])*))?)/;
12
- function tokenize(input) {
12
+ function tokenize(input, spans) {
13
13
  const tokens = [];
14
14
  let i = 0;
15
+ let start = 0;
16
+ const push = (token) => {
17
+ tokens.push(token);
18
+ spans?.push({ start, end: i });
19
+ };
15
20
  while (i < input.length) {
16
21
  if (/\s/.test(input[i])) {
17
22
  i++;
18
23
  continue;
19
24
  }
25
+ start = i;
20
26
  if (input[i] === "\\" && input.slice(i + 1, i + 7) === "result") {
21
- tokens.push({ type: "result", value: undefined });
22
27
  i += 7;
28
+ push({ type: "result", value: undefined });
23
29
  continue;
24
30
  }
25
31
  if (input[i] === '"' || input[i] === "'") {
@@ -44,7 +50,7 @@ function tokenize(input) {
44
50
  }
45
51
  if (i < input.length)
46
52
  i++;
47
- tokens.push({ type: "str", value: s });
53
+ push({ type: "str", value: s });
48
54
  continue;
49
55
  }
50
56
  if (/[0-9]/.test(input[i]) || (input[i] === "." && /[0-9]/.test(input[i + 1]))) {
@@ -58,23 +64,23 @@ function tokenize(input) {
58
64
  // The `n` suffix is meaningful, not noise: a BigInt keeps its exact value
59
65
  // as a decimal string instead of being rounded into a double.
60
66
  if (bigintMatch)
61
- tokens.push({ type: "bigint", value: normalizeBigIntLiteral(text) });
67
+ push({ type: "bigint", value: normalizeBigIntLiteral(text) });
62
68
  else
63
- tokens.push({ type: "num", value: Number(text.replace(/_/g, "")) });
69
+ push({ type: "num", value: Number(text.replace(/_/g, "")) });
64
70
  continue;
65
71
  }
66
72
  if (/[a-zA-Z_]/.test(input[i])) {
67
73
  let id = "";
68
74
  while (i < input.length && /[a-zA-Z_0-9]/.test(input[i]))
69
75
  id += input[i++];
70
- tokens.push({ type: "ident", value: id });
76
+ push({ type: "ident", value: id });
71
77
  continue;
72
78
  }
73
79
  let matched = false;
74
80
  for (const op of MULTI_OPS) {
75
81
  if (input.slice(i, i + op.length) === op) {
76
- tokens.push({ type: "op", value: op });
77
82
  i += op.length;
83
+ push({ type: "op", value: op });
78
84
  matched = true;
79
85
  break;
80
86
  }
@@ -82,25 +88,28 @@ function tokenize(input) {
82
88
  if (matched)
83
89
  continue;
84
90
  const ch = input[i];
91
+ i++;
85
92
  if ("+-*/%><!?".includes(ch)) {
86
- tokens.push({ type: "op", value: ch });
93
+ push({ type: "op", value: ch });
87
94
  }
88
95
  else if ("()[],:.{}".includes(ch)) {
89
- tokens.push({ type: "punc", value: ch });
96
+ push({ type: "punc", value: ch });
90
97
  }
91
98
  else {
92
- throw new Error(`Unexpected '${ch}' at ${i} in: ${input}`);
99
+ throw new Error(`Unexpected '${ch}' at ${i - 1} in: ${input}`);
93
100
  }
94
- i++;
95
101
  }
96
102
  return tokens;
97
103
  }
98
104
  // ── Parser ───────────────────────────────────────────────────
99
105
  class Parser {
100
106
  tokens;
107
+ onFreeVariable;
101
108
  pos = 0;
102
- constructor(tokens) {
109
+ bound = new Set();
110
+ constructor(tokens, onFreeVariable) {
103
111
  this.tokens = tokens;
112
+ this.onFreeVariable = onFreeVariable;
104
113
  }
105
114
  peek() { return this.tokens[this.pos]; }
106
115
  advance() { return this.tokens[this.pos++]; }
@@ -304,10 +313,15 @@ class Parser {
304
313
  varType = ty;
305
314
  }
306
315
  this.expect("punc", ",");
316
+ const outer = this.bound;
317
+ this.bound = new Set([...outer, v]);
307
318
  const body = this.parseIff();
319
+ this.bound = outer;
308
320
  this.expect("punc", ")");
309
321
  return { kind: q, var: v, varType, body };
310
322
  }
323
+ if (!this.bound.has(t.value))
324
+ this.onFreeVariable?.(t.value, this.pos);
311
325
  this.advance();
312
326
  return { kind: "var", name: t.value };
313
327
  }
@@ -350,3 +364,18 @@ class Parser {
350
364
  export function parseExpr(input) {
351
365
  return new Parser(tokenize(input)).parse();
352
366
  }
367
+ /** Rewrite only free variable tokens, preserving annotation spelling and
368
+ * leaving fields, record keys, literals, types, and quantifier binders alone. */
369
+ export function renameSpecVariables(input, rename) {
370
+ const spans = [];
371
+ const tokens = tokenize(input, spans);
372
+ const edits = [];
373
+ new Parser(tokens, (name, index) => {
374
+ const replacement = rename(name);
375
+ if (replacement !== name)
376
+ edits.push({ ...spans[index], name: replacement });
377
+ }).parse();
378
+ for (const edit of edits.reverse())
379
+ input = input.slice(0, edit.start) + edit.name + input.slice(edit.end);
380
+ return input;
381
+ }
@@ -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, 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) })) };
@@ -84,50 +85,7 @@ function mapStmt(s, f) {
84
85
  case "assert": return { ...s, expr: r(s.expr) };
85
86
  }
86
87
  }
87
- /** Rename free occurrences of `from` to `to`, stopping at every construct that
88
- * rebinds `from` — lambda params, `let`/`let-bind`/`ghostLet` (shadows the
89
- * rest of the block), `match` arm patterns, `forall`/`exists`, and `for-in`
90
- * indices. Capture-avoiding: a nested scope that reintroduces `from` keeps its
91
- * own binding untouched. `mapExpr` doesn't descend into lambda bodies, so this
92
- * walks them by hand — statement binders are tracked only at that body's top
93
- * level, which is enough for the sole caller (dafny-emit's
94
- * `comprehensionBinder`). TODO: generalize if more callers need this. */
95
88
  const varE = (name) => ({ kind: "var", name });
96
- export function renameFreeVar(e, from, to) {
97
- const f = (x) => {
98
- if (x.kind === "var")
99
- return x.name === from ? { ...x, name: to } : x;
100
- // let-expression: `value` is in the outer scope (rename), `body` sees the
101
- // rebound `from` (leave it), so handle the recursion here to stop descent.
102
- if (x.kind === "let" && x.name === from)
103
- return { ...x, value: mapExpr(x.value, f) };
104
- if ((x.kind === "forall" || x.kind === "exists") && x.var === from)
105
- return x;
106
- if (x.kind === "match") {
107
- return { ...x, scrutinee: mapExpr(x.scrutinee, f), arms: x.arms.map(a => patternBinds(a.pattern, from) ? a : { ...a, body: mapExpr(a.body, f) }) };
108
- }
109
- if (x.kind === "lambda") {
110
- if (x.params.some(p => p.name === from))
111
- return x; // param shadows `from`
112
- const body = [];
113
- let shadowed = false;
114
- for (const s of x.body) {
115
- if (shadowed) {
116
- body.push(s);
117
- continue;
118
- }
119
- body.push(s.kind === "forin" && s.idx === from
120
- ? { ...s, bound: mapExpr(s.bound, f) } // idx shadows in the loop body
121
- : mapStmt(s, f));
122
- if ((s.kind === "let" || s.kind === "let-bind" || s.kind === "ghostLet") && s.name === from)
123
- shadowed = true;
124
- }
125
- return { ...x, body };
126
- }
127
- return null;
128
- };
129
- return mapExpr(e, f);
130
- }
131
89
  /** Map over all sub-expressions in a TExpr (typed IR). */
132
90
  function mapTExpr(e, f) {
133
91
  const hit = f(e);
@@ -175,9 +133,12 @@ function mapTStmt(s, f) {
175
133
  case "throw": return s;
176
134
  case "expr": return { ...s, expr: r(s.expr) };
177
135
  case "if": return { ...s, cond: r(s.cond), then: s.then.map(t => mapTStmt(t, f)), else: s.else.map(t => mapTStmt(t, f)) };
178
- case "while": return { ...s, cond: r(s.cond), invariants: s.invariants.map(r), body: s.body.map(t => mapTStmt(t, f)) };
136
+ case "while": return { ...s, cond: r(s.cond), invariants: s.invariants.map(r),
137
+ decreases: s.decreases ? r(s.decreases) : null,
138
+ doneWith: s.doneWith ? r(s.doneWith) : null, body: s.body.map(t => mapTStmt(t, f)) };
179
139
  case "switch": return { ...s, expr: r(s.expr), cases: s.cases.map(c => ({ ...c, body: c.body.map(t => mapTStmt(t, f)) })), defaultBody: s.defaultBody.map(t => mapTStmt(t, f)) };
180
- case "forof": return { ...s, iterable: r(s.iterable), invariants: s.invariants.map(r), body: s.body.map(t => mapTStmt(t, f)) };
140
+ case "forof": return { ...s, iterable: r(s.iterable), invariants: s.invariants.map(r),
141
+ doneWith: s.doneWith ? r(s.doneWith) : null, body: s.body.map(t => mapTStmt(t, f)) };
181
142
  case "ghostLet": return { ...s, init: r(s.init) };
182
143
  case "ghostAssign": return { ...s, value: r(s.value) };
183
144
  case "assert": return { ...s, expr: r(s.expr) };
@@ -456,7 +417,44 @@ function buildNestedFieldUpdate(recv, newVal) {
456
417
  return buildNestedFieldUpdate(recv.obj, upd);
457
418
  return null;
458
419
  }
420
+ /** Promote every spread segment before concatenation, preserving evaluation
421
+ * order. A seq<int> needs elementwise conversion; it cannot be cast to real. */
422
+ function lowerMinMaxSequence(e, real, binds) {
423
+ if (e.kind === "binop" && e.op === "arrayConcat") {
424
+ return { kind: "binop", op: "arrayConcat",
425
+ left: lowerMinMaxSequence(e.left, real, binds),
426
+ right: lowerMinMaxSequence(e.right, real, binds) };
427
+ }
428
+ if (e.kind === "arrayLiteral") {
429
+ return { kind: "arrayLiteral", elems: e.elems.map(el => {
430
+ const value = lowerExpr(el, binds);
431
+ if (real && isIntegral(el.ty))
432
+ return { kind: "toReal", expr: value };
433
+ return _opts.backend === "lean" && isNat(el.ty) ? { kind: "toInt", expr: value } : value;
434
+ }) };
435
+ }
436
+ const value = lowerExpr(e, binds);
437
+ if (_opts.backend === "lean" && e.ty.kind === "array" && isNat(e.ty.elem)) {
438
+ return { kind: "app", fn: "Array.map", args: [{ kind: "var", name: "Int.ofNat" }, value] };
439
+ }
440
+ return real && e.ty.kind === "array" && isIntegral(e.ty.elem)
441
+ ? { kind: "app", fn: "SeqIntToReal", args: [value] } : value;
442
+ }
459
443
  function lowerExpr(e, binds) {
444
+ // Lean spreads are checked Option operations. Lift even a syntactically pure
445
+ // call so total correctness requires the combined array to be nonempty.
446
+ if (_opts.backend === "lean" && e.kind === "call" && e.fn.kind === "var" &&
447
+ (e.fn.name === "MaxOfSeq" || e.fn.name === "MinOfSeq") && e.args.length === 1) {
448
+ const name = binds ? freshName(`_t${_liftCounter++}`) : null;
449
+ const value = { kind: "app",
450
+ fn: e.fn.name === "MaxOfSeq" ? "LemmaScript.maxOfArray" : "LemmaScript.minOfArray",
451
+ args: [lowerMinMaxSequence(e.args[0], e.ty.kind === "real", binds)] };
452
+ if (binds && name) {
453
+ binds.push({ kind: "let-bind", name, value });
454
+ return { kind: "var", name };
455
+ }
456
+ return value;
457
+ }
460
458
  // Monadic lifting: extract embedded method calls to let-binds.
461
459
  // `callKind: "method"` means a global var-fn call (classifyCall returns
462
460
  // "method" only for `fn.kind === "var"`). Receiver method calls have
@@ -813,6 +811,9 @@ function lowerExpr(e, binds) {
813
811
  }
814
812
  return { kind: "field", obj: transformExpr(e.obj), field: e.field, datatypeField: isRecordType(e.obj.ty) };
815
813
  case "index": {
814
+ if (e.obj.ty.kind === "string") {
815
+ return { kind: "stringIndex", str: lowerExpr(e.obj, binds), idx: lowerExpr(e.idx, binds) };
816
+ }
816
817
  const idx = transformExpr(e.idx);
817
818
  if (e.obj.ty.kind === "tuple") {
818
819
  // resolve guarantees a numeric-literal index here; project at that slot.
@@ -829,6 +830,12 @@ function lowerExpr(e, binds) {
829
830
  return { kind: "index", arr: transformExpr(e.obj), idx: wrappedIdx };
830
831
  }
831
832
  case "call": {
833
+ if (_opts.backend === "dafny" && e.fn.kind === "var" &&
834
+ (e.fn.name === "MaxOfSeq" || e.fn.name === "MinOfSeq") && e.args.length === 1) {
835
+ const real = e.ty.kind === "real";
836
+ return { kind: "app", fn: real ? `${e.fn.name}Real` : e.fn.name,
837
+ args: [lowerMinMaxSequence(e.args[0], real, binds)] };
838
+ }
832
839
  // Array.isArray(x) on a synth array-union (discriminant "__isArray__")
833
840
  // → constructor predicate `x.ArrayBranch?`. Used in spec ensures and
834
841
  // anywhere `Array.isArray` escapes the narrowing rule (narrow rewrites
@@ -858,8 +865,20 @@ function lowerExpr(e, binds) {
858
865
  // model, so the JS bound -(2^53 - 1) <= n <= 2^53 - 1 must be stated.
859
866
  if (e.fn.kind === "field" && e.fn.obj.kind === "var" && e.fn.obj.name === "Number" &&
860
867
  e.fn.field === "isSafeInteger" && e.args.length === 1 && isIntegral(e.args[0].ty)) {
861
- if (e.args[0].ty.kind === "int" && e.args[0].ty.big)
862
- return { kind: "bool", value: false };
868
+ if (isBigInt(e.args[0].ty)) {
869
+ // The result is false, but JS still evaluates the argument. Keep
870
+ // lifted method calls and pure expressions' proof obligations.
871
+ const value = lowerExpr(e.args[0], binds);
872
+ const result = { kind: "bool", value: false };
873
+ if (value.kind === "var" || value.kind === "bigint")
874
+ return result;
875
+ const name = freshName("_safeIntegerArg");
876
+ if (binds) {
877
+ binds.push({ kind: "let", name, type: e.args[0].ty, mutable: false, value });
878
+ return result;
879
+ }
880
+ return { kind: "let", name, type: e.args[0].ty, value, body: result };
881
+ }
863
882
  const n = lowerExpr(e.args[0], binds);
864
883
  const max = 9007199254740991;
865
884
  return {
@@ -868,19 +887,34 @@ function lowerExpr(e, binds) {
868
887
  right: { kind: "binop", op: "≤", left: n, right: { kind: "num", value: max } },
869
888
  };
870
889
  }
890
+ // Number.isSafeInteger(x) on a real: check integrality and safe range via
891
+ // a preamble predicate.
892
+ if (e.fn.kind === "field" && e.fn.obj.kind === "var" && e.fn.obj.name === "Number" &&
893
+ e.fn.field === "isSafeInteger" && e.args.length === 1 && e.args[0].ty.kind === "real") {
894
+ return { kind: "app", fn: "IsSafeIntegerReal", args: [lowerExpr(e.args[0], binds)] };
895
+ }
871
896
  // Math.abs/min/max preserve the resolved numeric type. Mixed operands
872
897
  // need explicit int/nat→real coercions, just like real binary operations.
873
898
  if (e.fn.kind === "field" && e.fn.obj.kind === "var" && e.fn.obj.name === "Math") {
899
+ const minMax = (e.fn.field === "min" || e.fn.field === "max") && e.args.length >= 1;
874
900
  const fn = e.fn.field === "abs" && e.args.length === 1 ? "MathAbs"
875
- : e.fn.field === "min" && e.args.length === 2 ? "MathMin"
876
- : e.fn.field === "max" && e.args.length === 2 ? "MathMax" : null;
901
+ : minMax ? (e.fn.field === "min" ? "MathMin" : "MathMax") : null;
877
902
  if (fn) {
878
903
  const real = e.ty.kind === "real";
879
904
  const args = e.args.map((arg) => {
880
905
  const lowered = lowerExpr(arg, binds);
881
- return real && isIntegral(arg.ty) ? { kind: "toReal", expr: lowered } : lowered;
906
+ if (real && isIntegral(arg.ty))
907
+ return { kind: "toReal", expr: lowered };
908
+ return _opts.backend === "lean" && minMax && e.ty.kind === "int" && isNat(arg.ty)
909
+ ? { kind: "toInt", expr: lowered } : lowered;
882
910
  });
883
- return { kind: "app", fn: real ? `${fn}Real` : fn, args };
911
+ const helper = real ? `${fn}Real` : _opts.backend === "lean" && minMax
912
+ ? `${e.fn.field === "min" ? "Min" : "Max"}.${e.fn.field}` : fn;
913
+ // Unary min/max is identity. Fold positional arguments through the
914
+ // binary helpers so scalar bounds need no sequence/index proofs.
915
+ return minMax
916
+ ? args.slice(1).reduce((acc, arg) => ({ kind: "app", fn: helper, args: [acc, arg] }), args[0])
917
+ : { kind: "app", fn: helper, args };
884
918
  }
885
919
  }
886
920
  // Math.ceil(x): CeilReal on real args, identity on int
@@ -909,6 +943,38 @@ function lowerExpr(e, binds) {
909
943
  return { kind: "app", fn: "FloorReal", args: [lowerExpr(arg, binds)] };
910
944
  return lowerExpr(arg, binds);
911
945
  }
946
+ // Math.trunc(x) / Math.round(x):
947
+ // - trunc(a / b) on integral operands → JSTruncDiv (Lean: Int.tdiv),
948
+ // checked first for the same reason as the floor case above
949
+ // - integral arg → identity
950
+ // - real arg (Dafny only) → TruncReal(x) / FloorReal(x + 0.5); JS
951
+ // rounds halfway ties toward +Infinity
952
+ // A bigint argument (a JS TypeError) would otherwise lower to the
953
+ // identity, and a Lean real argument has no lowering, so both are
954
+ // rejected. Other calls fall through to the unsupported-call error.
955
+ if (e.fn.kind === "field" && (e.fn.field === "trunc" || e.fn.field === "round") &&
956
+ e.fn.obj.kind === "var" && e.fn.obj.name === "Math" && e.args.length === 1 &&
957
+ (isIntegral(e.args[0].ty) || e.args[0].ty.kind === "real")) {
958
+ const name = `Math.${e.fn.field}`;
959
+ const arg = e.args[0];
960
+ if (isBigInt(arg.ty))
961
+ throw new Error(`${name} does not accept a bigint argument (JavaScript throws TypeError)`);
962
+ if (e.fn.field === "trunc" && arg.kind === "binop" && arg.op === "/" &&
963
+ isIntegral(arg.left.ty) && isIntegral(arg.right.ty)) {
964
+ return { kind: "app", fn: "JSTruncDiv", args: [lowerExpr(arg.left, binds), lowerExpr(arg.right, binds)] };
965
+ }
966
+ if (isIntegral(arg.ty))
967
+ return lowerExpr(arg, binds);
968
+ if (_opts.backend !== "dafny")
969
+ throw new Error("real arithmetic is not supported by the Lean backend (needs noncomputable ℝ / Mathlib).");
970
+ const x = lowerExpr(arg, binds);
971
+ if (e.fn.field === "trunc")
972
+ return { kind: "app", fn: "TruncReal", args: [x] };
973
+ return {
974
+ kind: "app", fn: "FloorReal",
975
+ args: [{ kind: "binop", op: "+", left: x, right: { kind: "num", value: 0.5 } }],
976
+ };
977
+ }
912
978
  // Method call: receiver.method(args) → methodCall node
913
979
  if (e.fn.kind === "field") {
914
980
  const recv = lowerExpr(e.fn.obj, binds);
@@ -1630,12 +1696,13 @@ function transformStmts(stmts, typeDecls) {
1630
1696
  const iterExpr = transformExpr(s.iterable);
1631
1697
  // All for-of shapes lower to the same range loop `for idx in 0..seq.size`;
1632
1698
  // they differ only in (a) which indexable `seq` is iterated and (b) the
1633
- // per-iteration `let`s that bind the loop names. Compute the shared loop-
1634
- // variable naming once, then let each shape fill in `seq` + `perIter`.
1699
+ // per-iteration `let`s that bind the loop names. The counter name was
1700
+ // minted by resolve, where specs naming it are resolved; the suffix
1701
+ // numbers this loop's helper names. Each shape fills in `seq` + `perIter`.
1635
1702
  const count = _forofCounters.get(headName) ?? 0;
1636
1703
  _forofCounters.set(headName, count + 1);
1637
1704
  const suffix = count === 0 ? "" : `${count + 1}`;
1638
- const idxName = freshName(`_${headName}_idx${suffix}`);
1705
+ const idxName = s.idx;
1639
1706
  const idxVar = { kind: "var", name: idxName };
1640
1707
  let seq;
1641
1708
  let perIter;
@@ -2196,14 +2263,23 @@ function matchesAccessPath(e, path) {
2196
2263
  return false;
2197
2264
  return collected.every((f, i) => f === path.fields[i]);
2198
2265
  }
2199
- /** Replace every TExpr matching `path` with `var(binder, binderTy)`. */
2266
+ /** Replace every read of `path` with `var(binder, binderTy)`. Extraction
2267
+ * leaves no binding that shadows another (see LexicalNames), so the name
2268
+ * identifies the variable, also inside a lambda that captures it. */
2200
2269
  function replacePathInTExpr(expr, path, binder, binderTy) {
2201
- return mapTExpr(expr, e => matchesAccessPath(e, path)
2202
- ? { kind: "var", name: binder, ty: binderTy } : null);
2270
+ return mapTExpr(expr, e => {
2271
+ if (matchesAccessPath(e, path))
2272
+ return { kind: "var", name: binder, ty: binderTy };
2273
+ if (e.kind === "lambda")
2274
+ return { ...e,
2275
+ params: e.params.map(p => p.defaultValue
2276
+ ? { ...p, defaultValue: replacePathInTExpr(p.defaultValue, path, binder, binderTy) } : p),
2277
+ body: replacePathInTStmts(e.body, path, binder, binderTy) };
2278
+ return null;
2279
+ });
2203
2280
  }
2204
2281
  function replacePathInTStmts(stmts, path, binder, binderTy) {
2205
- return stmts.map(s => mapTStmt(s, e => matchesAccessPath(e, path)
2206
- ? { kind: "var", name: binder, ty: binderTy } : null));
2282
+ return stmts.map(s => mapTStmt(s, e => replacePathInTExpr(e, path, binder, binderTy)));
2207
2283
  }
2208
2284
  // ── Pure function generation ─────────────────────────────────
2209
2285
  function transformPureBody(stmts, typeDecls) {
@@ -2548,6 +2624,30 @@ export function transformModule(mod, specImport, moduleBaseOverride) {
2548
2624
  });
2549
2625
  }
2550
2626
  }
2627
+ if (_opts.backend === "lean") {
2628
+ // A pure mirror would erase the failure on an empty spread. Keep these
2629
+ // functions and their transitive callers as methods, where WP checks it.
2630
+ const checked = new Set(["LemmaScript.maxOfArray", "LemmaScript.minOfArray"]);
2631
+ let changed = true;
2632
+ while (changed) {
2633
+ changed = false;
2634
+ for (const def of pureDefs) {
2635
+ if (!checked.has(def.name) && anyExpr(def.body, e => {
2636
+ const name = e.kind === "app" ? e.fn : e.kind === "var" ? e.name : "";
2637
+ return checked.has(name.replace(/^Pure\./, ""));
2638
+ })) {
2639
+ checked.add(def.name);
2640
+ changed = true;
2641
+ }
2642
+ }
2643
+ }
2644
+ for (let i = pureDefs.length - 1; i >= 0; i--) {
2645
+ if (checked.has(pureDefs[i].name)) {
2646
+ _pureDefNames.delete(pureDefs[i].name);
2647
+ pureDefs.splice(i, 1);
2648
+ }
2649
+ }
2650
+ }
2551
2651
  const base = mod.file.split("/").pop()?.replace(/\.ts$/, "") ?? "module";
2552
2652
  // Lean module base — overridable via `//@ lean-module` (see lsc.ts). Only the
2553
2653
  // def→types import below reads it; Dafny never passes an override.
@@ -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