lemmascript 0.6.4 → 0.6.6

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,17 +442,22 @@ 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
413
454
  if (ty === "string") {
414
455
  if (e.method === "indexOf") {
415
456
  needPreamble("StringIndexOf");
416
- if (args.length === 2)
417
- return `StringIndexOfFrom(${obj}, ${args[0]}, ${args[1]})`;
457
+ if (args.length === 2) {
458
+ needPreamble("StringSearchPosition");
459
+ return `StringIndexOfFrom(${obj}, ${args[0]}, StringSearchPosition(${obj}, ${args[1]}))`;
460
+ }
418
461
  return `StringIndexOf(${obj}, ${args[0]})`;
419
462
  }
420
463
  if (e.method === "split") {
@@ -443,8 +486,14 @@ function emitExpr(e) {
443
486
  return `${obj}[${args[0]}..]`;
444
487
  return `${obj}[${args[0]}..${args[1]}]`;
445
488
  }
446
- if (e.method === "endsWith")
489
+ if (e.method === "endsWith") {
490
+ if (args.length === 2) {
491
+ needPreamble("StringSearchPosition");
492
+ needPreamble("StringEndsWithAt");
493
+ return `StringEndsWithAt(${obj}, ${args[0]}, ${args[1]})`;
494
+ }
447
495
  return `(|${obj}| >= |${args[0]}| && ${obj}[|${obj}|-|${args[0]}|..] == ${args[0]})`;
496
+ }
448
497
  if (e.method === "trim") {
449
498
  needPreamble("StringTrim");
450
499
  return `StringTrim(${obj})`;
@@ -467,10 +516,20 @@ function emitExpr(e) {
467
516
  }
468
517
  if (e.method === "includes") {
469
518
  needPreamble("StringIndexOf");
519
+ if (args.length === 2) {
520
+ needPreamble("StringSearchPosition");
521
+ return `(StringIndexOfFrom(${obj}, ${args[0]}, StringSearchPosition(${obj}, ${args[1]})) >= 0)`;
522
+ }
470
523
  return `(StringIndexOf(${obj}, ${args[0]}) >= 0)`;
471
524
  }
472
- if (e.method === "startsWith")
525
+ if (e.method === "startsWith") {
526
+ if (args.length === 2) {
527
+ needPreamble("StringSearchPosition");
528
+ needPreamble("StringStartsWithAt");
529
+ return `StringStartsWithAt(${obj}, ${args[0]}, ${args[1]})`;
530
+ }
473
531
  return `(|${obj}| >= |${args[0]}| && ${obj}[..|${args[0]}|] == ${args[0]})`;
532
+ }
474
533
  if (e.method === "charCodeAt")
475
534
  return `(${obj}[${args[0]}] as int)`;
476
535
  if (e.method === "repeat") {
@@ -932,7 +991,7 @@ function emitDecl(d) {
932
991
  // Strip constraints like (==) from type params — ghost lemmas don't need them
933
992
  const lemmaTP = d.typeParams.length > 0 ? `<${d.typeParams.map(t => t.replace(/\(.*\)/, '')).join(", ")}>` : "";
934
993
  lines.push("");
935
- lines.push(`lemma ${escapeGeneratedName(`${d.name}_ensures`)}${lemmaTP}(${paramList(d.params)})`);
994
+ lines.push(`lemma ${escapeGeneratedName(`${d.name}${ENSURES_LEMMA_SUFFIX}`)}${lemmaTP}(${paramList(d.params)})`);
936
995
  for (const r of d.requires)
937
996
  lines.push(` requires ${emitExpr(r)}`);
938
997
  for (const e of d.ensures)
@@ -1029,6 +1088,11 @@ function needPreamble(key) { _neededPreambles.add(key); }
1029
1088
  /** Effective JS-clamp semantics for `arr.slice(lo, hi)`, resolved from project
1030
1089
  * config plus file directives before emission. */
1031
1090
  let _useSafeSlice = false;
1091
+ // Source of generated collection helpers, selected independently of string semantics.
1092
+ let _dafnyLibrary = DEFAULT_OPTIONS["dafny-library"];
1093
+ // The selected model controls literals, character helpers, and verifier flags.
1094
+ let _stringSemantics = DEFAULT_OPTIONS["string-semantics"];
1095
+ function isUtf16() { return _stringSemantics === "javascript-utf16"; }
1032
1096
  const POW2 = `function Pow2(n: int): int
1033
1097
  requires n >= 0
1034
1098
  decreases n
@@ -1095,6 +1159,25 @@ const SEQ_FILTER_SOME = `function SeqFilterSome<T>(xs: seq<Option<T>>): seq<T>
1095
1159
  if |xs| == 0 then []
1096
1160
  else (if xs[0].Some? then [xs[0].value] else []) + SeqFilterSome(xs[1..])
1097
1161
  }`;
1162
+ const SEQ_FILTER = `function SeqFilter<T(!new)>(p: T -> bool, xs: seq<T>): seq<T>
1163
+ ensures |SeqFilter(p, xs)| <= |xs|
1164
+ ensures forall x :: x in SeqFilter(p, xs) <==> x in xs && p(x)
1165
+ decreases |xs|
1166
+ {
1167
+ if |xs| == 0 then []
1168
+ else (if p(xs[0]) then [xs[0]] else []) + SeqFilter(p, xs[1..])
1169
+ }`;
1170
+ const SEQ_ALL = `predicate SeqAll<T>(xs: seq<T>, p: T -> bool)
1171
+ decreases |xs|
1172
+ {
1173
+ |xs| == 0 || (p(xs[0]) && SeqAll(xs[1..], p))
1174
+ }`;
1175
+ const SEQ_FOLD_LEFT = `function SeqFoldLeft<T, A>(f: (A, T) -> A, init: A, xs: seq<T>): A
1176
+ decreases |xs|
1177
+ {
1178
+ if |xs| == 0 then init
1179
+ else SeqFoldLeft(f, f(init, xs[0]), xs[1..])
1180
+ }`;
1098
1181
  const SEQ_FIND_INDEX = `function SeqFindIndex<T>(s: seq<T>, p: T -> bool): int
1099
1182
  ensures -1 <= SeqFindIndex(s, p) < |s|
1100
1183
  ensures SeqFindIndex(s, p) >= 0 ==> p(s[SeqFindIndex(s, p)])
@@ -1206,6 +1289,21 @@ function SafeSlice<T>(s: seq<T>, lo: int, hi: int): seq<T>
1206
1289
  var hi' := NormalizeSliceIndex(|s|, hi);
1207
1290
  if hi' < lo' then [] else s[lo'..hi']
1208
1291
  }`;
1292
+ const STRING_SEARCH_POSITION = `function StringSearchPosition(s: string, position: int): nat
1293
+ ensures StringSearchPosition(s, position) <= |s|
1294
+ {
1295
+ if position < 0 then 0 else if position > |s| then |s| else position
1296
+ }`;
1297
+ const STRING_STARTS_WITH_AT = `function StringStartsWithAt(s: string, sub: string, position: int): bool
1298
+ {
1299
+ var start := StringSearchPosition(s, position);
1300
+ |sub| <= |s| - start && s[start..start + |sub|] == sub
1301
+ }`;
1302
+ const STRING_ENDS_WITH_AT = `function StringEndsWithAt(s: string, sub: string, position: int): bool
1303
+ {
1304
+ var end := StringSearchPosition(s, position);
1305
+ |sub| <= end && s[end - |sub|..end] == sub
1306
+ }`;
1209
1307
  const STRING_INDEX_OF = `function StringIndexOf(s: string, sub: string): int
1210
1308
  ensures StringIndexOf(s, sub) == -1
1211
1309
  || (0 <= StringIndexOf(s, sub) <= |s| - |sub| && s[StringIndexOf(s, sub)..StringIndexOf(s, sub) + |sub|] == sub)
@@ -1262,15 +1360,16 @@ const SEQ_SORT_BY = `function {:axiom} SeqSortBy<T(==,!new)>(s: seq<T>, cmp: (T,
1262
1360
  // U+0020, and NOT U+0085 (NEL, which is Cc). See
1263
1361
  // https://tc39.es/ecma262/#sec-white-space and
1264
1362
  // 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.
1363
+ // `\\uXXXX` is Dafny's escape form under --unicode-char:false and `\\U{XXXX}`
1364
+ // under :true (each rejects the other); STRING_TRIM_SCALAR derives the latter.
1365
+ // The enumeration below is emitted Dafny source, not a decoded JS string.
1267
1366
  const STRING_TRIM = `predicate IsJSWhitespace(c: char)
1268
1367
  {
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}'
1368
+ c == '\\u0009' || c == '\\u000A' || c == '\\u000B' || c == '\\u000C' || c == '\\u000D' ||
1369
+ c == '\\u0020' || c == '\\u00A0' || c == '\\u1680' ||
1370
+ ('\\u2000' <= c <= '\\u200A') ||
1371
+ c == '\\u2028' || c == '\\u2029' || c == '\\u202F' || c == '\\u205F' ||
1372
+ c == '\\u3000' || c == '\\uFEFF'
1274
1373
  }
1275
1374
 
1276
1375
  function StringTrimLeft(s: string): string
@@ -1297,6 +1396,9 @@ function StringTrim(s: string): string
1297
1396
  {
1298
1397
  StringTrimRight(StringTrimLeft(s))
1299
1398
  }`;
1399
+ // The same predicate and trims under `--unicode-char:true`, which the
1400
+ // `unicode-scalar` profile verifies under: byte-identical to what was always emitted.
1401
+ const STRING_TRIM_SCALAR = STRING_TRIM.replace(/\\u([0-9A-F]{4})/g, "\\U{$1}");
1300
1402
  const STRING_TO_LOWER = `function StringToLower(s: string): string
1301
1403
  ensures |StringToLower(s)| == |s|
1302
1404
  decreases |s|
@@ -1317,17 +1419,20 @@ const STRING_TO_UPPER = `function StringToUpper(s: string): string
1317
1419
  var upper := if 'a' <= c <= 'z' then (c - 'a' + 'A') as char else c;
1318
1420
  [upper] + StringToUpper(s[1..])
1319
1421
  }`;
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.
1422
+ // `String.fromCharCode(n)` — the inverse of `s.charCodeAt(i)`'s `(s[i] as int)`
1423
+ // in the UTF-16 code-unit model selected by dafny-commands.ts. LemmaScript
1424
+ // currently admits the direct 16-bit range; JavaScript's wider ToUint16 coercion
1425
+ // remains outside the verified subset.
1324
1426
  const STRING_FROM_CHAR_CODE = `function StringFromCharCode(n: int): string
1325
- requires 0 <= n < 0xD800 || 0xE000 <= n < 0x110000
1427
+ requires 0 <= n < 0x10000
1326
1428
  ensures |StringFromCharCode(n)| == 1
1327
1429
  ensures (StringFromCharCode(n)[0] as int) == n
1328
1430
  {
1329
1431
  [n as char]
1330
1432
  }`;
1433
+ // `unicode-scalar` keeps the scalar range that was always required: a surrogate
1434
+ // is refused by precondition rather than admitted as a code unit.
1435
+ const STRING_FROM_CHAR_CODE_SCALAR = STRING_FROM_CHAR_CODE.replace("requires 0 <= n < 0x10000", "requires 0 <= n < 0xD800 || 0xE000 <= n < 0x110000");
1331
1436
  // `s.repeat(n)` — n copies of s, concatenated. The per-index ensures is stated
1332
1437
  // for the single-character receiver (the common case: padding with one digit).
1333
1438
  const STRING_REPEAT = `function StringRepeat(s: string, n: int): string
@@ -1442,6 +1547,9 @@ const PREAMBLE_CODE = [
1442
1547
  ["SeqIndexOf", SEQ_INDEX_OF],
1443
1548
  ["SeqFindIndex", SEQ_FIND_INDEX],
1444
1549
  ["SeqFindLastIndex", SEQ_FIND_LAST_INDEX],
1550
+ ["SeqFilter", SEQ_FILTER],
1551
+ ["SeqAll", SEQ_ALL],
1552
+ ["SeqFoldLeft", SEQ_FOLD_LEFT],
1445
1553
  ["SeqFilterSome", SEQ_FILTER_SOME],
1446
1554
  ["SeqFind", SEQ_FIND],
1447
1555
  ["SeqFindLast", SEQ_FIND_LAST],
@@ -1449,13 +1557,16 @@ const PREAMBLE_CODE = [
1449
1557
  ["SeqJoin", SEQ_JOIN],
1450
1558
  ["SafeSlice", SAFE_SLICE],
1451
1559
  ["StringIndexOf", STRING_INDEX_OF],
1560
+ ["StringSearchPosition", STRING_SEARCH_POSITION],
1561
+ ["StringStartsWithAt", STRING_STARTS_WITH_AT],
1562
+ ["StringEndsWithAt", STRING_ENDS_WITH_AT],
1452
1563
  ["StringSplit", STRING_SPLIT],
1453
1564
  ["SeqSort", SEQ_SORT],
1454
1565
  ["SeqSortBy", SEQ_SORT_BY],
1455
- ["StringTrim", STRING_TRIM],
1566
+ ["StringTrim", () => isUtf16() ? STRING_TRIM : STRING_TRIM_SCALAR],
1456
1567
  ["StringToLower", STRING_TO_LOWER],
1457
1568
  ["StringToUpper", STRING_TO_UPPER],
1458
- ["StringFromCharCode", STRING_FROM_CHAR_CODE],
1569
+ ["StringFromCharCode", () => isUtf16() ? STRING_FROM_CHAR_CODE : STRING_FROM_CHAR_CODE_SCALAR],
1459
1570
  ["StringRepeat", STRING_REPEAT],
1460
1571
  ["NatToString", NAT_TO_STRING],
1461
1572
  ["IntToString", INT_TO_STRING],
@@ -1467,6 +1578,21 @@ const PREAMBLE_CODE = [
1467
1578
  ["Perm", PERM],
1468
1579
  ["SetFromSeq", SET_FROM_SEQ],
1469
1580
  ];
1581
+ /**
1582
+ * The names of the functions, predicates, lemmas and methods declared in Dafny
1583
+ * `text`, in order: a declaration starts its line, may carry modifiers
1584
+ * (`ghost`, `opaque`, …) and attributes (`{:axiom}`), and is never in a comment.
1585
+ */
1586
+ export function declaredNames(text) {
1587
+ const declaration = /^\s*(?:(?:ghost|opaque|static|twostate|least|greatest)\s+)*(?:function|predicate|lemma|method)(?:\s+\{:[^}]*\})*\s+([A-Za-z_][A-Za-z0-9_]*)/gm;
1588
+ return [...text.matchAll(declaration)].map(m => m[1]);
1589
+ }
1590
+ /**
1591
+ * Every function, predicate, lemma and method the preambles declare, so tools reading
1592
+ * Dafny results can tell lsc's own helpers from the user's members. The
1593
+ * profile-dependent entries only change literals, so either variant gives the same names.
1594
+ */
1595
+ export const DAFNY_HELPER_NAMES = new Set(PREAMBLE_CODE.flatMap(([, code]) => declaredNames(typeof code === "function" ? code() : code)));
1470
1596
  // ── Constructor and record helpers ───────────────────────────
1471
1597
  let _recordCtors = new Map();
1472
1598
  let _structureDecls = new Map();
@@ -1582,7 +1708,11 @@ function translatePattern(p) {
1582
1708
  return `${ctorName}(${p.binders.map(escapeName).join(", ")})`;
1583
1709
  }
1584
1710
  export function emitDafnyFile(file, tsFileName, options = DEFAULT_OPTIONS) {
1711
+ // Programmatic callers share the CLI's compatibility checks.
1712
+ options = resolveOptions(options, tsFileName ?? "Dafny emission");
1585
1713
  _useSafeSlice = options["safe-slice"];
1714
+ _stringSemantics = options["string-semantics"];
1715
+ _dafnyLibrary = options["dafny-library"];
1586
1716
  resetDafnyNameCache();
1587
1717
  buildRecordCtorMap(file.decls);
1588
1718
  _neededPreambles.clear();
@@ -1647,10 +1777,13 @@ export function emitDafnyFile(file, tsFileName, options = DEFAULT_OPTIONS) {
1647
1777
  const lines = [];
1648
1778
  if (tsFileName)
1649
1779
  lines.push(`// Generated by lsc from ${tsFileName}`);
1780
+ // Record every UTF-16 selection, including strings introduced by helpers.
1781
+ if (isUtf16())
1782
+ lines.push("// lsc options: string-semantics=javascript-utf16");
1650
1783
  for (const [key, code] of PREAMBLE_CODE) {
1651
1784
  if (_neededPreambles.has(key)) {
1652
1785
  lines.push("");
1653
- lines.push(code);
1786
+ lines.push(typeof code === "function" ? code() : code);
1654
1787
  }
1655
1788
  }
1656
1789
  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())));
@@ -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;
@@ -276,8 +278,11 @@ function emitMethodCall(tyKind, method, monadic, obj, args) {
276
278
  // String methods
277
279
  if (tyKind === "string") {
278
280
  _needsJSString = true;
279
- if (method === "indexOf")
281
+ if (method === "indexOf") {
282
+ if (args.length !== 1)
283
+ throw new Error("Lean string.indexOf does not support a position argument");
280
284
  return `JSString.indexOf ${obj} ${args[0]}`;
285
+ }
281
286
  if (method === "slice")
282
287
  return `JSString.slice ${obj} ${args[0]} ${args[1]}`;
283
288
  }
@@ -351,8 +356,8 @@ function emitExpr(e, parentPrec) {
351
356
  const twos = ".2".repeat(e.index);
352
357
  return e.index === e.arity - 1 ? `${obj}${twos}` : `${obj}${twos}.1`;
353
358
  }
354
- case "emptyMap": return `Std.HashMap.empty`;
355
- case "emptySet": return `Std.HashSet.empty`;
359
+ case "emptyMap": return `∅`;
360
+ case "emptySet": return `∅`;
356
361
  case "default": return `(default : ${tyToLean(e.type)})`;
357
362
  case "methodCall": {
358
363
  const obj = emitExpr(e.obj);
@@ -671,26 +676,33 @@ function emitStmt(s, indent) {
671
676
  const prevBoolCtx = _boolCtx;
672
677
  _boolCtx = false;
673
678
  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)}`);
679
+ lines.push(`${pad} invariant invariant_${++_invariantIndex}: (${emitExpr(inv)} : Prop)`);
679
680
  if (s.decreasing)
680
681
  lines.push(`${pad} decreasing ${emitExpr(s.decreasing)}`);
682
+ if (s.doneWith)
683
+ lines.push(`${pad} done_with (${emitExpr(s.doneWith)} : Prop)`);
681
684
  _boolCtx = prevBoolCtx;
682
685
  lines.push(`${pad}do`);
683
686
  lines.push(emitStmts(s.body, indent + 1));
684
687
  return lines.join("\n");
685
688
  }
686
689
  case "forin": {
687
- const lines = [`${pad}for ${s.idx} in [:${emitExpr(s.bound)}]`];
690
+ // Velvet 2 needs an explicit exit assertion when invariants use the cursor.
691
+ // Preserve the range endpoint used by the old rule, including on `break`.
692
+ const stop = freshName(`_rangeStop${_rangeIndex++}`);
693
+ const idx = escapeName(s.idx);
694
+ const lines = [`${pad}let ${stop} : Nat := ${emitExpr(s.bound)}`,
695
+ `${pad}for ${idx} in [:${stop}]`];
688
696
  const prevBoolCtx = _boolCtx;
689
- _boolCtx = false; // invariants are Prop
690
- for (const inv of s.invariants)
691
- lines.push(`${pad} invariant ${emitExpr(inv)}`);
697
+ _boolCtx = false;
698
+ const invariants = s.invariants.map(inv => `(${emitExpr(inv)} : Prop)`);
699
+ for (const inv of invariants)
700
+ lines.push(`${pad} invariant invariant_${++_invariantIndex}: ${inv}`);
701
+ if (invariants.length > 0)
702
+ lines.push(`${pad} done_with (let ${idx} : Nat := ${stop}; ${invariants.join(" ∧ ")})`);
692
703
  _boolCtx = prevBoolCtx;
693
704
  lines.push(`${pad}do`);
705
+ lines.push(`${pad} let ${idx} : Nat := ${idx}`);
694
706
  lines.push(emitStmts(s.body, indent + 1));
695
707
  return lines.join("\n");
696
708
  }
@@ -815,11 +827,11 @@ function emitDecl(d) {
815
827
  // fields, unrelated params), so a module-wide check would prime spuriously.
816
828
  _resultName = freshNameWhere("res", n => d.params.some(p => escapeName(p.name) === n) ||
817
829
  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)}`);
830
+ _invariantIndex = 0;
831
+ _rangeIndex = 0;
832
+ const lines = [`method ${d.name} ${params} returns (${_resultName} : ${tyToLean(d.returnType)})`];
833
+ d.requires.forEach((r, i) => lines.push(` requires require_${i + 1}: (${emitExpr(r)} : Prop)`));
834
+ d.ensures.forEach((e, i) => lines.push(` ensures ensures_${i + 1}: (${emitExpr(e)} : Prop)`));
823
835
  lines.push(" do");
824
836
  _boolCtx = true;
825
837
  lines.push(emitStmts(d.body, 2));