lemmascript 0.6.12 → 0.6.13

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.
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Pure live-alias conflict kernel for Milestone 3b
3
+ * (`midspiral/LemmaScript#387`, `robertpenner/LemmaScript#50`).
4
+ *
5
+ * Kept strictly inside the LemmaScript subset so its core conflict-detection
6
+ * and alias-binding contracts are self-verified via
7
+ * `npx lsc check --backend=dafny tools/src/alias-check.ts`.
8
+ */
9
+ //@ pure
10
+ export function lookupAliasGroup(aliases, name) {
11
+ const g = aliases.get(name);
12
+ return g !== undefined ? g : -1;
13
+ }
14
+ /** Bind `name` to a fresh alias group `groupId` (breaking any prior alias). */
15
+ //@ ensures \result.has(name)
16
+ //@ ensures \result.get(name) == groupId
17
+ export function bindFreshGroup(aliases, name, groupId) {
18
+ const next = new Map(aliases);
19
+ next.set(name, groupId);
20
+ return next;
21
+ }
22
+ /** Bind `dst` to share `src`'s alias group if `src` is tracked, else `fallbackId`. */
23
+ //@ ensures \result.has(dst)
24
+ export function bindCopyGroup(aliases, dst, src, fallbackId) {
25
+ const next = new Map(aliases);
26
+ const srcGroup = aliases.get(src);
27
+ if (srcGroup !== undefined) {
28
+ next.set(dst, srcGroup);
29
+ }
30
+ else {
31
+ next.set(dst, fallbackId);
32
+ }
33
+ return next;
34
+ }
35
+ /**
36
+ * Find the first candidate variable `other` that:
37
+ * 1. is distinct from `mutatedVar`,
38
+ * 2. is live after the mutation (`liveAfter.has(other)`), and
39
+ * 3. shares the same non-negative alias group ID as `mutatedVar`.
40
+ *
41
+ * Returns `""` when no live alias conflict exists (covering both read-only
42
+ * aliases when no mutation occurs and dead-source moves where the aliased
43
+ * variable is not in `liveAfter`).
44
+ */
45
+ //@ ensures \result != "" ==> \result != mutatedVar && liveAfter.has(\result)
46
+ export function findLiveAliasConflict(mutatedVar, aliases, liveAfter, candidates) {
47
+ const mutGroup = aliases.get(mutatedVar);
48
+ if (mutGroup === undefined)
49
+ return "";
50
+ let i = 0;
51
+ while (i < candidates.length) {
52
+ //@ invariant 0 <= i && i <= candidates.length
53
+ const cand = candidates[i];
54
+ if (cand !== mutatedVar && liveAfter.has(cand)) {
55
+ const candGroup = aliases.get(cand);
56
+ if (candGroup !== undefined && candGroup === mutGroup) {
57
+ return cand;
58
+ }
59
+ }
60
+ i = i + 1;
61
+ }
62
+ return "";
63
+ }
64
+ /** Boolean wrapper over `findLiveAliasConflict`. */
65
+ export function hasLiveAliasConflict(mutatedVar, aliases, liveAfter, candidates) {
66
+ return findLiveAliasConflict(mutatedVar, aliases, liveAfter, candidates) !== "";
67
+ }
@@ -82,6 +82,9 @@ function forEachChildExpr(e, f) {
82
82
  case "unop":
83
83
  f(e.expr);
84
84
  return;
85
+ case "checkedUnwrap":
86
+ f(e.expr);
87
+ return;
85
88
  case "call":
86
89
  f(e.fn);
87
90
  e.args.forEach(f);
@@ -354,6 +357,7 @@ function rewriteExpr(e, hoisted) {
354
357
  case "havoc": return e;
355
358
  case "binop": return { ...e, left: rewriteExpr(e.left, hoisted), right: rewriteExpr(e.right, hoisted) };
356
359
  case "unop": return { ...e, expr: rewriteExpr(e.expr, hoisted) };
360
+ case "checkedUnwrap": return { ...e, expr: rewriteExpr(e.expr, hoisted) };
357
361
  case "call": return { ...e, fn: rewriteExpr(e.fn, hoisted), args: e.args.map(a => rewriteExpr(a, hoisted)) };
358
362
  case "index": return { ...e, obj: rewriteExpr(e.obj, hoisted), idx: rewriteExpr(e.idx, hoisted) };
359
363
  case "field": return { ...e, obj: rewriteExpr(e.obj, hoisted) };
@@ -0,0 +1,384 @@
1
+ /**
2
+ * Post-narrow checked-read insertion (`midspiral/LemmaScript#387`, Milestone 4 /
3
+ * `robertpenner/LemmaScript#52`).
4
+ *
5
+ * After `narrow.ts`'s `someMatch` / `tagMatch` drivers run, any access path
6
+ * that `resolve.ts` proved non-optional (via `&&`/`||` chains, `if ... else`,
7
+ * `while` presence guards, or definite assignment narrowing) whose underlying
8
+ * storage binding is still `Option<T>` is wrapped in an explicit
9
+ * `{ kind: "checkedUnwrap", expr, ty }`.
10
+ *
11
+ * Lowering `checkedUnwrap` emits a backend-checked projection (`.value` in
12
+ * Dafny, `.get (by grind)` in Lean) directly on the live storage variable,
13
+ * without introducing match-binder copies, sequential `if i_branch0` splits,
14
+ * or unnecessary `i_compareN` temporaries.
15
+ */
16
+ import { parseTsType } from "./types.js";
17
+ const ARITH = new Set(["+", "-", "*", "/", "%", "**"]);
18
+ function pathKey(e) {
19
+ if (e.kind === "var")
20
+ return e.name;
21
+ if (e.kind === "checkedUnwrap")
22
+ return pathKey(e.expr);
23
+ if (e.kind === "field") {
24
+ const inner = pathKey(e.obj);
25
+ return inner === null ? null : `${inner}.${e.field}`;
26
+ }
27
+ return null;
28
+ }
29
+ function isOptional(ty) {
30
+ return ty !== null && ty.kind === "optional";
31
+ }
32
+ function fieldInfoTy(f) {
33
+ if (!f)
34
+ return null;
35
+ const ty = f.type ?? parseTsType(f.tsType);
36
+ return f.optionalKey && ty.kind !== "optional" ? { kind: "optional", inner: ty } : ty;
37
+ }
38
+ function declField(decl, field, ofVariant) {
39
+ if (decl.kind === "record")
40
+ return decl.fields?.find(f => f.name === field) ?? null;
41
+ if (decl.kind !== "discriminated-union" || !decl.variants)
42
+ return null;
43
+ const variants = ofVariant ? decl.variants.filter(v => v.name === ofVariant) : decl.variants;
44
+ const found = variants.map(v => v.fields.find(f => f.name === field)).filter((f) => !!f);
45
+ if (found.length === 0)
46
+ return null;
47
+ const optional = found.map(f => isOptional(fieldInfoTy(f)));
48
+ return optional.every(o => o === optional[0]) ? found[0] : null;
49
+ }
50
+ function fieldStorageTy(ty, field, ofVariant, mod, depth = 0) {
51
+ if (depth > 8 || ty.kind !== "user")
52
+ return null;
53
+ const cls = mod.classes.find(c => c.name === ty.name);
54
+ if (cls)
55
+ return cls.fields.find(f => f.name === field)?.ty ?? null;
56
+ const decl = mod.typeDecls.find(d => d.name === ty.name);
57
+ if (!decl || (decl.typeParams && decl.typeParams.length > 0))
58
+ return null;
59
+ if (decl.kind === "alias" && decl.aliasOfTy) {
60
+ return fieldStorageTy(decl.aliasOfTy, field, ofVariant, mod, depth + 1);
61
+ }
62
+ return fieldInfoTy(declField(decl, field, ofVariant));
63
+ }
64
+ function storageTyOf(e, scope, mod) {
65
+ if (e.kind === "checkedUnwrap")
66
+ return e.ty;
67
+ const key = pathKey(e);
68
+ if (key !== null) {
69
+ const bound = scope.types.get(key);
70
+ if (bound)
71
+ return bound;
72
+ }
73
+ if (e.kind !== "field")
74
+ return null;
75
+ const objTy = storageTyOf(e.obj, scope, mod);
76
+ if (!objTy || objTy.kind === "optional")
77
+ return null;
78
+ return fieldStorageTy(objTy, e.field, e.ofVariant, mod);
79
+ }
80
+ function extendScope(scope, names) {
81
+ if (names.length === 0)
82
+ return scope;
83
+ const types = new Map(scope.types);
84
+ for (const n of names) {
85
+ types.set(n.name, n.ty);
86
+ for (const k of [...types.keys()])
87
+ if (k.startsWith(`${n.name}.`))
88
+ types.delete(k);
89
+ }
90
+ return { types };
91
+ }
92
+ function enterSomeMatch(scope, scrutinee, binder, binderTy) {
93
+ const types = new Map(scope.types);
94
+ types.set(binder, binderTy);
95
+ const key = pathKey(scrutinee);
96
+ if (key !== null)
97
+ types.set(key, binderTy);
98
+ return { types };
99
+ }
100
+ function isDefinitelyUnwrappedStamp(ty) {
101
+ return !isOptional(ty) && ty.kind !== "unknown" && ty.kind !== "void";
102
+ }
103
+ /** Rewrite an expression that is the direct operand of `=== undefined` /
104
+ * `!== undefined`: never wrap the operand itself in `checkedUnwrap` (restore
105
+ * its declared optional storage type so `transform.ts` emits an `Option`
106
+ * presence check), while still rewriting any optional receiver prefix. */
107
+ function rewritePresenceOperand(e, scope, mod) {
108
+ const storage = storageTyOf(e, scope, mod);
109
+ if (e.kind === "var" && isOptional(storage)) {
110
+ return { ...e, ty: storage };
111
+ }
112
+ if (e.kind === "field") {
113
+ const obj = rewriteExpr(e.obj, scope, mod);
114
+ const updated = obj === e.obj ? e : { ...e, obj };
115
+ const fStorage = storageTyOf(updated, scope, mod);
116
+ if (isOptional(fStorage))
117
+ return { ...updated, ty: fStorage };
118
+ return updated;
119
+ }
120
+ return rewriteExpr(e, scope, mod);
121
+ }
122
+ function isUndefinedVar(e) {
123
+ return e.kind === "var" && e.name === "undefined";
124
+ }
125
+ function rewriteExpr(e, scope, mod) {
126
+ switch (e.kind) {
127
+ case "var": {
128
+ const storage = storageTyOf(e, scope, mod);
129
+ if (isOptional(storage) && isDefinitelyUnwrappedStamp(e.ty)) {
130
+ return { kind: "checkedUnwrap", expr: { ...e, ty: storage }, ty: e.ty };
131
+ }
132
+ return e;
133
+ }
134
+ case "num":
135
+ case "bigint":
136
+ case "str":
137
+ case "bool":
138
+ case "havoc":
139
+ return e;
140
+ case "checkedUnwrap":
141
+ return { ...e, expr: rewriteExpr(e.expr, scope, mod) };
142
+ case "field": {
143
+ // Rewrite receiver first (so an optional receiver `box` becomes `checkedUnwrap(box)`).
144
+ const obj = rewriteExpr(e.obj, scope, mod);
145
+ const updated = obj === e.obj ? e : { ...e, obj };
146
+ // Check if this field itself is optional by declaration (or bound in scope) while stamped non-optional.
147
+ const storage = storageTyOf(updated, scope, mod);
148
+ if (isOptional(storage) && isDefinitelyUnwrappedStamp(updated.ty)) {
149
+ return { kind: "checkedUnwrap", expr: { ...updated, ty: storage }, ty: updated.ty };
150
+ }
151
+ return updated;
152
+ }
153
+ case "index":
154
+ return { ...e, obj: rewriteExpr(e.obj, scope, mod), idx: rewriteExpr(e.idx, scope, mod) };
155
+ case "binop": {
156
+ let left;
157
+ let right;
158
+ if ((e.op === "===" || e.op === "!==") && (isUndefinedVar(e.left) || isUndefinedVar(e.right))) {
159
+ left = isUndefinedVar(e.right) ? rewritePresenceOperand(e.left, scope, mod) : rewriteExpr(e.left, scope, mod);
160
+ right = isUndefinedVar(e.left) ? rewritePresenceOperand(e.right, scope, mod) : rewriteExpr(e.right, scope, mod);
161
+ }
162
+ else {
163
+ left = rewriteExpr(e.left, scope, mod);
164
+ right = rewriteExpr(e.right, scope, mod);
165
+ }
166
+ let ty = e.ty;
167
+ // Clear stale optional arithmetic stamp once operands are unwrapped.
168
+ if (ARITH.has(e.op) && isOptional(ty) && !isOptional(left.ty) && !isOptional(right.ty)) {
169
+ ty = left.ty;
170
+ }
171
+ return { ...e, left, right, ty };
172
+ }
173
+ case "unop": {
174
+ const expr = rewriteExpr(e.expr, scope, mod);
175
+ let ty = e.ty;
176
+ if (e.op === "-" && isOptional(ty) && !isOptional(expr.ty))
177
+ ty = expr.ty;
178
+ return { ...e, expr, ty };
179
+ }
180
+ case "call":
181
+ return {
182
+ ...e,
183
+ fn: rewriteExpr(e.fn, scope, mod),
184
+ args: e.args.map(a => rewriteExpr(a, scope, mod)),
185
+ };
186
+ case "record":
187
+ return {
188
+ ...e,
189
+ spread: e.spread ? rewriteExpr(e.spread, scope, mod) : null,
190
+ fields: e.fields.map(f => ({ ...f, value: rewriteExpr(f.value, scope, mod) })),
191
+ };
192
+ case "arrayLiteral":
193
+ return { ...e, elems: e.elems.map(el => rewriteExpr(el, scope, mod)) };
194
+ case "lambda": {
195
+ const inner = extendScope(scope, e.params.map(p => ({ name: p.name, ty: p.ty })));
196
+ return { ...e, body: rewriteStmts(e.body, inner, mod) };
197
+ }
198
+ case "conditional":
199
+ return {
200
+ ...e,
201
+ cond: rewriteExpr(e.cond, scope, mod),
202
+ then: rewriteExpr(e.then, scope, mod),
203
+ else: rewriteExpr(e.else, scope, mod),
204
+ };
205
+ case "optChain":
206
+ return {
207
+ ...e,
208
+ obj: rewriteExpr(e.obj, scope, mod),
209
+ chain: e.chain.map(st => st.kind === "call"
210
+ ? { ...st, args: st.args.map(a => rewriteExpr(a, scope, mod)) }
211
+ : st.kind === "index"
212
+ ? { ...st, idx: rewriteExpr(st.idx, scope, mod) }
213
+ : st),
214
+ };
215
+ case "nullish":
216
+ return { ...e, left: rewriteExpr(e.left, scope, mod), right: rewriteExpr(e.right, scope, mod) };
217
+ case "someMatch": {
218
+ // Do NOT unwrap the scrutinee itself (it is supposed to remain Option<T>),
219
+ // but DO rewrite any optional prefix inside a nested scrutinee (e.g. `box.inner`).
220
+ const scrutinee = e.scrutinee.kind === "field"
221
+ ? { ...e.scrutinee, obj: rewriteExpr(e.scrutinee.obj, scope, mod) }
222
+ : e.scrutinee;
223
+ const someScope = enterSomeMatch(scope, e.scrutinee, e.binder, e.binderTy);
224
+ return {
225
+ ...e,
226
+ scrutinee,
227
+ someBody: rewriteExpr(e.someBody, someScope, mod),
228
+ noneBody: rewriteExpr(e.noneBody, scope, mod),
229
+ };
230
+ }
231
+ case "tagMatch":
232
+ return {
233
+ ...e,
234
+ scrutinee: rewriteExpr(e.scrutinee, scope, mod),
235
+ cases: e.cases.map(c => ({ ...c, body: rewriteExpr(c.body, scope, mod) })),
236
+ fallthrough: e.fallthrough ? rewriteExpr(e.fallthrough, scope, mod) : null,
237
+ };
238
+ case "forall":
239
+ case "exists": {
240
+ const inner = extendScope(scope, [{ name: e.var, ty: e.varTy }]);
241
+ return { ...e, body: rewriteExpr(e.body, inner, mod) };
242
+ }
243
+ }
244
+ }
245
+ function rewriteStmts(stmts, scope, mod) {
246
+ let cur = scope;
247
+ const out = [];
248
+ for (const s of stmts) {
249
+ switch (s.kind) {
250
+ case "let": {
251
+ const init = rewriteExpr(s.init, cur, mod);
252
+ out.push({ ...s, init });
253
+ cur = extendScope(cur, [{ name: s.name, ty: s.ty }]);
254
+ break;
255
+ }
256
+ case "ghostLet": {
257
+ const init = rewriteExpr(s.init, cur, mod);
258
+ out.push({ ...s, init });
259
+ cur = extendScope(cur, [{ name: s.name, ty: s.ty }]);
260
+ break;
261
+ }
262
+ case "assign":
263
+ out.push({ ...s, value: rewriteExpr(s.value, cur, mod) });
264
+ break;
265
+ case "ghostAssign":
266
+ out.push({ ...s, value: rewriteExpr(s.value, cur, mod) });
267
+ break;
268
+ case "return":
269
+ out.push({ ...s, value: rewriteExpr(s.value, cur, mod) });
270
+ break;
271
+ case "expr":
272
+ out.push({ ...s, expr: rewriteExpr(s.expr, cur, mod) });
273
+ break;
274
+ case "assert":
275
+ out.push({ ...s, expr: rewriteExpr(s.expr, cur, mod) });
276
+ break;
277
+ case "break":
278
+ case "continue":
279
+ case "throw":
280
+ out.push(s);
281
+ break;
282
+ case "if":
283
+ out.push({
284
+ ...s,
285
+ cond: rewriteExpr(s.cond, cur, mod),
286
+ then: rewriteStmts(s.then, cur, mod),
287
+ else: rewriteStmts(s.else, cur, mod),
288
+ });
289
+ break;
290
+ case "while":
291
+ out.push({
292
+ ...s,
293
+ cond: rewriteExpr(s.cond, cur, mod),
294
+ invariants: s.invariants.map(inv => rewriteExpr(inv, cur, mod)),
295
+ decreases: s.decreases ? rewriteExpr(s.decreases, cur, mod) : null,
296
+ doneWith: s.doneWith ? rewriteExpr(s.doneWith, cur, mod) : null,
297
+ body: rewriteStmts(s.body, cur, mod),
298
+ });
299
+ break;
300
+ case "forof": {
301
+ const iterable = rewriteExpr(s.iterable, cur, mod);
302
+ const loopScope = extendScope(cur, [
303
+ ...s.names.map((n, i) => ({ name: n, ty: s.nameTypes[i] ?? { kind: "unknown" } })),
304
+ { name: s.idx, ty: { kind: "nat" } },
305
+ ]);
306
+ out.push({
307
+ ...s,
308
+ iterable,
309
+ invariants: s.invariants.map(inv => rewriteExpr(inv, loopScope, mod)),
310
+ doneWith: s.doneWith ? rewriteExpr(s.doneWith, loopScope, mod) : null,
311
+ body: rewriteStmts(s.body, loopScope, mod),
312
+ });
313
+ break;
314
+ }
315
+ case "switch":
316
+ out.push({
317
+ ...s,
318
+ expr: rewriteExpr(s.expr, cur, mod),
319
+ cases: s.cases.map(c => ({ ...c, body: rewriteStmts(c.body, cur, mod) })),
320
+ defaultBody: rewriteStmts(s.defaultBody, cur, mod),
321
+ });
322
+ break;
323
+ case "someMatch": {
324
+ const scrutinee = s.scrutinee.kind === "field"
325
+ ? { ...s.scrutinee, obj: rewriteExpr(s.scrutinee.obj, cur, mod) }
326
+ : s.scrutinee;
327
+ const someScope = enterSomeMatch(cur, s.scrutinee, s.binder, s.binderTy);
328
+ out.push({
329
+ ...s,
330
+ scrutinee,
331
+ someBody: rewriteStmts(s.someBody, someScope, mod),
332
+ noneBody: rewriteStmts(s.noneBody, cur, mod),
333
+ });
334
+ break;
335
+ }
336
+ case "tagMatch":
337
+ out.push({
338
+ ...s,
339
+ scrutinee: rewriteExpr(s.scrutinee, cur, mod),
340
+ cases: s.cases.map(c => ({ ...c, body: rewriteStmts(c.body, cur, mod) })),
341
+ fallthrough: rewriteStmts(s.fallthrough, cur, mod),
342
+ });
343
+ break;
344
+ }
345
+ }
346
+ return out;
347
+ }
348
+ function rewriteFunction(fn, className, globals, mod) {
349
+ const types = new Map(globals);
350
+ for (const p of fn.params)
351
+ types.set(p.name, p.ty);
352
+ if (className !== null)
353
+ types.set("this", { kind: "user", name: className });
354
+ const scope = { types };
355
+ const postTypes = new Map(types);
356
+ postTypes.set("\\result", fn.returnTy);
357
+ const postScope = { types: postTypes };
358
+ return {
359
+ ...fn,
360
+ requires: fn.requires.map(r => rewriteExpr(r, scope, mod)),
361
+ decreases: fn.decreases ? rewriteExpr(fn.decreases, scope, mod) : null,
362
+ ensures: fn.ensures.map(e => rewriteExpr(e, postScope, mod)),
363
+ body: rewriteStmts(fn.body, scope, mod),
364
+ };
365
+ }
366
+ /** Reconcile any narrowed-but-not-someMatch-bound optional reads by inserting
367
+ * explicit `checkedUnwrap` nodes. */
368
+ export function insertCheckedUnwraps(mod) {
369
+ const globals = new Map();
370
+ for (const c of mod.constants)
371
+ globals.set(c.name, c.ty);
372
+ return {
373
+ ...mod,
374
+ constants: mod.constants.map(c => ({
375
+ ...c,
376
+ value: rewriteExpr(c.value, { types: new Map(globals) }, mod),
377
+ })),
378
+ functions: mod.functions.map(fn => rewriteFunction(fn, null, globals, mod)),
379
+ classes: mod.classes.map(cls => ({
380
+ ...cls,
381
+ methods: cls.methods.map(m => rewriteFunction(m, cls.name, globals, mod)),
382
+ })),
383
+ };
384
+ }
@@ -647,9 +647,10 @@ function emitExpr(e) {
647
647
  return `${op}(${emitExpr(e.expr)})`;
648
648
  }
649
649
  case "binop": {
650
- // Discriminant check: x == .Ctor → x.Ctor?
650
+ // Discriminant check: x == .Ctor → x.Ctor? (0-arg constructors only;
651
+ // value-carrying constructors like `x == Some(v)` stay full equality).
651
652
  const op = mapOp(e.op);
652
- if ((op === "==" || op === "!=") && e.right.kind === "constructor") {
653
+ if ((op === "==" || op === "!=") && e.right.kind === "constructor" && e.right.args.length === 0) {
653
654
  const ctorName = dafnyCtorName(e.right.name.replace(/^\./, ""));
654
655
  const pred = `${emitExpr(e.left)}.${ctorName}?`;
655
656
  return op === "!=" ? `(!${pred})` : pred;
@@ -806,6 +807,11 @@ function emitExpr(e) {
806
807
  case "toInt": return emitExpr(e.expr);
807
808
  case "toReal":
808
809
  return `(${emitExpr(e.expr)} as real)`;
810
+ case "checkedUnwrap": {
811
+ const inner = emitExpr(e.expr);
812
+ const bare = e.expr.kind === "var" || e.expr.kind === "field" || e.expr.kind === "checkedUnwrap";
813
+ return bare ? `${inner}.value` : `(${inner}).value`;
814
+ }
809
815
  case "stringIndex":
810
816
  // TS indexing returns a string; Dafny's native string subscript is a
811
817
  // char. The singleton sequence preserves the native bounds obligation.
@@ -672,9 +672,10 @@ function extractExpr(node) {
672
672
  if (!hasSpread) {
673
673
  return { kind: "arrayLiteral", elems: elems.map(e => extractExpr(e)) };
674
674
  }
675
- // [a, ...b, c] → [a] + b + [c] via shared helper
675
+ // [a, ...b, c] → [a] + b + [c] via shared helper; mark freshClone so
676
+ // `[...arr]` is not misread by alias analysis as a reference alias of `arr`.
676
677
  const result = buildSpreadConcat(elems);
677
- return result;
678
+ return markFreshClone(result);
678
679
  }
679
680
  // Object literal: { res: true, done: false } or { ...obj, res: true }
680
681
  if (Node.isObjectLiteralExpression(node)) {
@@ -690,7 +691,7 @@ function extractExpr(node) {
690
691
  for (const prop of node.getProperties()) {
691
692
  if (Node.isSpreadAssignment(prop)) {
692
693
  const s = extractExpr(prop.getExpression());
693
- acc = acc === null ? s : { kind: "recordMerge", base: acc, override: s };
694
+ acc = acc === null ? markFreshClone(s) : { kind: "recordMerge", base: acc, override: s };
694
695
  }
695
696
  else if (Node.isShorthandPropertyAssignment(prop)) {
696
697
  const name = prop.getName();
@@ -740,8 +741,9 @@ function extractExpr(node) {
740
741
  const argSymbol = argType.getSymbol()?.getName() ?? argType.getAliasSymbol()?.getName();
741
742
  const argTypeText = _eraseGenerics(typeToString(argType));
742
743
  if (argSymbol === "Map" || argTypeText.startsWith("Record<")) {
743
- // new Map(existingMap) or new Map(record) — identity (Dafny maps are value types)
744
- return extractExpr(args[0]);
744
+ // new Map(existingMap) or new Map(record) — identity (Dafny maps are value types),
745
+ // marked freshClone so alias analysis knows JS allocates a fresh Map.
746
+ return markFreshClone(extractExpr(args[0]));
745
747
  }
746
748
  // new Map(entries) — map-from-array constructor
747
749
  return { kind: "call", fn: { kind: "var", name: "__mapFromArray" }, args: [extractExpr(args[0])] };
@@ -753,9 +755,9 @@ function extractExpr(node) {
753
755
  return { kind: "emptyCollection", collectionType: "Set", tsType, initElems: arg.getElements().map(e => extractExpr(e)) };
754
756
  }
755
757
  const argSymbol = arg.getType().getSymbol()?.getName() ?? arg.getType().getAliasSymbol()?.getName();
756
- // new Set(existingSet) — identity (sets are value types)
758
+ // new Set(existingSet) — identity (sets are value types), marked freshClone.
757
759
  if (argSymbol === "Set")
758
- return extractExpr(arg);
760
+ return markFreshClone(extractExpr(arg));
759
761
  // new Set(arr) — build a deduplicated set from the array's elements
760
762
  return { kind: "call", fn: { kind: "var", name: "__setFromArray" }, args: [extractExpr(arg)] };
761
763
  }
@@ -1358,6 +1360,15 @@ function typeToString(type) {
1358
1360
  }
1359
1361
  return type.getText();
1360
1362
  }
1363
+ function markFreshClone(e) {
1364
+ if (e.kind === "nonNull") {
1365
+ return { ...e, expr: markFreshClone(e.expr) };
1366
+ }
1367
+ if (e.kind === "var" || e.kind === "field" || e.kind === "index" || e.kind === "call") {
1368
+ return { ...e, freshClone: true };
1369
+ }
1370
+ return e;
1371
+ }
1361
1372
  const COMPOUND_OPS = {
1362
1373
  "+=": "+", "-=": "-", "*=": "*", "/=": "/", "%=": "%",
1363
1374
  "<<=": "<<", ">>=": ">>", "|=": "|", "&=": "&", "^=": "^", "**=": "**",
package/tools/dist/ir.js CHANGED
@@ -75,7 +75,8 @@ export function anyExpr(e, pred) {
75
75
  case "unop":
76
76
  case "toNat":
77
77
  case "toInt":
78
- case "toReal": return anyExpr(e.expr, pred);
78
+ case "toReal":
79
+ case "checkedUnwrap": return anyExpr(e.expr, pred);
79
80
  case "app": return e.args.some(a => anyExpr(a, pred));
80
81
  case "field": return anyExpr(e.obj, pred);
81
82
  case "index": return anyExpr(e.arr, pred) || anyExpr(e.idx, pred);
@@ -432,6 +432,21 @@ function emitExpr(e, parentPrec) {
432
432
  : _boolCtx && e.op === "∧" ? "&&"
433
433
  : _boolCtx && e.op === "∨" ? "||"
434
434
  : e.op;
435
+ // In Lean 4, `&&`, `||`, `∧`, and `∨` are non-dependent, so
436
+ // `checkedUnwrap` (`(x).get (by grind)`) in the right operand has no
437
+ // hypothesis in context. Emit dependent `if _h : ...` when the RHS contains
438
+ // a `checkedUnwrap` so Lean puts the presence guard in scope for `grind`.
439
+ if ((e.op === "∧" || e.op === "∨") && anyExpr(e.right, x => x.kind === "checkedUnwrap")) {
440
+ const l = emitExpr(e.left);
441
+ const r = emitExpr(e.right);
442
+ const condProp = isPropValued(e.left) ? l : `(${l}) = true`;
443
+ const tVal = _boolCtx ? "true" : "True";
444
+ const fVal = _boolCtx ? "false" : "False";
445
+ const rExpr = _boolCtx && isPropValued(e.right) ? `decide (${r})` : r;
446
+ return e.op === "∧"
447
+ ? `(if _h : ${condProp} then (${rExpr}) else ${fVal})`
448
+ : `(if _h : ${condProp} then ${tVal} else (${rExpr}))`;
449
+ }
435
450
  // Comparisons and ↔ do not chain in Lean. In particular, a Boolean
436
451
  // postcondition `res = (s = t)` must keep its inner equality grouped.
437
452
  const childPrec = ["↔", "=", "≠", "<", "≤", ">", "≥"].includes(e.op)
@@ -524,6 +539,8 @@ function emitExpr(e, parentPrec) {
524
539
  return wrap ? `(${inner}).toNat` : `${inner}.toNat`;
525
540
  }
526
541
  case "toInt": return `(Int.ofNat (${emitExpr(e.expr)}))`;
542
+ case "checkedUnwrap":
543
+ return `((${emitExpr(e.expr)}).get (by grind))`;
527
544
  case "toReal":
528
545
  // A real value reached the Lean backend via coercion (e.g. number `/`).
529
546
  // Same unsupported-real story as the `real` type case in tyToLean.
@@ -544,8 +561,19 @@ function emitExpr(e, parentPrec) {
544
561
  return `{ ${emitExpr(e.spread)} with ${fields.join(", ")} }`;
545
562
  return `{ ${fields.join(", ")} }`;
546
563
  }
547
- case "if":
564
+ case "if": {
565
+ const hasCU = anyExpr(e.then, x => x.kind === "checkedUnwrap") || anyExpr(e.else, x => x.kind === "checkedUnwrap");
566
+ if (hasCU) {
567
+ const c = emitExpr(e.cond);
568
+ const condProp = isPropValued(e.cond) ? c : `(${c}) = true`;
569
+ const t = emitExpr(e.then);
570
+ const f = emitExpr(e.else);
571
+ const tExpr = _boolCtx && isPropValued(e.then) ? `decide (${t})` : t;
572
+ const fExpr = _boolCtx && isPropValued(e.else) ? `decide (${f})` : f;
573
+ return `(if _h : ${condProp} then (${tExpr}) else (${fExpr}))`;
574
+ }
548
575
  return `if ${emitExpr(e.cond)} then ${emitExpr(e.then)} else ${emitExpr(e.else)}`;
576
+ }
549
577
  case "match": {
550
578
  // Always parenthesize inline matches — Lean parses alternatives greedily,
551
579
  // so any token after an arm body (`→`, another match's `|`, etc.) would
@@ -556,7 +584,11 @@ function emitExpr(e, parentPrec) {
556
584
  }
557
585
  case "forall": return `∀ ${e.var} : ${tyToLean(e.type)}, ${emitExpr(e.body)}`;
558
586
  case "exists": return `∃ ${e.var} : ${tyToLean(e.type)}, ${emitExpr(e.body)}`;
559
- case "let": return `let ${e.name}${e.type ? ` : ${tyToLean(e.type)}` : ""} := ${emitExpr(e.value)}\n${emitExpr(e.body)}`;
587
+ case "let":
588
+ if (e.name.startsWith("_cmp")) {
589
+ return `(let ${e.name}${e.type ? ` : ${tyToLean(e.type)}` : ""} := ${emitExpr(e.value)}; ${emitExpr(e.body)})`;
590
+ }
591
+ return `let ${e.name}${e.type ? ` : ${tyToLean(e.type)}` : ""} := ${emitExpr(e.value)}\n${emitExpr(e.body)}`;
560
592
  default: throw new Error(`Unsupported Lean expression: ${e.kind}`);
561
593
  }
562
594
  }
package/tools/dist/lsc.js CHANGED
@@ -10,6 +10,7 @@ import { createRequire } from "module";
10
10
  import path from "path";
11
11
  import { extractModule } from "./extract.js";
12
12
  import { resolveModule } from "./resolve.js";
13
+ import { assertNoLiveAliasMutations } from "./alias-check-pass.js";
13
14
  import { narrowModule } from "./narrow.js";
14
15
  import { autoHavocModule } from "./autohavoc.js";
15
16
  import { transformModuleLean, transformModuleDafny } from "./transform.js";
@@ -336,7 +337,7 @@ function runFile(cmd, filePath, backend, timeLimit, extraFlags, noVerify = false
336
337
  return;
337
338
  }
338
339
  // Resolve: Raw IR → Typed IR
339
- const resolved = resolveModule(raw);
340
+ const resolved = assertNoLiveAliasMutations(resolveModule(raw));
340
341
  // Narrow: Typed IR → Typed IR (rewrites optional-narrowing patterns to someMatch)
341
342
  // auto-havoc (//@ autohavoc): replace unmodellable expressions with arbitrary
342
343
  // values so verification rests only on the declared contracts (a sound