lemmascript 0.6.7 → 0.6.9

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/README.md CHANGED
@@ -97,6 +97,16 @@ lsc gen --backend=lean src/myModule.ts
97
97
  lake build
98
98
  ```
99
99
 
100
+ ## Sub-packages
101
+
102
+ ### Claimcheck
103
+
104
+ `lsc claimcheck` forwards to [lemmascript-claimcheck](https://github.com/midspiral/lemmascript-claimcheck) to sanity check the natural language `//@ contract` against the formal specifications.
105
+
106
+ ### Runtime precondition checks
107
+
108
+ `lsc guard` forwards to [lemmascript-guard](https://github.com/midspiral/lemmascript-guard) to generate a sibling `*.guarded.ts` module that checks `//@ requires` at runtime. Import its wrappers at application boundaries.
109
+
100
110
  ## Continuous Integration
101
111
 
102
112
  LemmaScript ships a **reusable GitHub Actions workflow** that regenerates your artifacts, verifies them, and fails the build if any committed generated file is out of date. Call it from your own repo's workflow:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lemmascript",
3
- "version": "0.6.7",
3
+ "version": "0.6.9",
4
4
  "description": "A verification toolchain for TypeScript — generates Lean 4 or Dafny from annotated TS",
5
5
  "type": "module",
6
6
  "engines": {
@@ -42,5 +42,8 @@
42
42
  "lean4",
43
43
  "dafny",
44
44
  "formal-methods"
45
- ]
45
+ ],
46
+ "optionalDependencies": {
47
+ "lemmascript-guard": "^0.1.0"
48
+ }
46
49
  }
@@ -43,22 +43,22 @@ export const BUILTINS = {
43
43
  "array.sort": { ret: self, pure: false,
44
44
  hof: { shape: "comparator" } },
45
45
  "array.filter": { ret: self, pure: false,
46
- hof: { shape: "unary" } },
46
+ hof: { shape: "element" } },
47
47
  "array.every": { ret: BOOL, pure: false,
48
- hof: { shape: "unary" } },
48
+ hof: { shape: "element" } },
49
49
  "array.some": { ret: BOOL, pure: false,
50
- hof: { shape: "unary" } },
50
+ hof: { shape: "element" } },
51
51
  "array.reduce": { pure: false,
52
52
  hof: { shape: "reduce" },
53
53
  ret: (_objTy, args) => args.length === 2 ? args[1].ty : UNKNOWN },
54
54
  "array.find": { ret: optElem, pure: false,
55
- hof: { shape: "unary" } },
55
+ hof: { shape: "element" } },
56
56
  "array.findLast": { ret: optElem, pure: false,
57
- hof: { shape: "unary" } },
57
+ hof: { shape: "element" } },
58
58
  "array.findIndex": { ret: INT, pure: false,
59
- hof: { shape: "unary" } },
59
+ hof: { shape: "element" } },
60
60
  "array.findLastIndex": { ret: INT,
61
- pure: false, hof: { shape: "unary" } },
61
+ pure: false, hof: { shape: "element" } },
62
62
  "array.flat": { pure: true,
63
63
  ret: (objTy) => objTy.kind === "array" && objTy.elem.kind === "array"
64
64
  ? { kind: "array", elem: objTy.elem.elem } : UNKNOWN },
@@ -67,7 +67,7 @@ export const BUILTINS = {
67
67
  ret: (objTy) => objTy.kind === "array" && objTy.elem.kind === "string"
68
68
  ? STRING() : UNKNOWN },
69
69
  "array.map": { pure: false,
70
- hof: { shape: "unary" },
70
+ hof: { shape: "element" },
71
71
  // Prefer the lambda's declared return type (handles multi-statement bodies
72
72
  // where body[0] is an `if`, not a `return`); fall back to the body's return.
73
73
  ret: (_objTy, args) => {
@@ -123,3 +123,17 @@ export function recognizeBuiltin(objTy, method) {
123
123
  export function builtinSpec(id) {
124
124
  return BUILTINS[id];
125
125
  }
126
+ /** The actual arguments passed by JavaScript, independently of which ones a
127
+ * callback declares or observes. Array indices are JS numbers (modeled ints). */
128
+ export function callbackArgumentTypes(spec, receiver, initial) {
129
+ if (!spec.hof || receiver.kind !== "array")
130
+ return undefined;
131
+ switch (spec.hof.shape) {
132
+ case "element": return [receiver.elem, { kind: "int" }, receiver];
133
+ case "comparator": return [receiver.elem, receiver.elem];
134
+ case "reduce": return initial ? [initial, receiver.elem, { kind: "int" }, receiver] : undefined;
135
+ }
136
+ }
137
+ export function callbackBaseArity(shape) {
138
+ return shape === "element" ? 1 : 2;
139
+ }
@@ -0,0 +1,67 @@
1
+ import { pCtor, usesNameInStmts } from "./ir.js";
2
+ import { callbackBaseArity } from "./builtins.js";
3
+ import { freshName } from "./names.js";
4
+ const INT = { kind: "int" };
5
+ const INDICES = { kind: "array", elem: INT };
6
+ const variable = (name) => ({ kind: "var", name });
7
+ export function lowerIndexedCallback(receiver, receiverTy, method, args, shape, monadic, id) {
8
+ const callback = args[0];
9
+ if (receiverTy.kind !== "array" || callback?.kind !== "lambda" ||
10
+ callback.params.length <= callbackBaseArity(shape))
11
+ return null;
12
+ const sourceName = freshName(`_callbackSource${id}`);
13
+ const indexName = freshName(`_callbackIndex${id}`);
14
+ const accName = freshName(`_callbackAcc${id}`);
15
+ const source = variable(sourceName), index = variable(indexName);
16
+ const element = { kind: "index", arr: source, idx: { kind: "toNat", expr: index } };
17
+ const values = shape === "reduce" ? [variable(accName), element, index, source] : [element, index, source];
18
+ const elementPosition = shape === "reduce" ? 1 : 0;
19
+ if (receiverTy.elem.kind === "nat" && callback.params[elementPosition].type.kind === "int") {
20
+ values[elementPosition] = { kind: "toInt", expr: element };
21
+ }
22
+ const bindings = callback.params.flatMap((p, i) => usesNameInStmts(callback.body, p.name)
23
+ ? [{ kind: "let", name: p.name, type: p.type, mutable: false, value: values[i] }]
24
+ : []);
25
+ // Keep the body expression-shaped when possible, as required by Dafny's
26
+ // collection operations. These bindings evaluate only already-bound values.
27
+ let body = callback.body;
28
+ if (body.length === 1 && body[0].kind === "return") {
29
+ let value = body[0].value;
30
+ for (const s of [...bindings].reverse()) {
31
+ if (s.kind === "let")
32
+ value = { kind: "let", name: s.name, type: s.type, value: s.value, body: value };
33
+ }
34
+ // Backend collection helpers take total callbacks. Extend the callback
35
+ // outside its actual index domain without evaluating its body there.
36
+ // map and some inline the body under membership/bounds instead.
37
+ if (method !== "map" && method !== "some") {
38
+ const valid = { kind: "binop", op: "∧",
39
+ left: { kind: "binop", op: "≤", left: { kind: "num", value: 0 }, right: index },
40
+ right: { kind: "binop", op: "<", left: index, right: { kind: "field", obj: source, field: "size" } } };
41
+ value = { kind: "if", cond: valid, then: value,
42
+ else: shape === "reduce" ? variable(accName) : { kind: "bool", value: false } };
43
+ }
44
+ body = [{ kind: "return", value }];
45
+ }
46
+ else
47
+ body = [...bindings, ...body];
48
+ const adapted = { kind: "lambda", body, typedParams: true, params: shape === "reduce"
49
+ ? [{ name: accName, type: callback.params[0].type }, { name: indexName, type: INT }]
50
+ : [{ name: indexName, type: INT }] };
51
+ const positions = { kind: "arrayRange", length: { kind: "field", obj: source, field: "size" } };
52
+ let result = { kind: "methodCall", obj: positions, objTy: INDICES,
53
+ method, args: [adapted, ...args.slice(1)], monadic };
54
+ // Selection methods return elements; their index-domain versions return
55
+ // positions. Translate the result back without changing order or witnesses.
56
+ if (method === "filter") {
57
+ result = { kind: "methodCall", obj: result, objTy: INDICES, method: "map", monadic: false,
58
+ args: [{ kind: "lambda", typedParams: true, params: [{ name: indexName, type: INT }], body: [{ kind: "return", value: element }] }] };
59
+ }
60
+ else if (method === "find" || method === "findLast") {
61
+ result = { kind: "match", scrutinee: result, arms: [
62
+ { pattern: pCtor("some", indexName), body: { kind: "constructor", name: "some", args: [element] } },
63
+ { pattern: pCtor("none"), body: { kind: "constructor", name: "none", args: [] } },
64
+ ] };
65
+ }
66
+ return { kind: "let", name: sourceName, type: receiverTy, value: receiver, body: result };
67
+ }
@@ -69,9 +69,11 @@ export function bindPresentFact(f, ctx) {
69
69
  }
70
70
  /** Detect optional checks: `e !== undefined`, `e === undefined`, `!e`, or a
71
71
  * bare optional `e` — for a pure-access-path optional-typed `e`. `!e` and
72
- * bare `e` are truthiness forms. Following TS, only pure access paths
73
- * narrow; complex scrutinees return null. */
72
+ * bare `e` are truthiness forms. `!!c` is the same check as `c`. Following
73
+ * TS, only pure access paths narrow; complex scrutinees return null. */
74
74
  export function presentFact(cond) {
75
+ if (cond.kind === "unop" && cond.op === "!" && cond.expr.kind === "unop" && cond.expr.op === "!")
76
+ return presentFact(cond.expr.expr);
75
77
  // `!e` where e is optional — a truthiness form: false iff e is absent OR its
76
78
  // inner value is itself falsy (so `Some(0)`/`Some("")` count as falsy too).
77
79
  if (cond.kind === "unop" && cond.op === "!" && cond.expr.ty.kind === "optional") {
@@ -216,6 +216,21 @@ const OP_MAP = {
216
216
  "∧": "&&", "∨": "||", "¬": "!", "↔": "<==>",
217
217
  "arrayConcat": "+",
218
218
  };
219
+ /** Escape controls and line separators while preserving printable Unicode. */
220
+ function escapeDafnyScalarString(value) {
221
+ return value.replace(/["\\\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, char => {
222
+ switch (char) {
223
+ case '"': return '\\"';
224
+ case "\\": return "\\\\";
225
+ case "\0": return "\\0";
226
+ case "\n": return "\\n";
227
+ case "\r": return "\\r";
228
+ case "\t": return "\\t";
229
+ // Dafny has no short escapes for controls such as backspace or form feed.
230
+ default: return `\\U{${char.charCodeAt(0).toString(16).toUpperCase().padStart(4, "0")}}`;
231
+ }
232
+ });
233
+ }
219
234
  /** Render a JavaScript string without losing its UTF-16 representation.
220
235
  *
221
236
  * JavaScript iteration by index exposes UTF-16 code units, including unpaired
@@ -273,11 +288,9 @@ function emitExpr(e) {
273
288
  case "bigint": return e.value;
274
289
  case "bool": return e.value ? "true" : "false";
275
290
  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
291
  return isUtf16()
279
292
  ? `"${escapeDafnyUTF16String(e.value)}"`
280
- : `"${e.value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n')}"`;
293
+ : `"${escapeDafnyScalarString(e.value)}"`;
281
294
  case "constructor": {
282
295
  // Option constructors (Some/None) may appear in inferred positions
283
296
  // (e.g. lambda result) without an explicit `optional<T>` in any
@@ -293,6 +306,9 @@ function emitExpr(e) {
293
306
  if (e.elems.length === 0)
294
307
  return `[]`;
295
308
  return `[${e.elems.map(emitExpr).join(", ")}]`;
309
+ case "arrayRange":
310
+ needPreamble("CallbackIndices");
311
+ return `CallbackIndices(${emitExpr(e.length)})`;
296
312
  case "tupleLiteral": return `(${e.elems.map(emitExpr).join(", ")})`;
297
313
  case "tupleProj": return `${emitExpr(e.obj)}.${e.index}`;
298
314
  case "emptyMap": return `map[]`;
@@ -333,17 +349,15 @@ function emitExpr(e) {
333
349
  // the copy is just the seq itself (the idiom for "copy then mutate").
334
350
  if (e.method === "slice" && args.length === 0)
335
351
  return obj;
336
- if (e.method === "slice" && args.length === 1)
337
- return `${obj}[${args[0]}..]`;
338
- if (e.method === "slice" && args.length === 2) {
352
+ if (e.method === "slice" && (args.length === 1 || args.length === 2)) {
339
353
  // JS slice clamps both bounds; Dafny requires `0 <= lo <= hi <= |s|`.
340
354
  // Direct slice is default (matches existing case studies that wrote
341
355
  // bounded calls). Files needing JS clamping opt in via `//@ safe-slice`.
342
356
  if (_useSafeSlice) {
343
357
  needPreamble("SafeSlice");
344
- return `SafeSlice(${obj}, ${args[0]}, ${args[1]})`;
358
+ return `SafeSlice(${obj}, ${args[0]}, ${args[1] ?? `|${obj}|`})`;
345
359
  }
346
- return `${obj}[${args[0]}..${args[1]}]`;
360
+ return args.length === 1 ? `${obj}[${args[0]}..]` : `${obj}[${args[0]}..${args[1]}]`;
347
361
  }
348
362
  if (e.method === "map") {
349
363
  // Always a seq comprehension: Seq.Map would hide the element access
@@ -355,8 +369,9 @@ function emitExpr(e) {
355
369
  // comprehension mentions it three times, and splicing would make
356
370
  // any closure literal inside it (e.g. a Filter predicate) three
357
371
  // distinct closures, unprovably equal through an opaque callee.
358
- // Name freshness is a local IR-level check until a backend name
359
- // allocator exists.
372
+ // Name freshness is a local IR-level check (`usesName`), not the
373
+ // Dafny-namespace allocator (`escapeGeneratedName`): a user identifier
374
+ // that *escapes* to `i_map`/`s_map` (e.g. `_map`) is still captured.
360
375
  const lam = e.args[0];
361
376
  const fresh = (base, taken) => {
362
377
  let name = base;
@@ -367,6 +382,17 @@ function emitExpr(e) {
367
382
  const taken = (n) => usesName(e.obj, n) || usesName(lam, n) ||
368
383
  (lam.kind === "lambda" && (lam.params.some(pp => pp.name === n) ||
369
384
  usesNameInStmts(lam.body, n)));
385
+ // Mapping over positions (an indexed callback): the comprehension
386
+ // index is the position itself, so no CallbackIndices sequence is
387
+ // needed. Keep the callback's declared type so the binding is `int`.
388
+ if (e.obj.kind === "arrayRange" && lam.kind === "lambda" && lam.params.length === 1 &&
389
+ lam.body.length === 1 && lam.body[0].kind === "return") {
390
+ const n = emitExpr(e.obj.length);
391
+ const idx = fresh("i_map", taken);
392
+ const p = lam.params[0];
393
+ const ty = lam.typedParams ? tyToDafny(p.type) : "int";
394
+ return `seq(${n}, ${idx} requires 0 <= ${idx} < ${n} => var ${escapeName(p.name)}: ${ty} := ${idx}; ${emitExpr(lam.body[0].value)})`;
395
+ }
370
396
  const bind = e.obj.kind !== "var";
371
397
  const s = bind ? fresh("s_map", taken) : obj;
372
398
  const idx = fresh("i_map", n => taken(n) || n === s);
@@ -460,6 +486,14 @@ function emitExpr(e) {
460
486
  }
461
487
  return `StringIndexOf(${obj}, ${args[0]})`;
462
488
  }
489
+ if (e.method === "lastIndexOf") {
490
+ needPreamble("StringLastIndexOf");
491
+ if (args.length === 2) {
492
+ needPreamble("StringSearchPosition");
493
+ return `StringLastIndexOfFrom(${obj}, ${args[0]}, StringSearchPosition(${obj}, ${args[1]}))`;
494
+ }
495
+ return `StringLastIndexOf(${obj}, ${args[0]})`;
496
+ }
463
497
  if (e.method === "split") {
464
498
  needPreamble("StringSplit");
465
499
  return `StringSplit(${obj}, ${args[0]})`;
@@ -685,6 +719,12 @@ function emitExpr(e) {
685
719
  needPreamble("MathMin");
686
720
  if (e.fn === "MathMax")
687
721
  needPreamble("MathMax");
722
+ if (e.fn === "MathAbsReal")
723
+ needPreamble("MathAbsReal");
724
+ if (e.fn === "MathMinReal")
725
+ needPreamble("MathMinReal");
726
+ if (e.fn === "MathMaxReal")
727
+ needPreamble("MathMaxReal");
688
728
  if (e.fn === "MaxOfSeq") {
689
729
  needPreamble("MathMax");
690
730
  needPreamble("MaxOfSeq");
@@ -733,6 +773,7 @@ function emitExpr(e) {
733
773
  case "toNat":
734
774
  // Dafny doesn't need toNat — just emit the inner expression
735
775
  return emitExpr(e.expr);
776
+ case "toInt": return emitExpr(e.expr);
736
777
  case "toReal":
737
778
  return `(${emitExpr(e.expr)} as real)`;
738
779
  case "index": {
@@ -809,7 +850,7 @@ function emitExpr(e) {
809
850
  }
810
851
  case "forall": return emitQuantifier(e, "forall");
811
852
  case "exists": return emitQuantifier(e, "exists");
812
- case "let": return `(var ${escapeName(e.name)} := ${emitExpr(e.value)}; ${emitExpr(e.body)})`;
853
+ case "let": return `(var ${escapeName(e.name)}${e.type ? `: ${tyToDafny(e.type)}` : ""} := ${emitExpr(e.value)}; ${emitExpr(e.body)})`;
813
854
  case "havoc": return "*";
814
855
  // No Dafny producer: the only `default` source is the Lean return-in-loop
815
856
  // rewrite, which never runs on the Dafny path (native in-loop returns).
@@ -833,7 +874,7 @@ function emitPureExpr(e, indent) {
833
874
  return lines.join("\n");
834
875
  }
835
876
  case "let":
836
- return `${pad}var ${escapeName(e.name)} := ${emitExpr(e.value)};\n${emitPureExpr(e.body, indent)}`;
877
+ return `${pad}var ${escapeName(e.name)}${e.type ? `: ${tyToDafny(e.type)}` : ""} := ${emitExpr(e.value)};\n${emitPureExpr(e.body, indent)}`;
837
878
  default:
838
879
  return `${pad}${emitExpr(e)}`;
839
880
  }
@@ -1153,6 +1194,13 @@ const CEIL_REAL = `function CeilReal(x: real): int
1153
1194
  if x == (x.Floor as real) then x.Floor
1154
1195
  else x.Floor + 1
1155
1196
  }`;
1197
+ const CALLBACK_INDICES = `function CallbackIndices(n: nat): (r: seq<int>)
1198
+ ensures |r| == n
1199
+ ensures forall i :: 0 <= i < n ==> r[i] == i
1200
+ ensures forall i :: i in r <==> 0 <= i < n
1201
+ {
1202
+ if n == 0 then [] else CallbackIndices(n - 1) + [n - 1]
1203
+ }`;
1156
1204
  const SEQ_FILTER_SOME = `function SeqFilterSome<T>(xs: seq<Option<T>>): seq<T>
1157
1205
  ensures |SeqFilterSome(xs)| <= |xs|
1158
1206
  {
@@ -1162,12 +1210,14 @@ const SEQ_FILTER_SOME = `function SeqFilterSome<T>(xs: seq<Option<T>>): seq<T>
1162
1210
  const SEQ_FILTER = `function SeqFilter<T(!new)>(p: T -> bool, xs: seq<T>): seq<T>
1163
1211
  ensures |SeqFilter(p, xs)| <= |xs|
1164
1212
  ensures forall x :: x in SeqFilter(p, xs) <==> x in xs && p(x)
1213
+ ensures forall i :: 0 <= i < |SeqFilter(p, xs)| ==> SeqFilter(p, xs)[i] in xs
1165
1214
  decreases |xs|
1166
1215
  {
1167
1216
  if |xs| == 0 then []
1168
1217
  else (if p(xs[0]) then [xs[0]] else []) + SeqFilter(p, xs[1..])
1169
1218
  }`;
1170
1219
  const SEQ_ALL = `predicate SeqAll<T>(xs: seq<T>, p: T -> bool)
1220
+ ensures SeqAll(xs, p) <==> (forall x :: x in xs ==> p(x))
1171
1221
  decreases |xs|
1172
1222
  {
1173
1223
  |xs| == 0 || (p(xs[0]) && SeqAll(xs[1..], p))
@@ -1330,6 +1380,36 @@ function StringIndexOfFromN(s: string, sub: string, from: nat): int
1330
1380
  else if s[from..from + |sub|] == sub then from as int
1331
1381
  else StringIndexOfFromN(s, sub, from + 1)
1332
1382
  }`;
1383
+ // JS `s.lastIndexOf(sub, position)` searches backward from the clamped
1384
+ // position for the last match starting at or before it. An empty `sub` matches
1385
+ // at that position. The postconditions also state that no later match exists,
1386
+ // which is what lets callers reason about the not-found result.
1387
+ const STRING_LAST_INDEX_OF = `predicate StringMatchesAt(s: string, sub: string, j: int)
1388
+ {
1389
+ 0 <= j && j + |sub| <= |s| && s[j..j + |sub|] == sub
1390
+ }
1391
+
1392
+ function StringLastIndexOf(s: string, sub: string): int
1393
+ ensures StringLastIndexOf(s, sub) == -1
1394
+ || (0 <= StringLastIndexOf(s, sub) <= |s| - |sub| && StringMatchesAt(s, sub, StringLastIndexOf(s, sub)))
1395
+ ensures forall j {:trigger StringMatchesAt(s, sub, j)} ::
1396
+ StringLastIndexOf(s, sub) < j ==> !StringMatchesAt(s, sub, j)
1397
+ {
1398
+ StringLastIndexOfFrom(s, sub, |s|)
1399
+ }
1400
+
1401
+ function StringLastIndexOfFrom(s: string, sub: string, from: nat): int
1402
+ decreases from
1403
+ ensures StringLastIndexOfFrom(s, sub, from) == -1
1404
+ || (0 <= StringLastIndexOfFrom(s, sub, from) <= from
1405
+ && StringMatchesAt(s, sub, StringLastIndexOfFrom(s, sub, from)))
1406
+ ensures forall j {:trigger StringMatchesAt(s, sub, j)} ::
1407
+ StringLastIndexOfFrom(s, sub, from) < j <= from ==> !StringMatchesAt(s, sub, j)
1408
+ {
1409
+ if StringMatchesAt(s, sub, from) then from as int
1410
+ else if from == 0 then -1
1411
+ else StringLastIndexOfFrom(s, sub, from - 1)
1412
+ }`;
1333
1413
  // `s.split(d)` in TS returns a non-empty sequence of segments. Modeled here as
1334
1414
  // an axiom — defining it recursively would force StringIndexOf to grow ensures
1335
1415
  // clauses that callers don't need. The two ensures cover what verification
@@ -1445,6 +1525,8 @@ const STRING_REPEAT = `function StringRepeat(s: string, n: int): string
1445
1525
  }`;
1446
1526
  const MATH_MIN = `function MathMin(a: int, b: int): int { if a <= b then a else b }`;
1447
1527
  const MATH_MAX = `function MathMax(a: int, b: int): int { if a >= b then a else b }`;
1528
+ const MATH_MIN_REAL = `function MathMinReal(a: real, b: real): real { if a <= b then a else b }`;
1529
+ const MATH_MAX_REAL = `function MathMaxReal(a: real, b: real): real { if a >= b then a else b }`;
1448
1530
  const MAX_OF_SEQ = `function MaxOfSeq(s: seq<int>): int
1449
1531
  requires |s| > 0
1450
1532
  ensures forall i: nat :: i < |s| ==> s[i] <= MaxOfSeq(s)
@@ -1504,6 +1586,7 @@ const INT_TO_STRING = `function IntToString(n: int): string
1504
1586
  if n < 0 then "-" + NatToString(-n) else NatToString(n)
1505
1587
  }`;
1506
1588
  const MATH_ABS = `function MathAbs(x: int): nat { if x >= 0 then x else -x }`;
1589
+ const MATH_ABS_REAL = `function MathAbsReal(x: real): real { if x >= 0.0 then x else -x }`;
1507
1590
  // perm(a, b) — `a` and `b` are reorderings of each other (equal as multisets).
1508
1591
  // Transparent (Dafny unfolds it), so hand-proofs can reason with `multiset`
1509
1592
  // directly. The `(==)` bound requires the element type to support equality.
@@ -1551,12 +1634,14 @@ const PREAMBLE_CODE = [
1551
1634
  ["SeqAll", SEQ_ALL],
1552
1635
  ["SeqFoldLeft", SEQ_FOLD_LEFT],
1553
1636
  ["SeqFilterSome", SEQ_FILTER_SOME],
1637
+ ["CallbackIndices", CALLBACK_INDICES],
1554
1638
  ["SeqFind", SEQ_FIND],
1555
1639
  ["SeqFindLast", SEQ_FIND_LAST],
1556
1640
  ["SeqFlatten", SEQ_FLATTEN],
1557
1641
  ["SeqJoin", SEQ_JOIN],
1558
1642
  ["SafeSlice", SAFE_SLICE],
1559
1643
  ["StringIndexOf", STRING_INDEX_OF],
1644
+ ["StringLastIndexOf", STRING_LAST_INDEX_OF],
1560
1645
  ["StringSearchPosition", STRING_SEARCH_POSITION],
1561
1646
  ["StringStartsWithAt", STRING_STARTS_WITH_AT],
1562
1647
  ["StringEndsWithAt", STRING_ENDS_WITH_AT],
@@ -1573,6 +1658,9 @@ const PREAMBLE_CODE = [
1573
1658
  ["MathAbs", MATH_ABS],
1574
1659
  ["MathMin", MATH_MIN],
1575
1660
  ["MathMax", MATH_MAX],
1661
+ ["MathAbsReal", MATH_ABS_REAL],
1662
+ ["MathMinReal", MATH_MIN_REAL],
1663
+ ["MathMaxReal", MATH_MAX_REAL],
1576
1664
  ["MaxOfSeq", MAX_OF_SEQ],
1577
1665
  ["MinOfSeq", MIN_OF_SEQ],
1578
1666
  ["Perm", PERM],
@@ -555,10 +555,16 @@ function extractExpr(node) {
555
555
  const destructureBindings = [];
556
556
  const params = node.getParameters().map((p, paramIndex) => {
557
557
  const typeNode = p.getTypeNode();
558
- const tsType = typeNode ? typeNode.getText() : undefined;
558
+ const tsType = typeNode ? annotationTypeText(typeNode, p.getType()) ?? typeNode.getText() : undefined;
559
559
  const nameNode = p.getNameNode();
560
560
  if (Node.isIdentifier(nameNode))
561
- return { name: nameNode.getText(), tsType };
561
+ return {
562
+ name: nameNode.getText(), tsType,
563
+ ...(p.isRestParameter() ? { rest: true } : {}),
564
+ ...(p.getInitializer() ? { defaultValue: extractExpr(p.getInitializer()),
565
+ inferredTsType: p.getType().getCallSignatures().length
566
+ ? p.getType().getText(p) : typeToString(p.getType()) } : {}),
567
+ };
562
568
  if (Node.isArrayBindingPattern(nameNode)) {
563
569
  throw new Error(`array binding pattern in arrow parameter not yet supported: ${nameNode.getText()}`);
564
570
  }
@@ -743,9 +749,10 @@ function extractExpr(node) {
743
749
  // ── Annotation parsing ───────────────────────────────────────
744
750
  const PREFIX = "//@ ";
745
751
  const KEYWORDS = ["requires", "ensures", "contract", "invariant", "decreases", "done_with", "type"];
746
- /** The other directives (SPEC §2.1) besides options, read by keyword elsewhere. */
752
+ /** The other directives (SPEC §2.1) besides options, read by keyword elsewhere.
753
+ * `guarded` is consumed by lemmascript-guard's manifest sweep. */
747
754
  const DIRECTIVES = ["verify", "pure", "impure", "skip", "extern", "havoc", "autohavoc", "assert", "assume",
748
- "ghost", "declare-type", "backend", "lean-module"];
755
+ "ghost", "declare-type", "backend", "lean-module", "guarded"];
749
756
  function parseAnnotation(text) {
750
757
  if (!text.startsWith(PREFIX))
751
758
  return null;
@@ -1195,6 +1202,15 @@ function declaredTypeTextIfBetter(propDecl, tsType) {
1195
1202
  return tsType;
1196
1203
  return text;
1197
1204
  }
1205
+ /** The type an annotation names, as text for `parseTsType`. That parser has
1206
+ * no checker, so an indexed access type (`T["k"]`, `T["k"][number]`) would
1207
+ * survive as an opaque name spelled with brackets. When the annotation uses
1208
+ * one, render the checker's resolved type instead. */
1209
+ function annotationTypeText(tn, type) {
1210
+ const indexed = Node.isIndexedAccessTypeNode(tn)
1211
+ || tn.getFirstDescendantByKind(SyntaxKind.IndexedAccessType) !== undefined;
1212
+ return indexed ? typeToString(type) : undefined;
1213
+ }
1198
1214
  function typeToString(type) {
1199
1215
  if (constEnumInfo(type))
1200
1216
  return "number";
@@ -1425,7 +1441,8 @@ function renameRawExpr(e, from, to) {
1425
1441
  case "nonNull": return { ...e, expr: r(e.expr) };
1426
1442
  case "optChain": return { ...e, obj: r(e.obj), chain: e.chain.map(c => c.kind === "call" ? { ...c, args: c.args.map(r) } : c.kind === "index" ? { ...c, idx: r(c.idx) } : c) };
1427
1443
  case "lambda": return e.params.some(p => p.name === from) ? e
1428
- : { ...e, body: Array.isArray(e.body) ? renameRawStmts(e.body, from, to) : r(e.body) };
1444
+ : { ...e, params: e.params.map(p => p.defaultValue ? { ...p, defaultValue: r(p.defaultValue) } : p),
1445
+ body: Array.isArray(e.body) ? renameRawStmts(e.body, from, to) : r(e.body) };
1429
1446
  case "forall":
1430
1447
  case "exists": return e.var === from ? e : { ...e, body: r(e.body) };
1431
1448
  }
@@ -1712,7 +1729,9 @@ function extractStmts(stmts) {
1712
1729
  // Dafny binding `var x: T := <default>;` typechecks. The empty-
1713
1730
  // collection cases are picked up by dafny-emit's let case, which
1714
1731
  // adds an explicit `: T` annotation for inference.
1715
- const tsType = _eraseGenerics(d.getTypeNode()?.getText() ?? typeToString(declType));
1732
+ const typeNode = d.getTypeNode();
1733
+ const tsType = _eraseGenerics((typeNode && annotationTypeText(typeNode, declType))
1734
+ ?? typeNode?.getText() ?? typeToString(declType));
1716
1735
  const isOptional = / \| (null|undefined)\b/.test(tsType)
1717
1736
  || /^(null|undefined) \| /.test(tsType)
1718
1737
  || tsType.endsWith(" | undefined") || tsType.endsWith(" | null");
@@ -1745,7 +1764,9 @@ function extractStmts(stmts) {
1745
1764
  // where the imported declaration's shape is opaque to LS): in that
1746
1765
  // case leave null so resolve infers from the initializer's IR type
1747
1766
  // (which sees the declare-type stubs).
1748
- const annotatedText = d.getTypeNode()?.getText();
1767
+ const annotationNode = d.getTypeNode();
1768
+ const annotatedText = annotationNode
1769
+ ? annotationTypeText(annotationNode, declType) ?? annotationNode.getText() : undefined;
1749
1770
  const inferred = annotatedText ? null : _eraseGenerics(typeToString(declType));
1750
1771
  const tsType = havocType
1751
1772
  ?? (annotatedText ? _eraseGenerics(annotatedText) : (inferred === "any" ? null : inferred));
@@ -1855,7 +1876,9 @@ function extractStmts(stmts) {
1855
1876
  const name = fresh ?? decl.getName();
1856
1877
  if (fresh)
1857
1878
  renames.push([decl.getName(), fresh]);
1858
- const tsType = decl.getTypeNode()?.getText() ?? typeToString(decl.getType());
1879
+ const typeNode = decl.getTypeNode();
1880
+ const tsType = (typeNode && annotationTypeText(typeNode, decl.getType()))
1881
+ ?? typeNode?.getText() ?? typeToString(decl.getType());
1859
1882
  const initExpr = decl.getInitializer();
1860
1883
  if (!initExpr)
1861
1884
  throw new Error(`for(...) at line ${line}: missing initializer for ${name}`);
@@ -2191,8 +2214,12 @@ function extractFunctionInner(fn, parentAnnotations) {
2191
2214
  // when no annotation is present, fall back to the computed type
2192
2215
  // (e.g., `eof = false` infers `boolean` from the default value).
2193
2216
  const tn = p.getTypeNode();
2217
+ const resolved = tn && annotationTypeText(tn, p.getType());
2194
2218
  let tsType;
2195
- if (tn && Node.isUnionTypeNode(tn)) {
2219
+ if (resolved) {
2220
+ tsType = _eraseGenerics(resolved);
2221
+ }
2222
+ else if (tn && Node.isUnionTypeNode(tn)) {
2196
2223
  tsType = _eraseGenerics(_tsTypeFromUnionNode(tn));
2197
2224
  }
2198
2225
  else if (tn) {
@@ -2229,6 +2256,9 @@ function extractFunctionInner(fn, parentAnnotations) {
2229
2256
  // and the type mapper reads the subject name as an opaque type.
2230
2257
  if (node && node.getKind() === SyntaxKind.TypePredicate)
2231
2258
  return "boolean";
2259
+ const resolved = node && annotationTypeText(node, fn.getReturnType());
2260
+ if (resolved)
2261
+ return _eraseGenerics(resolved);
2232
2262
  if (node && Node.isUnionTypeNode(node))
2233
2263
  return _eraseGenerics(_tsTypeFromUnionNode(node));
2234
2264
  if (node)
@@ -2253,6 +2283,12 @@ function extractFunctionInner(fn, parentAnnotations) {
2253
2283
  export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDependency = () => { }) {
2254
2284
  _extractOptions = options;
2255
2285
  _validateDependency = validateDependency;
2286
+ // Per-module state: a previous module in the same process (batch mode,
2287
+ // tests) must not leak a havoc key, temp-name counter, or function-local maps.
2288
+ _havocKey = null;
2289
+ _destrCounter = 0;
2290
+ _typeParamMap = new Map();
2291
+ _reservedForCounterNames = new Set();
2256
2292
  // Seed the fresh-name check (names.ts) before anything mints: every
2257
2293
  // Identifier token in the module, a deliberate over-approximation.
2258
2294
  setUserNames(new Set(sourceFile.getDescendantsOfKind(SyntaxKind.Identifier).map(i => i.getText())));
@@ -2877,6 +2913,8 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
2877
2913
  }
2878
2914
  }
2879
2915
  if (e.kind === "lambda") {
2916
+ e.params.forEach(p => { if (p.defaultValue)
2917
+ collectNamesExpr(p.defaultValue); });
2880
2918
  if (Array.isArray(e.body))
2881
2919
  collectNames(e.body);
2882
2920
  else
@@ -0,0 +1,36 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { createRequire } from "node:module";
3
+ import { fileURLToPath } from "node:url";
4
+ /** Forward to the packaged guard CLI, using this compiler for extraction. */
5
+ export function runGuard(args) {
6
+ if (Number(process.versions.node.split(".")[0]) < 22) {
7
+ console.error("`lsc guard` requires Node.js 22 or newer.");
8
+ process.exit(1);
9
+ }
10
+ let cli;
11
+ try {
12
+ cli = createRequire(import.meta.url).resolve("lemmascript-guard/dist/guard.js");
13
+ }
14
+ catch {
15
+ console.error("`lsc guard` needs lemmascript-guard >= 0.1.0; reinstall lemmascript with optional dependencies enabled (--include=optional).");
16
+ process.exit(1);
17
+ }
18
+ try {
19
+ execFileSync(process.execPath, [cli, ...args], {
20
+ stdio: "inherit",
21
+ env: {
22
+ ...process.env,
23
+ // A checkout can have another lemmascript version installed as a peer.
24
+ // Use this build by default, while retaining the explicit dev override.
25
+ LEMMASCRIPT: process.env.LEMMASCRIPT || fileURLToPath(new URL("../../", import.meta.url)),
26
+ },
27
+ });
28
+ }
29
+ catch (err) {
30
+ const status = err.status;
31
+ if (typeof status === "number")
32
+ process.exit(status);
33
+ console.error(err instanceof Error ? err.message : String(err));
34
+ process.exit(1);
35
+ }
36
+ }
package/tools/dist/ir.js CHANGED
@@ -74,6 +74,7 @@ export function anyExpr(e, pred) {
74
74
  case "binop": return anyExpr(e.left, pred) || anyExpr(e.right, pred);
75
75
  case "unop":
76
76
  case "toNat":
77
+ case "toInt":
77
78
  case "toReal": return anyExpr(e.expr, pred);
78
79
  case "app": return e.args.some(a => anyExpr(a, pred));
79
80
  case "field": return anyExpr(e.obj, pred);
@@ -83,6 +84,7 @@ export function anyExpr(e, pred) {
83
84
  case "implies": return e.premises.some(p => anyExpr(p, pred)) || anyExpr(e.conclusion, pred);
84
85
  case "record": return (e.spread ? anyExpr(e.spread, pred) : false) || e.fields.some(f => anyExpr(f.value, pred));
85
86
  case "arrayLiteral": return e.elems.some(x => anyExpr(x, pred));
87
+ case "arrayRange": return anyExpr(e.length, pred);
86
88
  case "mapLiteral": return e.entries.some(en => anyExpr(en.key, pred) || anyExpr(en.value, pred));
87
89
  case "methodCall": return anyExpr(e.obj, pred) || e.args.some(a => anyExpr(a, pred));
88
90
  case "lambda": return e.body.some(s => anyExprInStmt(s, pred));