lemmascript 0.6.10 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lemmascript",
3
- "version": "0.6.10",
3
+ "version": "0.6.11",
4
4
  "description": "A verification toolchain for TypeScript — generates Lean 4 or Dafny from annotated TS",
5
5
  "type": "module",
6
6
  "engines": {
@@ -5,6 +5,7 @@ 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. */
@@ -180,12 +180,13 @@ function isEmittedUserName(name) {
180
180
  * namespace so it can't collapse onto an escaped user name. Bypasses the user
181
181
  * map on purpose: the raw name is synthesized, so it must be freshened *away
182
182
  * from* a same-spelled user name, not aliased onto it. Cached so a declaration
183
- * and its references render identically. */
184
- function escapeGeneratedName(name) {
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) {
185
186
  const cached = _generatedDafnyNames.get(name);
186
187
  if (cached !== undefined)
187
188
  return cached;
188
- const emitted = freshDafnyName(dafnyBaseName(name));
189
+ const emitted = freshDafnyName(dafnyBaseName(base));
189
190
  _generatedDafnyNames.set(name, emitted);
190
191
  _takenDafnyNames.add(emitted);
191
192
  return emitted;
@@ -359,7 +360,19 @@ function emitExpr(e) {
359
360
  needPreamble("SafeSlice");
360
361
  return `SafeSlice(${obj}, ${args[0]}, ${args[1] ?? `|${obj}|`})`;
361
362
  }
362
- return args.length === 1 ? `${obj}[${args[0]}..]` : `${obj}[${args[0]}..${args[1]}]`;
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}]`;
363
376
  }
364
377
  if (e.method === "map") {
365
378
  // Always a seq comprehension: Seq.Map would hide the element access
@@ -543,10 +556,12 @@ function emitExpr(e) {
543
556
  return `StringTrimLeft(${obj})`;
544
557
  }
545
558
  if (e.method === "toLowerCase") {
559
+ needPreamble("StringIsAscii");
546
560
  needPreamble("StringToLower");
547
561
  return `StringToLower(${obj})`;
548
562
  }
549
563
  if (e.method === "toUpperCase") {
564
+ needPreamble("StringIsAscii");
550
565
  needPreamble("StringToUpper");
551
566
  return `StringToUpper(${obj})`;
552
567
  }
@@ -707,6 +722,8 @@ function emitExpr(e) {
707
722
  needPreamble("CeilReal");
708
723
  if (e.fn === "FloorReal")
709
724
  needPreamble("FloorReal");
725
+ if (e.fn === "TruncReal")
726
+ needPreamble("TruncReal");
710
727
  if (e.fn === "StringFromCharCode")
711
728
  needPreamble("StringFromCharCode");
712
729
  if (e.fn === "NatToString")
@@ -721,6 +738,8 @@ function emitExpr(e) {
721
738
  needPreamble("MathMin");
722
739
  if (e.fn === "MathMax")
723
740
  needPreamble("MathMax");
741
+ if (e.fn === "IsSafeIntegerReal")
742
+ needPreamble("IsSafeIntegerReal");
724
743
  if (e.fn === "MathAbsReal")
725
744
  needPreamble("MathAbsReal");
726
745
  if (e.fn === "MathMinReal")
@@ -735,6 +754,16 @@ function emitExpr(e) {
735
754
  needPreamble("MathMin");
736
755
  needPreamble("MinOfSeq");
737
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");
738
767
  if (e.fn === "Perm")
739
768
  needPreamble("Perm");
740
769
  if (e.fn === "SetFromSeq")
@@ -778,6 +807,10 @@ function emitExpr(e) {
778
807
  case "toInt": return emitExpr(e.expr);
779
808
  case "toReal":
780
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)}]]`;
781
814
  case "index": {
782
815
  const obj = emitExpr(e.arr);
783
816
  const idx = emitExpr(e.idx);
@@ -1206,6 +1239,16 @@ const CEIL_REAL = `function CeilReal(x: real): int
1206
1239
  if x == (x.Floor as real) then x.Floor
1207
1240
  else x.Floor + 1
1208
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
+ }`;
1209
1252
  const CALLBACK_INDICES = `function CallbackIndices(n: nat): (r: seq<int>)
1210
1253
  ensures |r| == n
1211
1254
  ensures forall i :: 0 <= i < n ==> r[i] == i
@@ -1491,26 +1534,42 @@ function StringTrim(s: string): string
1491
1534
  // The same predicate and trims under `--unicode-char:true`, which the
1492
1535
  // `unicode-scalar` profile verifies under: byte-identical to what was always emitted.
1493
1536
  const STRING_TRIM_SCALAR = STRING_TRIM.replace(/\\u([0-9A-F]{4})/g, "\\U{$1}");
1494
- const STRING_TO_LOWER = `function StringToLower(s: string): string
1495
- ensures |StringToLower(s)| == |s|
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|
1496
1549
  decreases |s|
1497
1550
  {
1498
1551
  if |s| == 0 then ""
1499
1552
  else
1500
1553
  var c := s[0];
1501
1554
  var lower := if 'A' <= c <= 'Z' then (c - 'A' + 'a') as char else c;
1502
- [lower] + StringToLower(s[1..])
1503
- }`;
1504
- const STRING_TO_UPPER = `function StringToUpper(s: string): string
1505
- ensures |StringToUpper(s)| == |s|
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|
1506
1562
  decreases |s|
1507
1563
  {
1508
1564
  if |s| == 0 then ""
1509
1565
  else
1510
1566
  var c := s[0];
1511
1567
  var upper := if 'a' <= c <= 'z' then (c - 'a' + 'A') as char else c;
1512
- [upper] + StringToUpper(s[1..])
1513
- }`;
1568
+ [upper] + AsciiToUpper(s[1..])
1569
+ }
1570
+
1571
+ function {:axiom} StringToUpper(s: string): string
1572
+ ensures StringIsAscii(s) ==> StringToUpper(s) == AsciiToUpper(s)`;
1514
1573
  // `String.fromCharCode(n)` — the inverse of `s.charCodeAt(i)`'s `(s[i] as int)`
1515
1574
  // in the UTF-16 code-unit model selected by dafny-commands.ts. LemmaScript
1516
1575
  // currently admits the direct 16-bit range; JavaScript's wider ToUint16 coercion
@@ -1586,6 +1645,56 @@ lemma MinOfSeqConcat(a: seq<int>, b: seq<int>)
1586
1645
  assert (a + b)[|a| + i] == b[i];
1587
1646
  }
1588
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
+ }`;
1589
1698
  const NAT_TO_STRING = `function NatToString(n: nat): string
1590
1699
  decreases n
1591
1700
  {
@@ -1639,6 +1748,8 @@ const PREAMBLE_CODE = [
1639
1748
  ["JSStringLt", JS_STRING_LT],
1640
1749
  ["CeilReal", CEIL_REAL],
1641
1750
  ["FloorReal", FLOOR_REAL],
1751
+ ["IsSafeIntegerReal", IS_SAFE_INTEGER_REAL],
1752
+ ["TruncReal", TRUNC_REAL],
1642
1753
  ["SeqIndexOf", SEQ_INDEX_OF],
1643
1754
  ["SeqFindIndex", SEQ_FIND_INDEX],
1644
1755
  ["SeqFindLastIndex", SEQ_FIND_LAST_INDEX],
@@ -1661,6 +1772,7 @@ const PREAMBLE_CODE = [
1661
1772
  ["SeqSort", SEQ_SORT],
1662
1773
  ["SeqSortBy", SEQ_SORT_BY],
1663
1774
  ["StringTrim", () => isUtf16() ? STRING_TRIM : STRING_TRIM_SCALAR],
1775
+ ["StringIsAscii", STRING_IS_ASCII],
1664
1776
  ["StringToLower", STRING_TO_LOWER],
1665
1777
  ["StringToUpper", STRING_TO_UPPER],
1666
1778
  ["StringFromCharCode", () => isUtf16() ? STRING_FROM_CHAR_CODE : STRING_FROM_CHAR_CODE_SCALAR],
@@ -1675,6 +1787,9 @@ const PREAMBLE_CODE = [
1675
1787
  ["MathMaxReal", MATH_MAX_REAL],
1676
1788
  ["MaxOfSeq", MAX_OF_SEQ],
1677
1789
  ["MinOfSeq", MIN_OF_SEQ],
1790
+ ["MaxOfSeqReal", MAX_OF_SEQ_REAL],
1791
+ ["MinOfSeqReal", MIN_OF_SEQ_REAL],
1792
+ ["SeqIntToReal", SEQ_INT_TO_REAL],
1678
1793
  ["Perm", PERM],
1679
1794
  ["SetFromSeq", SET_FROM_SEQ],
1680
1795
  ];
@@ -1775,11 +1890,11 @@ function resolveTy(ty) {
1775
1890
  }
1776
1891
  /** Constructor names come from source strings (string-union values like
1777
1892
  * "spec-pure", discriminated-union tags), which may contain characters no
1778
- * TS identifier has; map those to `_` before the ordinary escaping. A
1779
- * collision after mapping fails loudly in Dafny (duplicate constructor)
1780
- * rather than silently merging. */
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. */
1781
1896
  function dafnyCtorName(name) {
1782
- return escapeName(name.replace(/[^A-Za-z0-9_'?]/g, "_"));
1897
+ return _userDafnyNames.get(name) ?? escapeGeneratedName(name, name.replace(/[^A-Za-z0-9_'?]/g, "_"));
1783
1898
  }
1784
1899
  function qualifyCtor(name, type) {
1785
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
+ }
@@ -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
- throw new Error(`array binding pattern in arrow parameter not yet supported: ${nameNode.getText()}`);
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
- return extractExpr(node.getExpression());
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);
@@ -432,13 +432,14 @@ function emitExpr(e, parentPrec) {
432
432
  : _boolCtx && e.op === "∧" ? "&&"
433
433
  : _boolCtx && e.op === "∨" ? "||"
434
434
  : e.op;
435
- // ↔ does not chain in Lean — a nested iff operand needs parens.
436
- const childPrec = e.op === "↔" ? prec(e.op) + 1 : prec(e.op);
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 = e.op === "↔" ? childPrec
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
- const args = e.args.map(a => (a.kind === "binop" || a.kind === "unop" || a.kind === "implies" || a.kind === "app" || a.kind === "methodCall") ? `(${emitExpr(a)})` : emitExpr(a));
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)
@@ -248,6 +248,7 @@ function rewriteChildrenExpr(e) {
248
248
  case "toInt": return { ...e, expr: r(e.expr) };
249
249
  case "toReal": return { ...e, expr: r(e.expr) };
250
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) };
251
252
  case "tupleLiteral": return { ...e, elems: e.elems.map(r) };
252
253
  case "tupleProj": return { ...e, obj: r(e.obj) };
253
254
  case "record": return { ...e, spread: e.spread ? r(e.spread) : null,
@@ -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
- return { ...expr, ty: payloadTy };
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 ((fn.field === "min" || fn.field === "max") && args.length >= 1)
811
- return args.some(a => a.ty.kind === "real") ? { kind: "real" } : args[0].ty;
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 === "map" ? { kind: "optional", inner: stepInTy.value }
1275
- : { kind: "unknown" };
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 ty = spread ? spread.ty : { kind: "unknown" };
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
@@ -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.kind === "int" && e.args[0].ty.big)
862
- return { kind: "bool", value: false };
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" && e.args.length === 2 ? "MathMin"
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
- return real && isIntegral(arg.ty) ? { kind: "toReal", expr: lowered } : lowered;
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
- return { kind: "app", fn: real ? `${fn}Real` : fn, args };
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.
@@ -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