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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lemmascript",
3
- "version": "0.6.10",
3
+ "version": "0.6.12",
4
4
  "description": "A verification toolchain for TypeScript — generates Lean 4 or Dafny from annotated TS",
5
5
  "type": "module",
6
6
  "engines": {
@@ -5,22 +5,35 @@ 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}`);
11
12
  }
12
- export function dafnyGen(genPath, dfyPath, text) {
13
+ export function dafnyGen(genPath, dfyPath, text, basePath) {
14
+ // Preserve the previous generation as the three-way merge base when overwriting
15
+ // a changed .dfy.gen beside an existing .dfy, so a later `lsc regen` still
16
+ // merges from the generation the proof derives from.
17
+ if (basePath && existsSync(dfyPath) && existsSync(genPath) && !existsSync(basePath)) {
18
+ const oldGen = readFileSync(genPath, "utf-8");
19
+ if (oldGen !== text)
20
+ writeFileSync(basePath, oldGen);
21
+ }
13
22
  writeGen(genPath, text);
14
23
  if (!existsSync(dfyPath)) {
15
24
  writeFileSync(dfyPath, text);
16
25
  console.log(`Created: ${dfyPath}`);
17
26
  }
18
27
  }
19
- export function dafnyCheckDiff(genPath, dfyPath, log) {
28
+ export function dafnyCheckDiff(genPath, dfyPath, log, basePath) {
20
29
  const ok = additionsOnly(genPath, dfyPath);
21
- if (!ok)
30
+ if (!ok) {
22
31
  log?.finish({ stage: "diff", exit: 1, dfyPath });
23
- return ok;
32
+ return false;
33
+ }
34
+ if (basePath && existsSync(basePath))
35
+ unlinkSync(basePath);
36
+ return true;
24
37
  }
25
38
  function additionsOnly(genPath, dfyPath) {
26
39
  for (const filePath of [genPath, dfyPath]) {
@@ -43,7 +56,7 @@ function additionsOnly(genPath, dfyPath) {
43
56
  }
44
57
  let diff = "";
45
58
  try {
46
- diff = execFileSync("git", ["diff", "--no-index", "--minimal", "--no-color", "--no-ext-diff", "--no-textconv", "--text", "--", genPath, dfyPath], { encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"] });
59
+ diff = execFileSync("git", ["diff", "--no-index", "--minimal", "--no-color", "--no-ext-diff", "--no-textconv", "--text", "--", genPath, dfyPath], { encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: Infinity });
47
60
  }
48
61
  catch (e) {
49
62
  // `git diff --no-index` exits 1 for a valid, non-empty comparison. Every
@@ -78,6 +91,14 @@ function additionsOnly(genPath, dfyPath) {
78
91
  console.error(" " + d);
79
92
  return false;
80
93
  }
94
+ // Added lines must not bypass the verifier, weaken generated contracts, or change verifier options.
95
+ const violations = proofAdditionViolations(readFileSync(genPath, "utf-8"), readFileSync(dfyPath, "utf-8"), path.basename(dfyPath));
96
+ if (violations.length > 0) {
97
+ console.error(`ERROR: ${path.basename(dfyPath)} has disallowed proof additions:`);
98
+ for (const v of violations)
99
+ console.error(" " + v);
100
+ return false;
101
+ }
81
102
  return true;
82
103
  }
83
104
  /** Read the saved model, rejecting ambiguous headers before verification. */
@@ -3,7 +3,6 @@
3
3
  */
4
4
  import { decimalNumberLiteral, exactIntegerLiteral, usesName, usesNameInDecl, usesNameInStmts } from "./ir.js";
5
5
  import { freshNameWhere, userNames } from "./names.js";
6
- import { renameFreeVar } from "./transform.js";
7
6
  import { DEFAULT_OPTIONS, resolveOptions } from "./config.js";
8
7
  /** Appended to a function's name for the lemma that carries its `//@ ensures`. */
9
8
  export const ENSURES_LEMMA_SUFFIX = "_ensures";
@@ -15,21 +14,13 @@ export const SPEC_FUNCTION_SUFFIX = "_fun_spec";
15
14
  function freshBinder(base, ...wrapped) {
16
15
  return freshNameWhere(base, name => wrapped.some(w => usesName(w, name)));
17
16
  }
18
- /** Binder + body for lowering a single-return lambda to a comprehension whose
19
- * receiver is emitted inside the binder's scope. TS scoping keeps the receiver
20
- * outside the lambda, so a lambda param sharing a name with anything free in
21
- * the receiver would capture it — e.g. `mk(n).some(n => …)` naively emitting
22
- * `exists n :: n in mk(n) && …`. Alpha-rename the param out of the way (and
23
- * its free uses in the body); the zero-param default must also dodge free
24
- * names in the body. */
17
+ /** Binder for lowering a single-return lambda to a comprehension whose
18
+ * receiver is emitted inside the binder's scope. A source parameter is used
19
+ * as is: extraction renames one that shares a name with anything its receiver
20
+ * reads (see LexicalNames), so `mk(n).some(n => …)` arrives as `n_2 => …`.
21
+ * The zero-param default is minted here and must dodge free names itself. */
25
22
  function comprehensionBinder(lam, value, receiver) {
26
- const rawName = lam.params[0]?.name;
27
- if (rawName === undefined)
28
- return { binder: escapeName(freshBinder("x", receiver, value)), body: value };
29
- if (!usesName(receiver, rawName))
30
- return { binder: escapeName(rawName), body: value };
31
- const fresh = freshBinder(rawName, receiver, value);
32
- return { binder: escapeName(fresh), body: renameFreeVar(value, rawName, fresh) };
23
+ return escapeName(lam.params[0]?.name ?? freshBinder("x", receiver, value));
33
24
  }
34
25
  // ── Ty → Dafny type string ─────────────────────────────────
35
26
  function tyToDafny(ty) {
@@ -180,12 +171,13 @@ function isEmittedUserName(name) {
180
171
  * namespace so it can't collapse onto an escaped user name. Bypasses the user
181
172
  * map on purpose: the raw name is synthesized, so it must be freshened *away
182
173
  * from* a same-spelled user name, not aliased onto it. Cached so a declaration
183
- * and its references render identically. */
184
- function escapeGeneratedName(name) {
174
+ * and its references render identically. An optional base changes the candidate
175
+ * spelling without changing the original name used as the cache key. */
176
+ function escapeGeneratedName(name, base = name) {
185
177
  const cached = _generatedDafnyNames.get(name);
186
178
  if (cached !== undefined)
187
179
  return cached;
188
- const emitted = freshDafnyName(dafnyBaseName(name));
180
+ const emitted = freshDafnyName(dafnyBaseName(base));
189
181
  _generatedDafnyNames.set(name, emitted);
190
182
  _takenDafnyNames.add(emitted);
191
183
  return emitted;
@@ -284,7 +276,12 @@ function wrapQuantifier(sub) {
284
276
  }
285
277
  function emitExpr(e) {
286
278
  switch (e.kind) {
287
- case "var": return e.name === "undefined" ? "None" : escapeName(e.name);
279
+ case "var":
280
+ if (e.name === "undefined") {
281
+ needPreamble("OptionType");
282
+ return "None";
283
+ }
284
+ return escapeName(e.name);
288
285
  case "num": return decimalNumberLiteral(e.value);
289
286
  // Already canonical decimal; Dafny's `int` is mathematical, so no `n` suffix.
290
287
  case "bigint": return e.value;
@@ -359,7 +356,19 @@ function emitExpr(e) {
359
356
  needPreamble("SafeSlice");
360
357
  return `SafeSlice(${obj}, ${args[0]}, ${args[1] ?? `|${obj}|`})`;
361
358
  }
362
- return args.length === 1 ? `${obj}[${args[0]}..]` : `${obj}[${args[0]}..${args[1]}]`;
359
+ // JS negative index: xs.slice(0, -N) → xs[0..|xs|-N].
360
+ // Same rewrite the string branch uses.
361
+ const negVal = (a) => {
362
+ const v = exactIntegerLiteral(a);
363
+ return v !== null && v < 0n ? (-v).toString(10) : null;
364
+ };
365
+ const loN = negVal(e.args[0]);
366
+ const loEx = loN !== null ? `|${obj}|-${loN}` : args[0];
367
+ if (args.length === 1)
368
+ return `${obj}[${loEx}..]`;
369
+ const hiN = negVal(e.args[1]);
370
+ const hiEx = hiN !== null ? `|${obj}|-${hiN}` : args[1];
371
+ return `${obj}[${loEx}..${hiEx}]`;
363
372
  }
364
373
  if (e.method === "map") {
365
374
  // Always a seq comprehension: Seq.Map would hide the element access
@@ -460,9 +469,8 @@ function emitExpr(e) {
460
469
  const lam = e.args[0];
461
470
  let p, body;
462
471
  if (lam.kind === "lambda" && lam.body.length === 1 && lam.body[0].kind === "return") {
463
- const cb = comprehensionBinder(lam, lam.body[0].value, e.obj);
464
- p = cb.binder;
465
- body = emitExpr(cb.body);
472
+ p = comprehensionBinder(lam, lam.body[0].value, e.obj);
473
+ body = emitExpr(lam.body[0].value);
466
474
  }
467
475
  else {
468
476
  p = escapeName(freshBinder("x", e.obj, e.args[0]));
@@ -543,10 +551,12 @@ function emitExpr(e) {
543
551
  return `StringTrimLeft(${obj})`;
544
552
  }
545
553
  if (e.method === "toLowerCase") {
554
+ needPreamble("StringIsAscii");
546
555
  needPreamble("StringToLower");
547
556
  return `StringToLower(${obj})`;
548
557
  }
549
558
  if (e.method === "toUpperCase") {
559
+ needPreamble("StringIsAscii");
550
560
  needPreamble("StringToUpper");
551
561
  return `StringToUpper(${obj})`;
552
562
  }
@@ -611,8 +621,8 @@ function emitExpr(e) {
611
621
  const ret = lam.body[0];
612
622
  if (ret.kind !== "return")
613
623
  throw new Error("unreachable");
614
- const { binder: p, body: v } = comprehensionBinder(lam, ret.value, e.obj);
615
- const body = emitExpr(v);
624
+ const p = comprehensionBinder(lam, ret.value, e.obj);
625
+ const body = emitExpr(ret.value);
616
626
  return `(set ${p} | ${p} in ${obj} && ${body})`;
617
627
  }
618
628
  }
@@ -686,6 +696,10 @@ function emitExpr(e) {
686
696
  }
687
697
  case "app": {
688
698
  const args = e.args.map(emitExpr);
699
+ // Optional coercions also arrive as applications, including locals
700
+ // whose inferred types never pass through tyToDafny.
701
+ if (!e.ctorOf && (e.fn === "Some" || e.fn === "None"))
702
+ needPreamble("OptionType");
689
703
  if (e.fn === "SetToSeq") {
690
704
  needPreamble("SetToSeq");
691
705
  return `SetToSeq(${args.join(", ")})`;
@@ -707,6 +721,8 @@ function emitExpr(e) {
707
721
  needPreamble("CeilReal");
708
722
  if (e.fn === "FloorReal")
709
723
  needPreamble("FloorReal");
724
+ if (e.fn === "TruncReal")
725
+ needPreamble("TruncReal");
710
726
  if (e.fn === "StringFromCharCode")
711
727
  needPreamble("StringFromCharCode");
712
728
  if (e.fn === "NatToString")
@@ -721,6 +737,8 @@ function emitExpr(e) {
721
737
  needPreamble("MathMin");
722
738
  if (e.fn === "MathMax")
723
739
  needPreamble("MathMax");
740
+ if (e.fn === "IsSafeIntegerReal")
741
+ needPreamble("IsSafeIntegerReal");
724
742
  if (e.fn === "MathAbsReal")
725
743
  needPreamble("MathAbsReal");
726
744
  if (e.fn === "MathMinReal")
@@ -735,6 +753,16 @@ function emitExpr(e) {
735
753
  needPreamble("MathMin");
736
754
  needPreamble("MinOfSeq");
737
755
  }
756
+ if (e.fn === "MaxOfSeqReal") {
757
+ needPreamble("MathMaxReal");
758
+ needPreamble("MaxOfSeqReal");
759
+ }
760
+ if (e.fn === "MinOfSeqReal") {
761
+ needPreamble("MathMinReal");
762
+ needPreamble("MinOfSeqReal");
763
+ }
764
+ if (e.fn === "SeqIntToReal")
765
+ needPreamble("SeqIntToReal");
738
766
  if (e.fn === "Perm")
739
767
  needPreamble("Perm");
740
768
  if (e.fn === "SetFromSeq")
@@ -778,6 +806,10 @@ function emitExpr(e) {
778
806
  case "toInt": return emitExpr(e.expr);
779
807
  case "toReal":
780
808
  return `(${emitExpr(e.expr)} as real)`;
809
+ case "stringIndex":
810
+ // TS indexing returns a string; Dafny's native string subscript is a
811
+ // char. The singleton sequence preserves the native bounds obligation.
812
+ return `[${emitExpr(e.str)}[${emitExpr(e.idx)}]]`;
781
813
  case "index": {
782
814
  const obj = emitExpr(e.arr);
783
815
  const idx = emitExpr(e.idx);
@@ -1206,6 +1238,16 @@ const CEIL_REAL = `function CeilReal(x: real): int
1206
1238
  if x == (x.Floor as real) then x.Floor
1207
1239
  else x.Floor + 1
1208
1240
  }`;
1241
+ const IS_SAFE_INTEGER_REAL = `predicate IsSafeIntegerReal(x: real)
1242
+ {
1243
+ x.Floor as real == x && -9007199254740991 <= x.Floor <= 9007199254740991
1244
+ }`;
1245
+ const TRUNC_REAL = `function TruncReal(x: real): (t: int)
1246
+ ensures x >= 0.0 ==> t as real <= x < t as real + 1.0
1247
+ ensures x < 0.0 ==> t as real - 1.0 < x <= t as real
1248
+ {
1249
+ if x >= 0.0 then x.Floor else -((-x).Floor)
1250
+ }`;
1209
1251
  const CALLBACK_INDICES = `function CallbackIndices(n: nat): (r: seq<int>)
1210
1252
  ensures |r| == n
1211
1253
  ensures forall i :: 0 <= i < n ==> r[i] == i
@@ -1491,26 +1533,42 @@ function StringTrim(s: string): string
1491
1533
  // The same predicate and trims under `--unicode-char:true`, which the
1492
1534
  // `unicode-scalar` profile verifies under: byte-identical to what was always emitted.
1493
1535
  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|
1536
+ // `s.toLowerCase()` / `s.toUpperCase()` apply JavaScript's full Unicode case
1537
+ // mapping (UnicodeData plus SpecialCasing): non-ASCII letters change and the
1538
+ // length can change ("ß".toUpperCase() is "SS", "İ".toLowerCase() has length 2).
1539
+ // The helpers are therefore axioms that fix only the all-ASCII case, where
1540
+ // JavaScript maps exactly A-Z <-> a-z and leaves every other character alone.
1541
+ // Any other input has an unconstrained (but deterministic) result.
1542
+ const STRING_IS_ASCII = `predicate StringIsAscii(s: string)
1543
+ {
1544
+ forall i :: 0 <= i < |s| ==> (s[i] as int) < 128
1545
+ }`;
1546
+ const STRING_TO_LOWER = `function AsciiToLower(s: string): string
1547
+ ensures |AsciiToLower(s)| == |s|
1496
1548
  decreases |s|
1497
1549
  {
1498
1550
  if |s| == 0 then ""
1499
1551
  else
1500
1552
  var c := s[0];
1501
1553
  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|
1554
+ [lower] + AsciiToLower(s[1..])
1555
+ }
1556
+
1557
+ function {:axiom} StringToLower(s: string): string
1558
+ ensures StringIsAscii(s) ==> StringToLower(s) == AsciiToLower(s)`;
1559
+ const STRING_TO_UPPER = `function AsciiToUpper(s: string): string
1560
+ ensures |AsciiToUpper(s)| == |s|
1506
1561
  decreases |s|
1507
1562
  {
1508
1563
  if |s| == 0 then ""
1509
1564
  else
1510
1565
  var c := s[0];
1511
1566
  var upper := if 'a' <= c <= 'z' then (c - 'a' + 'A') as char else c;
1512
- [upper] + StringToUpper(s[1..])
1513
- }`;
1567
+ [upper] + AsciiToUpper(s[1..])
1568
+ }
1569
+
1570
+ function {:axiom} StringToUpper(s: string): string
1571
+ ensures StringIsAscii(s) ==> StringToUpper(s) == AsciiToUpper(s)`;
1514
1572
  // `String.fromCharCode(n)` — the inverse of `s.charCodeAt(i)`'s `(s[i] as int)`
1515
1573
  // in the UTF-16 code-unit model selected by dafny-commands.ts. LemmaScript
1516
1574
  // currently admits the direct 16-bit range; JavaScript's wider ToUint16 coercion
@@ -1586,6 +1644,56 @@ lemma MinOfSeqConcat(a: seq<int>, b: seq<int>)
1586
1644
  assert (a + b)[|a| + i] == b[i];
1587
1645
  }
1588
1646
  }`;
1647
+ const MAX_OF_SEQ_REAL = `function MaxOfSeqReal(s: seq<real>): real
1648
+ requires |s| > 0
1649
+ ensures forall i: nat :: i < |s| ==> s[i] <= MaxOfSeqReal(s)
1650
+ ensures exists i: nat :: i < |s| && s[i] == MaxOfSeqReal(s)
1651
+ decreases |s|
1652
+ {
1653
+ if |s| == 1 then s[0]
1654
+ else MathMaxReal(s[0], MaxOfSeqReal(s[1..]))
1655
+ }
1656
+
1657
+ lemma MaxOfSeqRealConcat(a: seq<real>, b: seq<real>)
1658
+ requires |a| + |b| > 0
1659
+ ensures forall i: nat :: i < |a| ==> a[i] <= MaxOfSeqReal(a + b)
1660
+ ensures forall i: nat :: i < |b| ==> b[i] <= MaxOfSeqReal(a + b)
1661
+ {
1662
+ forall i: nat | i < |a| ensures a[i] <= MaxOfSeqReal(a + b) {
1663
+ assert (a + b)[i] == a[i];
1664
+ }
1665
+ forall i: nat | i < |b| ensures b[i] <= MaxOfSeqReal(a + b) {
1666
+ assert (a + b)[|a| + i] == b[i];
1667
+ }
1668
+ }`;
1669
+ const MIN_OF_SEQ_REAL = `function MinOfSeqReal(s: seq<real>): real
1670
+ requires |s| > 0
1671
+ ensures forall i: nat :: i < |s| ==> MinOfSeqReal(s) <= s[i]
1672
+ ensures exists i: nat :: i < |s| && s[i] == MinOfSeqReal(s)
1673
+ decreases |s|
1674
+ {
1675
+ if |s| == 1 then s[0]
1676
+ else MathMinReal(s[0], MinOfSeqReal(s[1..]))
1677
+ }
1678
+
1679
+ lemma MinOfSeqRealConcat(a: seq<real>, b: seq<real>)
1680
+ requires |a| + |b| > 0
1681
+ ensures forall i: nat :: i < |a| ==> MinOfSeqReal(a + b) <= a[i]
1682
+ ensures forall i: nat :: i < |b| ==> MinOfSeqReal(a + b) <= b[i]
1683
+ {
1684
+ forall i: nat | i < |a| ensures MinOfSeqReal(a + b) <= a[i] {
1685
+ assert (a + b)[i] == a[i];
1686
+ }
1687
+ forall i: nat | i < |b| ensures MinOfSeqReal(a + b) <= b[i] {
1688
+ assert (a + b)[|a| + i] == b[i];
1689
+ }
1690
+ }`;
1691
+ const SEQ_INT_TO_REAL = `function SeqIntToReal(s: seq<int>): seq<real>
1692
+ ensures |SeqIntToReal(s)| == |s|
1693
+ ensures forall i: nat :: i < |s| ==> SeqIntToReal(s)[i] == (s[i] as real)
1694
+ {
1695
+ seq(|s|, i requires 0 <= i < |s| => s[i] as real)
1696
+ }`;
1589
1697
  const NAT_TO_STRING = `function NatToString(n: nat): string
1590
1698
  decreases n
1591
1699
  {
@@ -1639,6 +1747,8 @@ const PREAMBLE_CODE = [
1639
1747
  ["JSStringLt", JS_STRING_LT],
1640
1748
  ["CeilReal", CEIL_REAL],
1641
1749
  ["FloorReal", FLOOR_REAL],
1750
+ ["IsSafeIntegerReal", IS_SAFE_INTEGER_REAL],
1751
+ ["TruncReal", TRUNC_REAL],
1642
1752
  ["SeqIndexOf", SEQ_INDEX_OF],
1643
1753
  ["SeqFindIndex", SEQ_FIND_INDEX],
1644
1754
  ["SeqFindLastIndex", SEQ_FIND_LAST_INDEX],
@@ -1661,6 +1771,7 @@ const PREAMBLE_CODE = [
1661
1771
  ["SeqSort", SEQ_SORT],
1662
1772
  ["SeqSortBy", SEQ_SORT_BY],
1663
1773
  ["StringTrim", () => isUtf16() ? STRING_TRIM : STRING_TRIM_SCALAR],
1774
+ ["StringIsAscii", STRING_IS_ASCII],
1664
1775
  ["StringToLower", STRING_TO_LOWER],
1665
1776
  ["StringToUpper", STRING_TO_UPPER],
1666
1777
  ["StringFromCharCode", () => isUtf16() ? STRING_FROM_CHAR_CODE : STRING_FROM_CHAR_CODE_SCALAR],
@@ -1675,6 +1786,9 @@ const PREAMBLE_CODE = [
1675
1786
  ["MathMaxReal", MATH_MAX_REAL],
1676
1787
  ["MaxOfSeq", MAX_OF_SEQ],
1677
1788
  ["MinOfSeq", MIN_OF_SEQ],
1789
+ ["MaxOfSeqReal", MAX_OF_SEQ_REAL],
1790
+ ["MinOfSeqReal", MIN_OF_SEQ_REAL],
1791
+ ["SeqIntToReal", SEQ_INT_TO_REAL],
1678
1792
  ["Perm", PERM],
1679
1793
  ["SetFromSeq", SET_FROM_SEQ],
1680
1794
  ];
@@ -1775,11 +1889,11 @@ function resolveTy(ty) {
1775
1889
  }
1776
1890
  /** Constructor names come from source strings (string-union values like
1777
1891
  * "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. */
1892
+ * TS identifier has. Sanitize only the candidate spelling, keeping the original
1893
+ * literal as the cache key so distinct literals cannot collapse onto one entry.
1894
+ * Identifier-shaped tags retain their existing source-name mapping. */
1781
1895
  function dafnyCtorName(name) {
1782
- return escapeName(name.replace(/[^A-Za-z0-9_'?]/g, "_"));
1896
+ return _userDafnyNames.get(name) ?? escapeGeneratedName(name, name.replace(/[^A-Za-z0-9_'?]/g, "_"));
1783
1897
  }
1784
1898
  function qualifyCtor(name, type) {
1785
1899
  const rawName = name.replace(/^\./, "");