lemmascript 0.6.3 → 0.6.5

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.
@@ -4,7 +4,9 @@
4
4
  import { exactIntegerLiteral, usesName, usesNameInDecl, usesNameInStmts } from "./ir.js";
5
5
  import { freshNameWhere, userNames } from "./names.js";
6
6
  import { renameFreeVar } from "./transform.js";
7
- import { DEFAULT_OPTIONS } from "./config.js";
7
+ import { DEFAULT_OPTIONS, resolveOptions } from "./config.js";
8
+ /** Appended to a function's name for the lemma that carries its `//@ ensures`. */
9
+ export const ENSURES_LEMMA_SUFFIX = "_ensures";
8
10
  /** Fresh binder for a comprehension wrapping the given subexpressions: `base`
9
11
  * verbatim unless one of them references it, then primed until free. A *local*
10
12
  * check — a same-named name elsewhere in the module keeps the plain binder. */
@@ -214,6 +216,29 @@ const OP_MAP = {
214
216
  "∧": "&&", "∨": "||", "¬": "!", "↔": "<==>",
215
217
  "arrayConcat": "+",
216
218
  };
219
+ /** Render a JavaScript string without losing its UTF-16 representation.
220
+ *
221
+ * JavaScript iteration by index exposes UTF-16 code units, including unpaired
222
+ * surrogates. Node's UTF-8 file writer would replace an unpaired surrogate if
223
+ * we emitted it literally, so every non-printable/non-ASCII unit is written as
224
+ * a Dafny `\\uXXXX` escape. Under `--unicode-char:false`, each escape denotes
225
+ * exactly one Dafny char and therefore exactly one JavaScript code unit.
226
+ */
227
+ function escapeDafnyUTF16String(value) {
228
+ let out = "";
229
+ for (let i = 0; i < value.length; i++) {
230
+ const unit = value.charCodeAt(i);
231
+ if (unit === 0x22)
232
+ out += '\\"';
233
+ else if (unit === 0x5c)
234
+ out += "\\\\";
235
+ else if (0x20 <= unit && unit <= 0x7e)
236
+ out += String.fromCharCode(unit);
237
+ else
238
+ out += `\\u${unit.toString(16).toUpperCase().padStart(4, "0")}`;
239
+ }
240
+ return out;
241
+ }
217
242
  function mapOp(op) { return OP_MAP[op] ?? op; }
218
243
  // ── Expression emission ─────────────────────────────────────
219
244
  function emitScrutinee(s) {
@@ -247,7 +272,12 @@ function emitExpr(e) {
247
272
  // Already canonical decimal; Dafny's `int` is mathematical, so no `n` suffix.
248
273
  case "bigint": return e.value;
249
274
  case "bool": return e.value ? "true" : "false";
250
- case "str": return `"${e.value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n')}"`;
275
+ case "str":
276
+ // Under the default profile the literal is written exactly as before;
277
+ // only the UTF-16 profile needs code-unit escapes (DESIGN_STRINGS.md §3).
278
+ return isUtf16()
279
+ ? `"${escapeDafnyUTF16String(e.value)}"`
280
+ : `"${e.value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n')}"`;
251
281
  case "constructor": {
252
282
  // Option constructors (Some/None) may appear in inferred positions
253
283
  // (e.g. lambda result) without an explicit `optional<T>` in any
@@ -352,16 +382,24 @@ function emitExpr(e) {
352
382
  const comp = `seq(|${s}|, ${idx} requires 0 <= ${idx} < |${s}| => ${core})`;
353
383
  return bind ? `(var ${s} := ${obj}; ${comp})` : comp;
354
384
  }
355
- if (e.method === "filter")
356
- return `Std.Collections.Seq.Filter(${args[0]}, ${obj})`;
385
+ if (e.method === "filter") {
386
+ if (_dafnyLibrary === "stdlib")
387
+ return `Std.Collections.Seq.Filter(${args[0]}, ${obj})`;
388
+ needPreamble("SeqFilter");
389
+ return `SeqFilter(${args[0]}, ${obj})`;
390
+ }
357
391
  // filterMap (synthesized in resolve): drop Nones and unwrap to seq<T>.
358
392
  if (e.method === "filterSome") {
359
393
  needPreamble("SeqFilterSome");
360
394
  needPreamble("OptionType");
361
395
  return `SeqFilterSome(${obj})`;
362
396
  }
363
- if (e.method === "every")
364
- return `Std.Collections.Seq.All(${obj}, ${args[0]})`;
397
+ if (e.method === "every") {
398
+ if (_dafnyLibrary === "stdlib")
399
+ return `Std.Collections.Seq.All(${obj}, ${args[0]})`;
400
+ needPreamble("SeqAll");
401
+ return `SeqAll(${obj}, ${args[0]})`;
402
+ }
365
403
  if (e.method === "find") {
366
404
  needPreamble("OptionType");
367
405
  needPreamble("SeqFind");
@@ -404,9 +442,12 @@ function emitExpr(e) {
404
442
  }
405
443
  return `(exists ${p} :: ${p} in ${obj} && ${body})`;
406
444
  }
407
- // `.reduce(f, init)` → Std's FoldLeft(f, init, xs) (same arg order).
445
+ // `.reduce(f, init)` → FoldLeft(f, init, xs), using the selected library.
408
446
  if (e.method === "reduce" && args.length === 2) {
409
- return `Std.Collections.Seq.FoldLeft(${args[0]}, ${args[1]}, ${obj})`;
447
+ if (_dafnyLibrary === "stdlib")
448
+ return `Std.Collections.Seq.FoldLeft(${args[0]}, ${args[1]}, ${obj})`;
449
+ needPreamble("SeqFoldLeft");
450
+ return `SeqFoldLeft(${args[0]}, ${args[1]}, ${obj})`;
410
451
  }
411
452
  }
412
453
  // String methods
@@ -932,7 +973,7 @@ function emitDecl(d) {
932
973
  // Strip constraints like (==) from type params — ghost lemmas don't need them
933
974
  const lemmaTP = d.typeParams.length > 0 ? `<${d.typeParams.map(t => t.replace(/\(.*\)/, '')).join(", ")}>` : "";
934
975
  lines.push("");
935
- lines.push(`lemma ${escapeGeneratedName(`${d.name}_ensures`)}${lemmaTP}(${paramList(d.params)})`);
976
+ lines.push(`lemma ${escapeGeneratedName(`${d.name}${ENSURES_LEMMA_SUFFIX}`)}${lemmaTP}(${paramList(d.params)})`);
936
977
  for (const r of d.requires)
937
978
  lines.push(` requires ${emitExpr(r)}`);
938
979
  for (const e of d.ensures)
@@ -1029,6 +1070,11 @@ function needPreamble(key) { _neededPreambles.add(key); }
1029
1070
  /** Effective JS-clamp semantics for `arr.slice(lo, hi)`, resolved from project
1030
1071
  * config plus file directives before emission. */
1031
1072
  let _useSafeSlice = false;
1073
+ // Source of generated collection helpers, selected independently of string semantics.
1074
+ let _dafnyLibrary = DEFAULT_OPTIONS["dafny-library"];
1075
+ // The selected model controls literals, character helpers, and verifier flags.
1076
+ let _stringSemantics = DEFAULT_OPTIONS["string-semantics"];
1077
+ function isUtf16() { return _stringSemantics === "javascript-utf16"; }
1032
1078
  const POW2 = `function Pow2(n: int): int
1033
1079
  requires n >= 0
1034
1080
  decreases n
@@ -1095,6 +1141,25 @@ const SEQ_FILTER_SOME = `function SeqFilterSome<T>(xs: seq<Option<T>>): seq<T>
1095
1141
  if |xs| == 0 then []
1096
1142
  else (if xs[0].Some? then [xs[0].value] else []) + SeqFilterSome(xs[1..])
1097
1143
  }`;
1144
+ const SEQ_FILTER = `function SeqFilter<T(!new)>(p: T -> bool, xs: seq<T>): seq<T>
1145
+ ensures |SeqFilter(p, xs)| <= |xs|
1146
+ ensures forall x :: x in SeqFilter(p, xs) <==> x in xs && p(x)
1147
+ decreases |xs|
1148
+ {
1149
+ if |xs| == 0 then []
1150
+ else (if p(xs[0]) then [xs[0]] else []) + SeqFilter(p, xs[1..])
1151
+ }`;
1152
+ const SEQ_ALL = `predicate SeqAll<T>(xs: seq<T>, p: T -> bool)
1153
+ decreases |xs|
1154
+ {
1155
+ |xs| == 0 || (p(xs[0]) && SeqAll(xs[1..], p))
1156
+ }`;
1157
+ const SEQ_FOLD_LEFT = `function SeqFoldLeft<T, A>(f: (A, T) -> A, init: A, xs: seq<T>): A
1158
+ decreases |xs|
1159
+ {
1160
+ if |xs| == 0 then init
1161
+ else SeqFoldLeft(f, f(init, xs[0]), xs[1..])
1162
+ }`;
1098
1163
  const SEQ_FIND_INDEX = `function SeqFindIndex<T>(s: seq<T>, p: T -> bool): int
1099
1164
  ensures -1 <= SeqFindIndex(s, p) < |s|
1100
1165
  ensures SeqFindIndex(s, p) >= 0 ==> p(s[SeqFindIndex(s, p)])
@@ -1262,15 +1327,16 @@ const SEQ_SORT_BY = `function {:axiom} SeqSortBy<T(==,!new)>(s: seq<T>, cmp: (T,
1262
1327
  // U+0020, and NOT U+0085 (NEL, which is Cc). See
1263
1328
  // https://tc39.es/ecma262/#sec-white-space and
1264
1329
  // https://tc39.es/ecma262/#sec-line-terminators.
1265
- // `\\U{..}` are Dafny char escapes (not JS: the string
1266
- // is emitted verbatim), so the enumeration below is Dafny source, not decoded.
1330
+ // `\\uXXXX` is Dafny's escape form under --unicode-char:false and `\\U{XXXX}`
1331
+ // under :true (each rejects the other); STRING_TRIM_SCALAR derives the latter.
1332
+ // The enumeration below is emitted Dafny source, not a decoded JS string.
1267
1333
  const STRING_TRIM = `predicate IsJSWhitespace(c: char)
1268
1334
  {
1269
- c == '\\U{0009}' || c == '\\U{000A}' || c == '\\U{000B}' || c == '\\U{000C}' || c == '\\U{000D}' ||
1270
- c == '\\U{0020}' || c == '\\U{00A0}' || c == '\\U{1680}' ||
1271
- ('\\U{2000}' <= c <= '\\U{200A}') ||
1272
- c == '\\U{2028}' || c == '\\U{2029}' || c == '\\U{202F}' || c == '\\U{205F}' ||
1273
- c == '\\U{3000}' || c == '\\U{FEFF}'
1335
+ c == '\\u0009' || c == '\\u000A' || c == '\\u000B' || c == '\\u000C' || c == '\\u000D' ||
1336
+ c == '\\u0020' || c == '\\u00A0' || c == '\\u1680' ||
1337
+ ('\\u2000' <= c <= '\\u200A') ||
1338
+ c == '\\u2028' || c == '\\u2029' || c == '\\u202F' || c == '\\u205F' ||
1339
+ c == '\\u3000' || c == '\\uFEFF'
1274
1340
  }
1275
1341
 
1276
1342
  function StringTrimLeft(s: string): string
@@ -1297,6 +1363,9 @@ function StringTrim(s: string): string
1297
1363
  {
1298
1364
  StringTrimRight(StringTrimLeft(s))
1299
1365
  }`;
1366
+ // The same predicate and trims under `--unicode-char:true`, which the
1367
+ // `unicode-scalar` profile verifies under: byte-identical to what was always emitted.
1368
+ const STRING_TRIM_SCALAR = STRING_TRIM.replace(/\\u([0-9A-F]{4})/g, "\\U{$1}");
1300
1369
  const STRING_TO_LOWER = `function StringToLower(s: string): string
1301
1370
  ensures |StringToLower(s)| == |s|
1302
1371
  decreases |s|
@@ -1317,17 +1386,20 @@ const STRING_TO_UPPER = `function StringToUpper(s: string): string
1317
1386
  var upper := if 'a' <= c <= 'z' then (c - 'a' + 'A') as char else c;
1318
1387
  [upper] + StringToUpper(s[1..])
1319
1388
  }`;
1320
- // `String.fromCharCode(n)` — the inverse of `s.charCodeAt(i)`'s `(s[i] as int)`.
1321
- // Dafny's `char` is a Unicode scalar value, so the argument must miss the
1322
- // surrogate range; that is the `requires`, discharged at each call site. The two
1323
- // `ensures` give callers the round-trip law without unfolding the body.
1389
+ // `String.fromCharCode(n)` — the inverse of `s.charCodeAt(i)`'s `(s[i] as int)`
1390
+ // in the UTF-16 code-unit model selected by dafny-commands.ts. LemmaScript
1391
+ // currently admits the direct 16-bit range; JavaScript's wider ToUint16 coercion
1392
+ // remains outside the verified subset.
1324
1393
  const STRING_FROM_CHAR_CODE = `function StringFromCharCode(n: int): string
1325
- requires 0 <= n < 0xD800 || 0xE000 <= n < 0x110000
1394
+ requires 0 <= n < 0x10000
1326
1395
  ensures |StringFromCharCode(n)| == 1
1327
1396
  ensures (StringFromCharCode(n)[0] as int) == n
1328
1397
  {
1329
1398
  [n as char]
1330
1399
  }`;
1400
+ // `unicode-scalar` keeps the scalar range that was always required: a surrogate
1401
+ // is refused by precondition rather than admitted as a code unit.
1402
+ const STRING_FROM_CHAR_CODE_SCALAR = STRING_FROM_CHAR_CODE.replace("requires 0 <= n < 0x10000", "requires 0 <= n < 0xD800 || 0xE000 <= n < 0x110000");
1331
1403
  // `s.repeat(n)` — n copies of s, concatenated. The per-index ensures is stated
1332
1404
  // for the single-character receiver (the common case: padding with one digit).
1333
1405
  const STRING_REPEAT = `function StringRepeat(s: string, n: int): string
@@ -1442,6 +1514,9 @@ const PREAMBLE_CODE = [
1442
1514
  ["SeqIndexOf", SEQ_INDEX_OF],
1443
1515
  ["SeqFindIndex", SEQ_FIND_INDEX],
1444
1516
  ["SeqFindLastIndex", SEQ_FIND_LAST_INDEX],
1517
+ ["SeqFilter", SEQ_FILTER],
1518
+ ["SeqAll", SEQ_ALL],
1519
+ ["SeqFoldLeft", SEQ_FOLD_LEFT],
1445
1520
  ["SeqFilterSome", SEQ_FILTER_SOME],
1446
1521
  ["SeqFind", SEQ_FIND],
1447
1522
  ["SeqFindLast", SEQ_FIND_LAST],
@@ -1452,10 +1527,10 @@ const PREAMBLE_CODE = [
1452
1527
  ["StringSplit", STRING_SPLIT],
1453
1528
  ["SeqSort", SEQ_SORT],
1454
1529
  ["SeqSortBy", SEQ_SORT_BY],
1455
- ["StringTrim", STRING_TRIM],
1530
+ ["StringTrim", () => isUtf16() ? STRING_TRIM : STRING_TRIM_SCALAR],
1456
1531
  ["StringToLower", STRING_TO_LOWER],
1457
1532
  ["StringToUpper", STRING_TO_UPPER],
1458
- ["StringFromCharCode", STRING_FROM_CHAR_CODE],
1533
+ ["StringFromCharCode", () => isUtf16() ? STRING_FROM_CHAR_CODE : STRING_FROM_CHAR_CODE_SCALAR],
1459
1534
  ["StringRepeat", STRING_REPEAT],
1460
1535
  ["NatToString", NAT_TO_STRING],
1461
1536
  ["IntToString", INT_TO_STRING],
@@ -1467,6 +1542,21 @@ const PREAMBLE_CODE = [
1467
1542
  ["Perm", PERM],
1468
1543
  ["SetFromSeq", SET_FROM_SEQ],
1469
1544
  ];
1545
+ /**
1546
+ * The names of the functions, predicates, lemmas and methods declared in Dafny
1547
+ * `text`, in order: a declaration starts its line, may carry modifiers
1548
+ * (`ghost`, `opaque`, …) and attributes (`{:axiom}`), and is never in a comment.
1549
+ */
1550
+ export function declaredNames(text) {
1551
+ const declaration = /^\s*(?:(?:ghost|opaque|static|twostate|least|greatest)\s+)*(?:function|predicate|lemma|method)(?:\s+\{:[^}]*\})*\s+([A-Za-z_][A-Za-z0-9_]*)/gm;
1552
+ return [...text.matchAll(declaration)].map(m => m[1]);
1553
+ }
1554
+ /**
1555
+ * Every function, predicate, lemma and method the preambles declare, so tools reading
1556
+ * Dafny results can tell lsc's own helpers from the user's members. The
1557
+ * profile-dependent entries only change literals, so either variant gives the same names.
1558
+ */
1559
+ export const DAFNY_HELPER_NAMES = new Set(PREAMBLE_CODE.flatMap(([, code]) => declaredNames(typeof code === "function" ? code() : code)));
1470
1560
  // ── Constructor and record helpers ───────────────────────────
1471
1561
  let _recordCtors = new Map();
1472
1562
  let _structureDecls = new Map();
@@ -1582,7 +1672,11 @@ function translatePattern(p) {
1582
1672
  return `${ctorName}(${p.binders.map(escapeName).join(", ")})`;
1583
1673
  }
1584
1674
  export function emitDafnyFile(file, tsFileName, options = DEFAULT_OPTIONS) {
1675
+ // Programmatic callers share the CLI's compatibility checks.
1676
+ options = resolveOptions(options, tsFileName ?? "Dafny emission");
1585
1677
  _useSafeSlice = options["safe-slice"];
1678
+ _stringSemantics = options["string-semantics"];
1679
+ _dafnyLibrary = options["dafny-library"];
1586
1680
  resetDafnyNameCache();
1587
1681
  buildRecordCtorMap(file.decls);
1588
1682
  _neededPreambles.clear();
@@ -1647,10 +1741,13 @@ export function emitDafnyFile(file, tsFileName, options = DEFAULT_OPTIONS) {
1647
1741
  const lines = [];
1648
1742
  if (tsFileName)
1649
1743
  lines.push(`// Generated by lsc from ${tsFileName}`);
1744
+ // Record every UTF-16 selection, including strings introduced by helpers.
1745
+ if (isUtf16())
1746
+ lines.push("// lsc options: string-semantics=javascript-utf16");
1650
1747
  for (const [key, code] of PREAMBLE_CODE) {
1651
1748
  if (_neededPreambles.has(key)) {
1652
1749
  lines.push("");
1653
- lines.push(code);
1750
+ lines.push(typeof code === "function" ? code() : code);
1654
1751
  }
1655
1752
  }
1656
1753
  lines.push(...declLines);
@@ -55,6 +55,8 @@ let _currentSourceFile = null;
55
55
  let _inFunctionExtraction = false;
56
56
  /** Effective options for the current extraction. Reset at extractModule entry. */
57
57
  let _extractOptions = DEFAULT_OPTIONS;
58
+ /** The CLI validates source options before copying a cross-file contract. */
59
+ let _validateDependency = () => { };
58
60
  /** Counter for synthetic names used by let-statement array destructuring
59
61
  * when the initializer isn't a bare variable (single-eval temp). */
60
62
  let _destrCounter = 0;
@@ -121,6 +123,8 @@ function detectCrossFileExtern(callee, sourceFile, sigTypesOut) {
121
123
  const sig = callee.getType().getCallSignatures()[0];
122
124
  if (!sig)
123
125
  return null;
126
+ // Includes global declarations selected by TypeScript without an import edge.
127
+ _validateDependency(externalDecl.getSourceFile());
124
128
  // Generic type parameters (e.g. `step<S, A>`). ts-morph reports param/return
125
129
  // types in the callee's own type-parameter namespace, so these names match
126
130
  // what `params`/`returnType` reference — declare them on the emitted axiom.
@@ -381,22 +385,22 @@ function extractExpr(node) {
381
385
  // Always push the head, even when empty: a leading string literal anchors the
382
386
  // whole chain as string-typed so each interpolated value is stringified (not
383
387
  // added numerically — `${a}${b}` is concatenation, not `a + b`).
384
- parts.push({ kind: "str", value: node.getHead().getLiteralText() });
388
+ parts.push(stringLiteral(node.getHead().getLiteralText(), node));
385
389
  for (const span of node.getTemplateSpans()) {
386
390
  parts.push(extractExpr(span.getExpression()));
387
391
  const text = span.getLiteral().getLiteralText();
388
392
  if (text)
389
- parts.push({ kind: "str", value: text });
393
+ parts.push(stringLiteral(text, span));
390
394
  }
391
395
  return parts.reduce((left, right) => ({ kind: "binop", op: "+", left, right }));
392
396
  }
393
397
  // No-substitution template literal: `hello` → "hello"
394
398
  if (Node.isNoSubstitutionTemplateLiteral(node)) {
395
- return { kind: "str", value: node.getLiteralText() };
399
+ return stringLiteral(node.getLiteralText(), node);
396
400
  }
397
401
  // String literal
398
402
  if (Node.isStringLiteral(node)) {
399
- return { kind: "str", value: node.getLiteralValue() };
403
+ return stringLiteral(node.getLiteralValue(), node);
400
404
  }
401
405
  // Boolean literals: true, false
402
406
  if (Node.isTrueLiteral(node))
@@ -811,6 +815,40 @@ function hasExternModeAnnotation(node, keyword, parentStmt) {
811
815
  return !!statement && statement.getLeadingCommentRanges()
812
816
  .some(r => r.getText().trim() === `//@ ${keyword}`);
813
817
  }
818
+ /** The first lone surrogate code unit in `value`, or -1. */
819
+ function findLoneSurrogate(value) {
820
+ for (let i = 0; i < value.length; i++) {
821
+ const unit = value.charCodeAt(i);
822
+ if (unit >= 0xD800 && unit <= 0xDBFF) {
823
+ const next = value.charCodeAt(i + 1);
824
+ if (next >= 0xDC00 && next <= 0xDFFF) {
825
+ i++;
826
+ continue;
827
+ }
828
+ return unit;
829
+ }
830
+ if (unit >= 0xDC00 && unit <= 0xDFFF)
831
+ return unit;
832
+ }
833
+ return -1;
834
+ }
835
+ /** A source string literal, admitted only if the selected string profile can
836
+ * represent it (DESIGN_STRINGS.md §3). Under `unicode-scalar` a lone surrogate
837
+ * has no Dafny value — and Node's UTF-8 writer would silently replace it on
838
+ * the way out — so it is refused here with the source line instead. */
839
+ function stringLiteral(value, node) {
840
+ if (_extractOptions["string-semantics"] === "unicode-scalar") {
841
+ const lone = findLoneSurrogate(value);
842
+ if (lone >= 0) {
843
+ const file = node.getSourceFile();
844
+ const { line } = file.getLineAndColumnAtPos(node.getStart());
845
+ throw new Error(`${file.getFilePath()}:${line}: string literal contains an unpaired surrogate ` +
846
+ `U+${lone.toString(16).toUpperCase()}, which "string-semantics": "unicode-scalar" cannot ` +
847
+ `represent; select string-semantics=javascript-utf16 and dafny-library=local in lemmascript.json or //@ option directives`);
848
+ }
849
+ }
850
+ return { kind: "str", value };
851
+ }
814
852
  function externIsImpure(node, name, parentStmt) {
815
853
  const pure = hasExternModeAnnotation(node, "pure", parentStmt);
816
854
  const impure = hasExternModeAnnotation(node, "impure", parentStmt);
@@ -2066,8 +2104,9 @@ function extractFunctionInner(fn, parentAnnotations) {
2066
2104
  };
2067
2105
  }
2068
2106
  // ── Module extraction ────────────────────────────────────────
2069
- export function extractModule(sourceFile, options = DEFAULT_OPTIONS) {
2107
+ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDependency = () => { }) {
2070
2108
  _extractOptions = options;
2109
+ _validateDependency = validateDependency;
2071
2110
  // Seed the fresh-name check (names.ts) before anything mints: every
2072
2111
  // Identifier token in the module, a deliberate over-approximation.
2073
2112
  setUserNames(new Set(sourceFile.getDescendantsOfKind(SyntaxKind.Identifier).map(i => i.getText())));
@@ -2,7 +2,7 @@
2
2
  * Lean backend commands: gen, check.
3
3
  */
4
4
  import { existsSync, writeFileSync } from "fs";
5
- import { execSync } from "child_process";
5
+ import { execFileSync } from "child_process";
6
6
  import path from "path";
7
7
  export function leanGen(typesPath, defPath, typesText, defText) {
8
8
  if (typesPath && typesText) {
@@ -12,21 +12,36 @@ export function leanGen(typesPath, defPath, typesText, defText) {
12
12
  writeFileSync(defPath, defText);
13
13
  console.log(`Generated: ${defPath}`);
14
14
  }
15
- export function leanCheck(dir, base) {
16
- let lakeDir = dir;
17
- while (lakeDir !== path.dirname(lakeDir)) {
18
- if (existsSync(path.join(lakeDir, "lakefile.lean")))
19
- break;
20
- lakeDir = path.dirname(lakeDir);
15
+ /** Find the nearest ancestor containing either supported Lake configuration. */
16
+ export function findLakeProjectRoot(dir) {
17
+ let candidate = path.resolve(dir);
18
+ while (true) {
19
+ if (existsSync(path.join(candidate, "lakefile.lean")) ||
20
+ existsSync(path.join(candidate, "lakefile.toml"))) {
21
+ return candidate;
22
+ }
23
+ const parent = path.dirname(candidate);
24
+ // Check the filesystem root above before terminating the search.
25
+ if (parent === candidate)
26
+ return null;
27
+ candidate = parent;
21
28
  }
29
+ }
30
+ export function leanCheck(dir, base) {
22
31
  const proofPath = path.join(dir, `${base}.proof.lean`);
23
32
  if (!existsSync(proofPath)) {
24
33
  console.error(`No proof file: ${proofPath}`);
25
34
  return false;
26
35
  }
36
+ const lakeDir = findLakeProjectRoot(dir);
37
+ if (lakeDir === null) {
38
+ console.error(`No Lake project found for ${path.resolve(dir)}: expected lakefile.lean or lakefile.toml ` +
39
+ "in this directory or an ancestor. Run this check inside a Lake project; lake was not started.");
40
+ return false;
41
+ }
27
42
  console.log("Running lake build...");
28
43
  try {
29
- execSync(`lake build`, { cwd: lakeDir, stdio: "inherit" });
44
+ execFileSync("lake", ["build"], { cwd: lakeDir, stdio: "inherit" });
30
45
  return true;
31
46
  }
32
47
  catch {
@@ -5,7 +5,7 @@
5
5
  * and support-import selection.
6
6
  */
7
7
  import { anyExpr, usesNameInDecl, patternBinders } from "./ir.js";
8
- import { freshNameWhere } from "./names.js";
8
+ import { freshName, freshNameWhere } from "./names.js";
9
9
  // ── Ty → Lean type string ──────────────────────────────────
10
10
  function tyToLean(ty) {
11
11
  switch (ty.kind) {
@@ -90,9 +90,11 @@ const LEAN_KEYWORDS = new Set([
90
90
  // `res`, but primed (e.g. `res'`) when a module identifier is named `res` — set
91
91
  // by the method case. `\result` in an ensures/body must use the same name.
92
92
  let _resultName = "res";
93
+ let _invariantIndex = 0;
94
+ let _rangeIndex = 0;
93
95
  function escapeName(name) {
94
96
  // \result is carried through the IR as the var name "\\result"; render it
95
- // as the method's return-value identifier (matches `return (res : T)`).
97
+ // as the method's return-value identifier (matches `returns (res : T)`).
96
98
  if (name === "\\result")
97
99
  return _resultName;
98
100
  return LEAN_KEYWORDS.has(name) ? `«${name}»` : name;
@@ -351,8 +353,8 @@ function emitExpr(e, parentPrec) {
351
353
  const twos = ".2".repeat(e.index);
352
354
  return e.index === e.arity - 1 ? `${obj}${twos}` : `${obj}${twos}.1`;
353
355
  }
354
- case "emptyMap": return `Std.HashMap.empty`;
355
- case "emptySet": return `Std.HashSet.empty`;
356
+ case "emptyMap": return `∅`;
357
+ case "emptySet": return `∅`;
356
358
  case "default": return `(default : ${tyToLean(e.type)})`;
357
359
  case "methodCall": {
358
360
  const obj = emitExpr(e.obj);
@@ -671,26 +673,33 @@ function emitStmt(s, indent) {
671
673
  const prevBoolCtx = _boolCtx;
672
674
  _boolCtx = false;
673
675
  for (const inv of s.invariants)
674
- lines.push(`${pad} invariant ${emitExpr(inv)}`);
675
- // `done_with True` (the auto-supplied fact for breaking loops) is a Prop;
676
- // the bool literal would need a coercion, so emit the Prop `True` directly.
677
- if (s.doneWith)
678
- lines.push(`${pad} done_with ${s.doneWith.kind === "bool" && s.doneWith.value ? "True" : emitExpr(s.doneWith)}`);
676
+ lines.push(`${pad} invariant invariant_${++_invariantIndex}: (${emitExpr(inv)} : Prop)`);
679
677
  if (s.decreasing)
680
678
  lines.push(`${pad} decreasing ${emitExpr(s.decreasing)}`);
679
+ if (s.doneWith)
680
+ lines.push(`${pad} done_with (${emitExpr(s.doneWith)} : Prop)`);
681
681
  _boolCtx = prevBoolCtx;
682
682
  lines.push(`${pad}do`);
683
683
  lines.push(emitStmts(s.body, indent + 1));
684
684
  return lines.join("\n");
685
685
  }
686
686
  case "forin": {
687
- const lines = [`${pad}for ${s.idx} in [:${emitExpr(s.bound)}]`];
687
+ // Velvet 2 needs an explicit exit assertion when invariants use the cursor.
688
+ // Preserve the range endpoint used by the old rule, including on `break`.
689
+ const stop = freshName(`_rangeStop${_rangeIndex++}`);
690
+ const idx = escapeName(s.idx);
691
+ const lines = [`${pad}let ${stop} : Nat := ${emitExpr(s.bound)}`,
692
+ `${pad}for ${idx} in [:${stop}]`];
688
693
  const prevBoolCtx = _boolCtx;
689
- _boolCtx = false; // invariants are Prop
690
- for (const inv of s.invariants)
691
- lines.push(`${pad} invariant ${emitExpr(inv)}`);
694
+ _boolCtx = false;
695
+ const invariants = s.invariants.map(inv => `(${emitExpr(inv)} : Prop)`);
696
+ for (const inv of invariants)
697
+ lines.push(`${pad} invariant invariant_${++_invariantIndex}: ${inv}`);
698
+ if (invariants.length > 0)
699
+ lines.push(`${pad} done_with (let ${idx} : Nat := ${stop}; ${invariants.join(" ∧ ")})`);
692
700
  _boolCtx = prevBoolCtx;
693
701
  lines.push(`${pad}do`);
702
+ lines.push(`${pad} let ${idx} : Nat := ${idx}`);
694
703
  lines.push(emitStmts(s.body, indent + 1));
695
704
  return lines.join("\n");
696
705
  }
@@ -815,11 +824,11 @@ function emitDecl(d) {
815
824
  // fields, unrelated params), so a module-wide check would prime spuriously.
816
825
  _resultName = freshNameWhere("res", n => d.params.some(p => escapeName(p.name) === n) ||
817
826
  usesNameInDecl(d.requires, d.ensures, d.body, n));
818
- const lines = [`method ${d.name} ${params} return (${_resultName} : ${tyToLean(d.returnType)})`];
819
- for (const r of d.requires)
820
- lines.push(` require ${emitExpr(r)}`);
821
- for (const e of d.ensures)
822
- lines.push(` ensures ${emitExpr(e)}`);
827
+ _invariantIndex = 0;
828
+ _rangeIndex = 0;
829
+ const lines = [`method ${d.name} ${params} returns (${_resultName} : ${tyToLean(d.returnType)})`];
830
+ d.requires.forEach((r, i) => lines.push(` requires require_${i + 1}: (${emitExpr(r)} : Prop)`));
831
+ d.ensures.forEach((e, i) => lines.push(` ensures ensures_${i + 1}: (${emitExpr(e)} : Prop)`));
823
832
  lines.push(" do");
824
833
  _boolCtx = true;
825
834
  lines.push(emitStmts(d.body, 2));