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.
@@ -12,6 +12,7 @@ import { builtinSpec } from "./builtins.js";
12
12
  import { lowerIndexedCallback } from "./callback-lowering.js";
13
13
  import { isFalsyCapableTy } from "./condition-facts.js";
14
14
  import { declOf, declOfKind, declOfTy, unionDeclOfTy, declWithVariant, tyBaseName } from "./typedecls.js";
15
+ import { buildNestedFieldExpr, collectAssignedIrTargets, describeReceiver, emitWriteBacksForTarget, findActiveUnwrapFrame, isMutatingCollectionMethod, makeUnwrapFrame, makeVariantFrame, resolveWriteTargetThroughFrames, } from "./place-lowering.js";
15
16
  // ── Generic IR walkers ──────────────────────────────────────
16
17
  /**
17
18
  * Map over all sub-expressions in an Expr. `f` is called on each node;
@@ -43,6 +44,7 @@ function mapExpr(e, f) {
43
44
  case "toNat": return { ...e, expr: r(e.expr) };
44
45
  case "toInt": return { ...e, expr: r(e.expr) };
45
46
  case "toReal": return { ...e, expr: r(e.expr) };
47
+ case "checkedUnwrap": return { ...e, expr: r(e.expr) };
46
48
  case "index": return { ...e, arr: r(e.arr), idx: r(e.idx) };
47
49
  case "stringIndex": return { ...e, str: r(e.str), idx: r(e.idx) };
48
50
  case "tupleLiteral": return { ...e, elems: e.elems.map(r) };
@@ -113,6 +115,7 @@ function mapTExpr(e, f) {
113
115
  : s) };
114
116
  case "nullish": return { ...e, left: r(e.left), right: r(e.right) };
115
117
  case "someMatch": return { ...e, scrutinee: r(e.scrutinee), someBody: r(e.someBody), noneBody: r(e.noneBody) };
118
+ case "checkedUnwrap": return { ...e, expr: r(e.expr) };
116
119
  case "tagMatch": return { ...e, scrutinee: r(e.scrutinee),
117
120
  cases: e.cases.map(c => ({ ...c, body: r(c.body) })),
118
121
  fallthrough: e.fallthrough ? r(e.fallthrough) : null };
@@ -406,7 +409,9 @@ function promoteAssignedLets(stmts) {
406
409
  }
407
410
  /** Build a nested record-update assigning `newVal` to a field-path receiver
408
411
  * rooted at a var: `b.a.items` → `b := b.(a := b.a.(items := newVal))`.
409
- * Returns null if the path isn't a chain of field accesses ending at a var. */
412
+ * Handles `checkedUnwrap` hops along the path by wrapping the updated record
413
+ * in `Some(...)`. Returns null if the path isn't a chain of field accesses
414
+ * (with optional checked unwraps) ending at a var. */
410
415
  function buildNestedFieldUpdate(recv, newVal) {
411
416
  if (recv.kind !== "field")
412
417
  return null;
@@ -415,6 +420,13 @@ function buildNestedFieldUpdate(recv, newVal) {
415
420
  return { root: recv.obj.name, value: upd };
416
421
  if (recv.obj.kind === "field")
417
422
  return buildNestedFieldUpdate(recv.obj, upd);
423
+ if (recv.obj.kind === "checkedUnwrap") {
424
+ const wrapped = { kind: "app", fn: "Some", args: [upd] };
425
+ if (recv.obj.expr.kind === "var")
426
+ return { root: recv.obj.expr.name, value: wrapped };
427
+ if (recv.obj.expr.kind === "field")
428
+ return buildNestedFieldUpdate(recv.obj.expr, wrapped);
429
+ }
418
430
  return null;
419
431
  }
420
432
  /** Promote every spread segment before concatenation, preserving evaluation
@@ -581,12 +593,34 @@ function lowerExpr(e, binds) {
581
593
  const valExpr = valSide.kind === "str" && innerTy.kind === "user"
582
594
  ? { kind: "constructor", name: valSide.value, type: innerTy.name, args: [] }
583
595
  : lowerExpr(valSide, binds);
584
- // The bound value goes on the left, so mirror the operator when the
585
- // optional was on the right: `x < opt` → `Some(v) => v > x`.
596
+ // Precondition preservation (#349): JavaScript evaluates BOTH operands of
597
+ // `===`, `!==`, `<`, `<=`, `>`, `>=` unconditionally. When `valSide` can
598
+ // carry preconditions (calls, indexing, checked reads, div/mod), bind
599
+ // `valExpr` in a `let` BEFORE matching `optExpr` so:
600
+ // 1. Every precondition in `valSide` is checked even when `optExpr` is `None`.
601
+ // 2. Comparing `bound op _cmp` unwrapped inside `Some` preserves Z3's
602
+ // sequence/map extensionality triggers (unlike `opt == Some(val)`).
603
+ // Pure comparisons (e.g. `res.truncatedBy === "bytes"` in pi-lemmascript)
604
+ // skip the `let` binding completely (zero temporary churn).
586
605
  const op = e.left.ty.kind === "optional" ? e.op : MIRROR_OP[e.op] ?? e.op;
587
606
  const cmpOp = BOOL_OP_MAP[op] ?? op;
588
607
  const noneVal = e.op === "!==" ? true : false;
589
608
  const bound = matchBinder("value");
609
+ if (!_inSpec && valExpr.kind !== "var" && hasPreconditionExpr(valSide)) {
610
+ const tmp = freshName(`_cmp${_cmpCounter++}`);
611
+ return {
612
+ kind: "let",
613
+ name: tmp,
614
+ value: valExpr,
615
+ body: {
616
+ kind: "match", scrutinee: optExpr,
617
+ arms: [
618
+ { pattern: pCtor("some", bound), body: { kind: "binop", op: cmpOp, left: { kind: "var", name: bound }, right: { kind: "var", name: tmp } } },
619
+ { pattern: pCtor("none"), body: { kind: "bool", value: noneVal } },
620
+ ],
621
+ },
622
+ };
623
+ }
590
624
  return {
591
625
  kind: "match", scrutinee: optExpr,
592
626
  arms: [
@@ -1210,6 +1244,8 @@ function lowerExpr(e, binds) {
1210
1244
  return { kind: "var", name };
1211
1245
  }
1212
1246
  return { kind: "havoc", type: e.ty };
1247
+ case "checkedUnwrap":
1248
+ return { kind: "checkedUnwrap", expr: lowerExpr(e.expr, binds) };
1213
1249
  case "someMatch": {
1214
1250
  let someBody;
1215
1251
  let scrutinee;
@@ -1757,7 +1793,7 @@ function transformStmts(stmts, typeDecls) {
1757
1793
  const bodyStmts = insertIncrementBeforeContinue(eliminateTopLevelContinue(transformStmts(s.body, typeDecls)), idxName);
1758
1794
  result.push({
1759
1795
  kind: "forin", idx: idxName, bound: arrSize,
1760
- invariants: [boundInv, ...s.invariants.map(transformExpr)],
1796
+ invariants: [boundInv, ...s.invariants.map(transformSpecExpr)],
1761
1797
  body: [...perIter, ...bodyStmts],
1762
1798
  });
1763
1799
  i++;
@@ -1772,6 +1808,88 @@ let _liftCounter = 0;
1772
1808
  let _callbackCounter = 0;
1773
1809
  // Branch results must not renumber the existing lifted-call temporaries.
1774
1810
  let _branchCounter = 0;
1811
+ let _cmpCounter = 0;
1812
+ // True while lowering proof-only spec clauses (`requires`, `ensures`, `invariants`,
1813
+ // `decreases`, `doneWith`). Prevents executable-only rewrites like `#349` `let _cmp`
1814
+ // from firing inside specifications.
1815
+ let _inSpec = false;
1816
+ function transformSpecExpr(e) {
1817
+ const prev = _inSpec;
1818
+ _inSpec = true;
1819
+ try {
1820
+ return transformExpr(e);
1821
+ }
1822
+ finally {
1823
+ _inSpec = prev;
1824
+ }
1825
+ }
1826
+ // Active narrowing write-back frames (`someMatch` unwraps & union variant arms).
1827
+ let _writeBackFrames = [];
1828
+ // Declared types of in-scope variables and narrowing binders (for optional-field wrap checks).
1829
+ let _varTypes = new Map();
1830
+ /** Look up the declared field type reached by walking `fields` from `rootTy`. */
1831
+ function lookupFieldTy(rootTy, fields, typeDecls) {
1832
+ let cur = rootTy;
1833
+ for (const field of fields) {
1834
+ if (!cur)
1835
+ return null;
1836
+ if (cur.kind === "optional")
1837
+ cur = cur.inner;
1838
+ if (cur.kind !== "user")
1839
+ return null;
1840
+ const decl = declOfTy(typeDecls, cur);
1841
+ if (!decl || decl.kind !== "record" || !decl.fields)
1842
+ return null;
1843
+ const f = decl.fields.find(fi => fi.name === field);
1844
+ if (!f)
1845
+ return null;
1846
+ cur = f.type ?? parseTsType(f.tsType);
1847
+ }
1848
+ return cur ?? null;
1849
+ }
1850
+ /** True if `e` contains any subexpression that can carry a backend precondition
1851
+ * (calls, indexing, checked unwraps, division/modulo). Used to ensure optional
1852
+ * comparisons evaluate `valSide` unconditionally instead of skipping it in a
1853
+ * `None` match arm (#349), while leaving pure literal/variable comparisons
1854
+ * untouched (zero churn on `pi-lemmascript` and existing `examples/`). */
1855
+ const TOTAL_PURE_BUILTINS = new Set([
1856
+ "set.has", "map.has", "array.includes", "string.includes",
1857
+ "string.startsWith", "string.endsWith", "string.indexOf", "string.lastIndexOf",
1858
+ "string.trim", "string.toLowerCase", "string.toUpperCase",
1859
+ ]);
1860
+ function hasPreconditionExpr(e) {
1861
+ switch (e.kind) {
1862
+ case "call":
1863
+ if (e.builtinId && TOTAL_PURE_BUILTINS.has(e.builtinId)) {
1864
+ return hasPreconditionExpr(e.fn) || e.args.some(hasPreconditionExpr);
1865
+ }
1866
+ return true;
1867
+ case "index":
1868
+ return true;
1869
+ case "checkedUnwrap":
1870
+ return true;
1871
+ case "binop":
1872
+ return e.op === "/" || e.op === "%" || hasPreconditionExpr(e.left) || hasPreconditionExpr(e.right);
1873
+ case "unop":
1874
+ return hasPreconditionExpr(e.expr);
1875
+ case "field":
1876
+ return hasPreconditionExpr(e.obj);
1877
+ case "record":
1878
+ return (e.spread !== null && hasPreconditionExpr(e.spread)) || e.fields.some(f => hasPreconditionExpr(f.value));
1879
+ case "arrayLiteral":
1880
+ return e.elems.some(hasPreconditionExpr);
1881
+ case "conditional":
1882
+ return hasPreconditionExpr(e.cond) || hasPreconditionExpr(e.then) || hasPreconditionExpr(e.else);
1883
+ case "nullish":
1884
+ return hasPreconditionExpr(e.left) || hasPreconditionExpr(e.right);
1885
+ case "someMatch":
1886
+ return hasPreconditionExpr(e.scrutinee) || hasPreconditionExpr(e.someBody) || hasPreconditionExpr(e.noneBody);
1887
+ case "tagMatch":
1888
+ return hasPreconditionExpr(e.scrutinee) || e.cases.some(c => hasPreconditionExpr(c.body)) || (e.fallthrough !== null && hasPreconditionExpr(e.fallthrough));
1889
+ default:
1890
+ return false;
1891
+ }
1892
+ }
1775
1893
  function liftMethodCalls(e) {
1776
1894
  const binds = [];
1777
1895
  return { binds, expr: lowerExpr(e, binds) };
@@ -1780,6 +1898,7 @@ function liftMethodCalls(e) {
1780
1898
  function transformStmt(s, typeDecls) {
1781
1899
  switch (s.kind) {
1782
1900
  case "let": {
1901
+ _varTypes.set(s.name, s.ty);
1783
1902
  // Whole-init havoc: emit directly, no lifting
1784
1903
  if (s.init.kind === "havoc") {
1785
1904
  return [{ kind: "let", name: s.name, type: s.ty, mutable: s.mutable, value: { kind: "havoc", type: s.init.ty } }];
@@ -1794,7 +1913,7 @@ function transformStmt(s, typeDecls) {
1794
1913
  value: { kind: "index", arr: arrVar, idx: { kind: "num", value: 0 } } };
1795
1914
  const sliceTail = { kind: "assign", target: arrName,
1796
1915
  value: { kind: "methodCall", obj: arrVar, objTy: init.fn.obj.ty, method: "slice", args: [{ kind: "num", value: 1 }], monadic: false } };
1797
- return [letHead, sliceTail];
1916
+ return [letHead, sliceTail, ...emitWriteBacksForTarget(arrName, _writeBackFrames)];
1798
1917
  }
1799
1918
  }
1800
1919
  // let x = arr.pop() → let x: T? = (Option-expr); arr := (truncated-or-self)
@@ -1805,6 +1924,7 @@ function transformStmt(s, typeDecls) {
1805
1924
  return [
1806
1925
  { kind: "let", name: s.name, type: s.ty, mutable: s.mutable, value: optValue },
1807
1926
  { kind: "assign", target: arrName, value: guardedTrunc },
1927
+ ...emitWriteBacksForTarget(arrName, _writeBackFrames),
1808
1928
  ];
1809
1929
  }
1810
1930
  }
@@ -1859,7 +1979,7 @@ function transformStmt(s, typeDecls) {
1859
1979
  return [...binds, { kind: "let", name: s.name, type: s.ty, mutable: s.mutable, value: expr }];
1860
1980
  }
1861
1981
  case "assign": {
1862
- // x = arr.pop() → x := (Option-expr); arr := (truncated-or-self)
1982
+ // x = arr.pop() → x := (Option-expr); arr := (truncated-or-self) + Place write-back
1863
1983
  if (s.value.kind === "call" && s.value.fn.kind === "field" &&
1864
1984
  s.value.fn.field === "pop" && s.value.fn.obj.ty.kind === "array" &&
1865
1985
  s.value.fn.obj.kind === "var") {
@@ -1868,13 +1988,108 @@ function transformStmt(s, typeDecls) {
1868
1988
  return [
1869
1989
  { kind: "assign", target: s.target, value: optValue },
1870
1990
  { kind: "assign", target: arrName, value: guardedTrunc },
1991
+ ...emitWriteBacksForTarget(arrName, _writeBackFrames),
1871
1992
  ];
1872
1993
  }
1994
+ // Non-`this.` dotted field assignment on a record, union variant, or narrowed
1995
+ // optional record (e.g. `b.count = 5`, `u.v = 99`, `u.items[0] = 10`, `u.box.count = 42`):
1996
+ // lower through active `unwrap` & `variant` frames with cascading write-back.
1997
+ if (s.target.includes(".") && !s.target.startsWith("this.")) {
1998
+ const parts = s.target.split(".");
1999
+ const rootVar = parts[0];
2000
+ const fields = parts.slice(1);
2001
+ const { binds, expr } = liftMethodCalls(s.value);
2002
+ const isUndefRhs = s.value.kind === "var" && s.value.name === "undefined";
2003
+ const isOptRhs = s.value.ty.kind === "optional" || isUndefRhs;
2004
+ const resolved = resolveWriteTargetThroughFrames(rootVar, fields, _writeBackFrames);
2005
+ if (resolved.leafUnwrapFrame) {
2006
+ const frame = resolved.leafUnwrapFrame;
2007
+ if (!isOptRhs) {
2008
+ return [
2009
+ ...binds,
2010
+ { kind: "assign", target: frame.binder, value: expr },
2011
+ ...emitWriteBacksForTarget(frame.binder, _writeBackFrames),
2012
+ ];
2013
+ }
2014
+ // Assigning `undefined` or an `Option<T>` value to a narrowed optional field:
2015
+ // write directly to the enclosing record field without double-wrapping in `Some`.
2016
+ const optExpr = isUndefRhs
2017
+ ? { kind: "constructor", name: "none", type: "Option", args: [] }
2018
+ : expr;
2019
+ if (frame.fields.length > 0) {
2020
+ return [
2021
+ ...binds,
2022
+ { kind: "assign", target: frame.rootVar, value: buildNestedFieldExpr(frame.rootVar, frame.fields, optExpr) },
2023
+ ...emitWriteBacksForTarget(frame.rootVar, _writeBackFrames),
2024
+ ];
2025
+ }
2026
+ return [
2027
+ ...binds,
2028
+ { kind: "assign", target: frame.rootVar, value: optExpr },
2029
+ ...emitWriteBacksForTarget(frame.rootVar, _writeBackFrames),
2030
+ ];
2031
+ }
2032
+ if (resolved.leafVariantBinder) {
2033
+ const binderTy = _varTypes.get(resolved.leafVariantBinder);
2034
+ const rhsExpr = binderTy?.kind === "optional" && !isOptRhs
2035
+ ? { kind: "constructor", name: "some", type: "Option", args: [expr] }
2036
+ : isUndefRhs && binderTy?.kind === "optional"
2037
+ ? { kind: "constructor", name: "none", type: "Option", args: [] }
2038
+ : expr;
2039
+ return [
2040
+ ...binds,
2041
+ { kind: "assign", target: resolved.leafVariantBinder, value: rhsExpr },
2042
+ ...emitWriteBacksForTarget(resolved.leafVariantBinder, _writeBackFrames),
2043
+ ];
2044
+ }
2045
+ if (resolved.remainingFields.length > 0) {
2046
+ const fieldTy = lookupFieldTy(_varTypes.get(resolved.currentRoot), resolved.remainingFields, typeDecls);
2047
+ const rhsExpr = fieldTy?.kind === "optional"
2048
+ ? (isUndefRhs
2049
+ ? { kind: "constructor", name: "none", type: "Option", args: [] }
2050
+ : s.value.ty.kind === "optional"
2051
+ ? expr
2052
+ : { kind: "constructor", name: "some", type: "Option", args: [expr] })
2053
+ : expr;
2054
+ return [
2055
+ ...binds,
2056
+ { kind: "assign", target: resolved.currentRoot, value: buildNestedFieldExpr(resolved.currentRoot, resolved.remainingFields, rhsExpr) },
2057
+ ...emitWriteBacksForTarget(resolved.currentRoot, _writeBackFrames),
2058
+ ];
2059
+ }
2060
+ }
2061
+ // Assignment to a narrowed optional variable (e.g., `arr[0] = v` desugared to
2062
+ // `arr = arr.with(0, v)` or `a = 10` coerced to `Some(10)` by resolve):
2063
+ // update the match binder and write back `arr := Option.Some(binder)` so
2064
+ // storage and binder stay in sync (#342).
2065
+ const activeUnwrap = !s.target.includes(".")
2066
+ ? findActiveUnwrapFrame(s.target, [], _writeBackFrames)
2067
+ : null;
2068
+ if (activeUnwrap) {
2069
+ if (s.value.kind === "call" && s.value.fn.kind === "var" &&
2070
+ s.value.fn.name === "Some" && s.value.args.length === 1) {
2071
+ const { binds, expr } = liftMethodCalls(s.value.args[0]);
2072
+ return [
2073
+ ...binds,
2074
+ { kind: "assign", target: activeUnwrap.binder, value: expr },
2075
+ ...emitWriteBacksForTarget(activeUnwrap.binder, _writeBackFrames),
2076
+ ];
2077
+ }
2078
+ if (s.value.ty.kind !== "optional" &&
2079
+ !(s.value.kind === "var" && s.value.name === "undefined")) {
2080
+ const { binds, expr } = liftMethodCalls(s.value);
2081
+ return [
2082
+ ...binds,
2083
+ { kind: "assign", target: activeUnwrap.binder, value: expr },
2084
+ ...emitWriteBacksForTarget(activeUnwrap.binder, _writeBackFrames),
2085
+ ];
2086
+ }
2087
+ }
1873
2088
  // Top-level method call → direct monadic bind, no lifting needed
1874
2089
  if (s.value.kind === "call" && s.value.callKind === "method")
1875
- return [{ kind: "bind", target: s.target, value: transformExpr(s.value) }];
2090
+ return [{ kind: "bind", target: s.target, value: transformExpr(s.value) }, ...emitWriteBacksForTarget(s.target, _writeBackFrames)];
1876
2091
  const { binds, expr } = liftMethodCalls(s.value);
1877
- return [...binds, { kind: "assign", target: s.target, value: expr }];
2092
+ return [...binds, { kind: "assign", target: s.target, value: expr }, ...emitWriteBacksForTarget(s.target, _writeBackFrames)];
1878
2093
  }
1879
2094
  case "return": {
1880
2095
  const { binds, expr } = liftMethodCalls(s.value);
@@ -1884,22 +2099,57 @@ function transformStmt(s, typeDecls) {
1884
2099
  case "continue": return [{ kind: "continue" }];
1885
2100
  case "expr": {
1886
2101
  // Mutating collection call: m.set(k, v) → m := m.set(k, v) (same for set
1887
- // .add/.delete and array .push). The receiver may be a bare var, or a
1888
- // field path rooted at a var (b.items.push(v) → b := b.(items := b.items + [v])).
2102
+ // .add/.delete and array .push/.unshift/.sort). The receiver may be a bare
2103
+ // var or a field path rooted at a var, with Place write-back through any
2104
+ // enclosing narrowing frames (`someMatch` unwrap or union variant arm).
2105
+ // Non-Place receivers (e.g. `getArr().push(1)`) fail closed instead of
2106
+ // silently discarding the updated collection.
1889
2107
  if (s.expr.kind === "call" && s.expr.fn.kind === "field") {
1890
2108
  const recv = s.expr.fn.obj;
1891
2109
  const f = s.expr.fn.field;
1892
- const isMutating = ((recv.ty.kind === "map" || recv.ty.kind === "set") && (f === "set" || f === "add" || f === "delete")) ||
1893
- (recv.ty.kind === "array" && (f === "push" || f === "unshift" || f === "sort"));
1894
- if (isMutating && recv.kind === "var") {
1895
- const { binds, expr } = liftMethodCalls(s.expr);
1896
- return [...binds, { kind: "assign", target: recv.name, value: expr }];
1897
- }
1898
- if (isMutating && recv.kind === "field") {
1899
- const { binds, expr } = liftMethodCalls(s.expr);
1900
- const upd = buildNestedFieldUpdate(recv, expr);
1901
- if (upd)
1902
- return [...binds, { kind: "assign", target: upd.root, value: upd.value }];
2110
+ if (isMutatingCollectionMethod(recv.ty, f)) {
2111
+ if (recv.kind === "var") {
2112
+ const { binds, expr } = liftMethodCalls(s.expr);
2113
+ return [
2114
+ ...binds,
2115
+ { kind: "assign", target: recv.name, value: expr },
2116
+ ...emitWriteBacksForTarget(recv.name, _writeBackFrames),
2117
+ ];
2118
+ }
2119
+ if (recv.kind === "field") {
2120
+ const { binds, expr } = liftMethodCalls(s.expr);
2121
+ const upd = buildNestedFieldUpdate(recv, expr);
2122
+ if (upd) {
2123
+ return [
2124
+ ...binds,
2125
+ { kind: "assign", target: upd.root, value: upd.value },
2126
+ ...emitWriteBacksForTarget(upd.root, _writeBackFrames),
2127
+ ];
2128
+ }
2129
+ }
2130
+ if (recv.kind === "checkedUnwrap") {
2131
+ const { binds, expr } = liftMethodCalls(s.expr);
2132
+ const wrapped = { kind: "app", fn: "Some", args: [expr] };
2133
+ if (recv.expr.kind === "var") {
2134
+ return [
2135
+ ...binds,
2136
+ { kind: "assign", target: recv.expr.name, value: wrapped },
2137
+ ...emitWriteBacksForTarget(recv.expr.name, _writeBackFrames),
2138
+ ];
2139
+ }
2140
+ if (recv.expr.kind === "field") {
2141
+ const upd = buildNestedFieldUpdate(recv.expr, wrapped);
2142
+ if (upd) {
2143
+ return [
2144
+ ...binds,
2145
+ { kind: "assign", target: upd.root, value: upd.value },
2146
+ ...emitWriteBacksForTarget(upd.root, _writeBackFrames),
2147
+ ];
2148
+ }
2149
+ }
2150
+ }
2151
+ throw new Error(`Unsupported in-place mutation \`${describeReceiver(recv)}.${f}(...)\`: ` +
2152
+ `receiver is not a writable Place rooted at a variable (bind it to a variable or mutate through a field path).`);
1903
2153
  }
1904
2154
  }
1905
2155
  // Optional chaining on map.get at statement level: m.get(k)?.push(v)
@@ -1921,7 +2171,12 @@ function transformStmt(s, typeDecls) {
1921
2171
  const pushed = { kind: "methodCall", obj: directGet, objTy: mapExpr.ty.value, method: "push", args: [pushArg], monadic: false };
1922
2172
  const updated = { kind: "methodCall", obj: mapVar, objTy: mapExpr.ty, method: "set", args: [keyExpr, pushed], monadic: false };
1923
2173
  const hasCond = { kind: "methodCall", obj: mapVar, objTy: mapExpr.ty, method: "has", args: [keyExpr], monadic: false };
1924
- return [{ kind: "if", cond: hasCond, then: [{ kind: "assign", target: mapName, value: updated }], else: [] }];
2174
+ return [{
2175
+ kind: "if",
2176
+ cond: hasCond,
2177
+ then: [{ kind: "assign", target: mapName, value: updated }, ...emitWriteBacksForTarget(mapName, _writeBackFrames)],
2178
+ else: [],
2179
+ }];
1925
2180
  }
1926
2181
  }
1927
2182
  const { binds, expr } = liftMethodCalls(s.expr);
@@ -1936,9 +2191,9 @@ function transformStmt(s, typeDecls) {
1936
2191
  return [{
1937
2192
  kind: "while",
1938
2193
  cond: transformExpr(asCondition(s.cond)),
1939
- invariants: s.invariants.map(transformExpr),
1940
- decreasing: s.decreases ? transformExpr(s.decreases) : null,
1941
- doneWith: s.doneWith ? transformExpr(s.doneWith) : null,
2194
+ invariants: s.invariants.map(transformSpecExpr),
2195
+ decreasing: s.decreases ? transformSpecExpr(s.decreases) : null,
2196
+ doneWith: s.doneWith ? transformSpecExpr(s.doneWith) : null,
1942
2197
  body: eliminateTopLevelContinue(transformStmts(s.body, typeDecls)),
1943
2198
  }];
1944
2199
  case "throw":
@@ -1957,7 +2212,21 @@ function transformStmt(s, typeDecls) {
1957
2212
  const path = asTAccessPath(s.scrutinee);
1958
2213
  if (path) {
1959
2214
  const replaced = replacePathInTStmts(s.someBody, path, s.binder, s.binderTy);
1960
- const someBody = transformStmts(replaced, typeDecls);
2215
+ _varTypes.set(s.binder, s.binderTy);
2216
+ _writeBackFrames.push(makeUnwrapFrame(s.binder, path.rootVar, path.fields));
2217
+ let someBody;
2218
+ try {
2219
+ someBody = transformStmts(replaced, typeDecls);
2220
+ }
2221
+ finally {
2222
+ _writeBackFrames.pop();
2223
+ }
2224
+ if (_opts.backend === "lean" && collectAssignedIrTargets(someBody).has(s.binder)) {
2225
+ someBody = [
2226
+ { kind: "let", name: s.binder, type: s.binderTy, mutable: true, value: varE(s.binder) },
2227
+ ...someBody,
2228
+ ];
2229
+ }
1961
2230
  const noneBody = transformStmts(s.noneBody, typeDecls);
1962
2231
  const scrutinee = path.fields.length === 0 ? varE(path.rootVar) : transformExpr(s.scrutinee);
1963
2232
  return [{
@@ -2029,7 +2298,8 @@ function emitMatchStmt(scrutinee, typeName, cases, fallthrough, typeDecls) {
2029
2298
  const path = asTAccessPath(scrutinee);
2030
2299
  const isPath = !!path && path.fields.length > 0;
2031
2300
  const prefix = path ? [path.rootVar, ...path.fields].join("_") : "?";
2032
- function transformArmBody(body, fields) {
2301
+ const baseUnionName = tyBaseName(typeName);
2302
+ function transformArmBody(body, fields, ctorName) {
2033
2303
  let stmts;
2034
2304
  if (isPath && path) {
2035
2305
  // Path scrutinee: the matched value is referred to by the bare path, so
@@ -2046,10 +2316,36 @@ function emitMatchStmt(scrutinee, typeName, cases, fallthrough, typeDecls) {
2046
2316
  stmts = replaceVarInTStmts(stmts, prefix, matchBinder(f.name, prefix), f.type ?? parseTsType(f.tsType));
2047
2317
  }
2048
2318
  }
2049
- return transformStmts(stmts, typeDecls);
2319
+ const pushVariant = !isPath && !!ctorName && fields.length > 0;
2320
+ if (pushVariant) {
2321
+ for (const f of fields) {
2322
+ _varTypes.set(matchBinder(f.name, prefix), f.type ?? parseTsType(f.tsType));
2323
+ }
2324
+ _writeBackFrames.push(makeVariantFrame(prefix, baseUnionName, ctorName, fields.map(f => ({ fieldName: f.name, binder: matchBinder(f.name, prefix) }))));
2325
+ }
2326
+ let lowered;
2327
+ try {
2328
+ lowered = transformStmts(stmts, typeDecls);
2329
+ }
2330
+ finally {
2331
+ if (pushVariant)
2332
+ _writeBackFrames.pop();
2333
+ }
2334
+ if (_opts.backend === "lean" && pushVariant) {
2335
+ const assigned = collectAssignedIrTargets(lowered);
2336
+ const mutShadows = fields
2337
+ .filter(f => assigned.has(matchBinder(f.name, prefix)))
2338
+ .map(f => {
2339
+ const b = matchBinder(f.name, prefix);
2340
+ return { kind: "let", name: b, type: f.type ?? parseTsType(f.tsType), mutable: true, value: varE(b) };
2341
+ });
2342
+ if (mutShadows.length > 0)
2343
+ lowered = [...mutShadows, ...lowered];
2344
+ }
2345
+ return lowered;
2050
2346
  }
2051
2347
  const armCases = cases.map(c => ({ name: c.variant, body: c.body }));
2052
- const arms = buildMatchArms(armCases, prefix, typeName, typeDecls, (body, _vn, fields) => transformArmBody(body, fields));
2348
+ const arms = buildMatchArms(armCases, prefix, typeName, typeDecls, (body, _vn, fields, ctorName) => transformArmBody(body, fields, ctorName));
2053
2349
  // Add the fallthrough arm whenever the listed cases don't cover every
2054
2350
  // variant — needed for exhaustiveness even when there's no `else`
2055
2351
  // (`fallthrough` empty), e.g. `if (Array.isArray(x)) {...}` with no else
@@ -2061,14 +2357,14 @@ function emitMatchStmt(scrutinee, typeName, cases, fallthrough, typeDecls) {
2061
2357
  // Exactly one variant left — destructure so the fallthrough body can
2062
2358
  // access variant-specific fields (Lean requires this; Dafny tolerates `_`).
2063
2359
  const pattern = buildMatchPattern(remaining.name, remaining.fields, prefix);
2064
- const body = transformArmBody(fallthrough, remaining.fields);
2360
+ const body = transformArmBody(fallthrough, remaining.fields, remaining.name);
2065
2361
  arms.push({ pattern, body });
2066
2362
  }
2067
2363
  else {
2068
2364
  arms.push({ pattern: pWild(), body: transformStmts(fallthrough, typeDecls) });
2069
2365
  }
2070
2366
  }
2071
- return { kind: "match", scrutinee: isPath ? transformExpr(scrutinee) : varE(prefix), arms };
2367
+ return { kind: "match", scrutinee: (isPath || scrutinee.kind === "checkedUnwrap") ? transformExpr(scrutinee) : varE(prefix), arms };
2072
2368
  }
2073
2369
  /** Replace bare `var(oldName)` references → `var(newName)` with the given type.
2074
2370
  * Used by emitMatchStmt for synth array-unions where the variant has a single
@@ -2151,9 +2447,36 @@ function emitSwitchStmt(s, typeDecls) {
2151
2447
  : ef
2152
2448
  ? buildMatchArms(cases, undefined, ctorDecl.name, typeDecls, (body) => transformStmts(body, typeDecls))
2153
2449
  : buildMatchArms(cases, s.expr.kind === "var" ? s.expr.name : "?", ctorDecl.name, typeDecls, (body, vn, fields, ctorName) => {
2154
- let out = transformStmts(replaceFieldAccessInTStmts(body, vn, fields), typeDecls);
2450
+ const pushVariant = !!ctorName && !!vn && vn !== "?" && !!baseName && fields.length > 0;
2451
+ const variantMeta = ctorName ? ctorDecl?.variants?.find(v => v.name === ctorName) : undefined;
2452
+ if (pushVariant) {
2453
+ for (const f of fields) {
2454
+ const vf = variantMeta?.fields.find(vf => vf.name === f.name);
2455
+ _varTypes.set(matchBinder(f.name, vn), vf?.type ?? parseTsType(f.tsType));
2456
+ }
2457
+ _writeBackFrames.push(makeVariantFrame(vn, baseName, ctorName, fields.map(f => ({ fieldName: f.name, binder: matchBinder(f.name, vn) }))));
2458
+ }
2459
+ let out;
2460
+ try {
2461
+ out = transformStmts(replaceFieldAccessInTStmts(body, vn, fields), typeDecls);
2462
+ }
2463
+ finally {
2464
+ if (pushVariant)
2465
+ _writeBackFrames.pop();
2466
+ }
2155
2467
  if (ctorName && vn && baseName)
2156
2468
  out = stampScrutineeUpdates(out, vn, ctorName, baseName);
2469
+ if (_opts.backend === "lean" && pushVariant) {
2470
+ const assigned = collectAssignedIrTargets(out);
2471
+ const mutShadows = fields
2472
+ .filter(f => assigned.has(matchBinder(f.name, vn)))
2473
+ .map(f => {
2474
+ const b = matchBinder(f.name, vn);
2475
+ return { kind: "let", name: b, type: parseTsType(f.tsType), mutable: true, value: varE(b) };
2476
+ });
2477
+ if (mutShadows.length > 0)
2478
+ out = [...mutShadows, ...out];
2479
+ }
2157
2480
  return out;
2158
2481
  });
2159
2482
  if (s.defaultBody.length > 0)
@@ -2166,7 +2489,9 @@ function replaceFieldsInTStmts(stmts, objName, replacements) {
2166
2489
  if (replacements.length === 0)
2167
2490
  return stmts;
2168
2491
  return stmts.map(s => mapTStmt(s, e => {
2169
- if (e.kind === "field" && e.obj.kind === "var" && e.obj.name === objName) {
2492
+ const objMatches = e.kind === "field" && ((e.obj.kind === "var" && e.obj.name === objName) ||
2493
+ (e.obj.kind === "checkedUnwrap" && e.obj.expr.kind === "var" && e.obj.expr.name === objName));
2494
+ if (objMatches && e.kind === "field") {
2170
2495
  const r = replacements.find(r => r.fieldName === e.field);
2171
2496
  if (r) {
2172
2497
  const ty = e.ty.kind !== "unknown" ? e.ty : r.fallbackTy;
@@ -2241,6 +2566,8 @@ function projectStructuralCallArgsInTStmts(stmts, varName, fields) {
2241
2566
  function asTAccessPath(e) {
2242
2567
  if (e.kind === "var")
2243
2568
  return { rootVar: e.name, fields: [] };
2569
+ if (e.kind === "checkedUnwrap")
2570
+ return asTAccessPath(e.expr);
2244
2571
  if (e.kind === "field") {
2245
2572
  const inner = asTAccessPath(e.obj);
2246
2573
  if (!inner)
@@ -2253,9 +2580,14 @@ function asTAccessPath(e) {
2253
2580
  function matchesAccessPath(e, path) {
2254
2581
  const collected = [];
2255
2582
  let cur = e;
2256
- while (cur.kind === "field") {
2257
- collected.unshift(cur.field);
2258
- cur = cur.obj;
2583
+ while (cur.kind === "field" || cur.kind === "checkedUnwrap") {
2584
+ if (cur.kind === "field") {
2585
+ collected.unshift(cur.field);
2586
+ cur = cur.obj;
2587
+ }
2588
+ else {
2589
+ cur = cur.expr;
2590
+ }
2259
2591
  }
2260
2592
  if (cur.kind !== "var" || cur.name !== path.rootVar)
2261
2593
  return false;
@@ -2573,6 +2905,9 @@ export function transformModule(mod, specImport, moduleBaseOverride) {
2573
2905
  _liftCounter = 0;
2574
2906
  _callbackCounter = 0;
2575
2907
  _branchCounter = 0;
2908
+ _cmpCounter = 0;
2909
+ _inSpec = false;
2910
+ _writeBackFrames = [];
2576
2911
  _typeDecls = mod.typeDecls;
2577
2912
  _neededKindHelpers = new Map();
2578
2913
  _pureDefNames = new Set(mod.functions.filter(f => f.isPure).map(f => f.name));
@@ -2594,22 +2929,23 @@ export function transformModule(mod, specImport, moduleBaseOverride) {
2594
2929
  if (body) {
2595
2930
  // For pure-function lemmas, replace \result with the function call.
2596
2931
  const fnCall = { kind: "app", fn: fn.name, args: fn.params.map(p => ({ kind: "var", name: p.name })) };
2597
- const ensures = fn.ensures.map(e => replaceVar(transformExpr(e), "\\result", fnCall));
2932
+ const ensures = fn.ensures.map(e => replaceVar(transformSpecExpr(e), "\\result", fnCall));
2598
2933
  pureDefs.push({
2599
2934
  kind: "def",
2600
2935
  name: fn.name,
2601
2936
  typeParams: fn.typeParams,
2602
2937
  params: fn.params.map(p => ({ name: p.name, type: p.ty })),
2603
2938
  returnType: fn.returnTy,
2604
- requires: fn.requires.map(transformExpr),
2939
+ requires: fn.requires.map(transformSpecExpr),
2605
2940
  ensures,
2606
- decreases: fn.decreases ? transformExpr(fn.decreases) : null,
2941
+ decreases: fn.decreases ? transformSpecExpr(fn.decreases) : null,
2607
2942
  body,
2608
2943
  });
2609
2944
  }
2610
2945
  else if (fn.forcePure) {
2611
2946
  // //@ pure but body can't be auto-converted — emit function by method
2612
2947
  _forofCounters.clear();
2948
+ _writeBackFrames = [];
2613
2949
  const methodBody = promoteAssignedLets(transformStmts(fn.body, mod.typeDecls));
2614
2950
  defByMethods.push({
2615
2951
  kind: "def-by-method",
@@ -2617,9 +2953,9 @@ export function transformModule(mod, specImport, moduleBaseOverride) {
2617
2953
  typeParams: fn.typeParams,
2618
2954
  params: fn.params.map(p => ({ name: p.name, type: p.ty })),
2619
2955
  returnType: fn.returnTy,
2620
- requires: fn.requires.map(transformExpr),
2621
- ensures: fn.ensures.map(transformExpr),
2622
- decreases: fn.decreases ? transformExpr(fn.decreases) : null,
2956
+ requires: fn.requires.map(transformSpecExpr),
2957
+ ensures: fn.ensures.map(transformSpecExpr),
2958
+ decreases: fn.decreases ? transformSpecExpr(fn.decreases) : null,
2623
2959
  methodBody,
2624
2960
  });
2625
2961
  }
@@ -2664,10 +3000,10 @@ export function transformModule(mod, specImport, moduleBaseOverride) {
2664
3000
  typeParams: ext.typeParams,
2665
3001
  params: ext.params.map(p => ({ name: p.name, type: p.ty })),
2666
3002
  returnType: ext.returnTy,
2667
- requires: ext.requires.map(transformExpr),
3003
+ requires: ext.requires.map(transformSpecExpr),
2668
3004
  ensures: ext.ensures.map(e => ext.impure
2669
- ? transformExpr(e)
2670
- : replaceVar(transformExpr(e), "\\result", fnCall)),
3005
+ ? transformSpecExpr(e)
3006
+ : replaceVar(transformSpecExpr(e), "\\result", fnCall)),
2671
3007
  impure: ext.impure,
2672
3008
  };
2673
3009
  });
@@ -2678,14 +3014,23 @@ export function transformModule(mod, specImport, moduleBaseOverride) {
2678
3014
  const pureDefNames = new Set([...pureDefs.map(d => d.name), ...defByMethods.map(d => d.name)]);
2679
3015
  const methods = mod.functions.map(fn => {
2680
3016
  const ensures = [];
2681
- for (const e of fn.ensures) {
2682
- const m = ensuresToMatch(e, mod.typeDecls);
2683
- if (m)
2684
- ensures.push(m);
2685
- else
2686
- ensures.push(transformExpr(e));
3017
+ const prevInSpec = _inSpec;
3018
+ _inSpec = true;
3019
+ try {
3020
+ for (const e of fn.ensures) {
3021
+ const m = ensuresToMatch(e, mod.typeDecls);
3022
+ if (m)
3023
+ ensures.push(m);
3024
+ else
3025
+ ensures.push(transformExpr(e));
3026
+ }
3027
+ }
3028
+ finally {
3029
+ _inSpec = prevInSpec;
2687
3030
  }
2688
3031
  _forofCounters.clear();
3032
+ _writeBackFrames = [];
3033
+ _varTypes = new Map(fn.params.map(p => [p.name, p.ty]));
2689
3034
  let body = pureDefNames.has(fn.name)
2690
3035
  ? [{ kind: "return", value: { kind: "app", fn: _opts.backend === "lean" ? `Pure.${fn.name}` : fn.name, args: fn.params.map(p => ({ kind: "var", name: p.name })) } }]
2691
3036
  : promoteAssignedLets(transformStmts(fn.body, mod.typeDecls));
@@ -2698,13 +3043,18 @@ export function transformModule(mod, specImport, moduleBaseOverride) {
2698
3043
  // since loom's default loop-exit fact `¬guard` does not hold across a break.
2699
3044
  if (_opts.backend === "lean" && !pureDefNames.has(fn.name)) {
2700
3045
  body = matchToIfChains(body);
2701
- const resultInvariants = fn.ensures.map(e => replaceVar(transformExpr(e), "\\result", { kind: "var", name: "_loopRet" }));
3046
+ const resultInvariants = fn.ensures.map(e => replaceVar(transformSpecExpr(e), "\\result", { kind: "var", name: "_loopRet" }));
2702
3047
  body = eliminateReturnInLoops(body, fn.returnTy, resultInvariants);
2703
3048
  requireDoneWithForBreaks(body, fn.name);
2704
3049
  }
2705
- // Shadow reassigned parameters with mutable locals
3050
+ // Shadow reassigned parameters with mutable locals (including parameters
3051
+ // written back via Place lowering inside `someMatch`, `tagMatch`, or `switch`).
2706
3052
  const paramNames = new Set(fn.params.map(p => p.name));
2707
3053
  const reassigned = findReassignedNames(fn.body, paramNames);
3054
+ for (const target of collectAssignedIrTargets(body)) {
3055
+ if (paramNames.has(target))
3056
+ reassigned.add(target);
3057
+ }
2708
3058
  if (reassigned.size > 0) {
2709
3059
  const shadows = fn.params
2710
3060
  .filter(p => reassigned.has(p.name))
@@ -2717,27 +3067,41 @@ export function transformModule(mod, specImport, moduleBaseOverride) {
2717
3067
  typeParams: fn.typeParams,
2718
3068
  params: fn.params.map(p => ({ name: p.name, type: p.ty })),
2719
3069
  returnType: fn.returnTy,
2720
- requires: fn.requires.map(transformExpr),
3070
+ requires: fn.requires.map(transformSpecExpr),
2721
3071
  ensures,
2722
- decreases: fn.decreases ? transformExpr(fn.decreases) : null,
3072
+ decreases: fn.decreases ? transformSpecExpr(fn.decreases) : null,
2723
3073
  body,
2724
3074
  };
2725
3075
  });
2726
3076
  // Class declarations
2727
3077
  const classDecls = (mod.classes ?? []).map(cls => {
2728
3078
  const classMethods = cls.methods.map(fn => {
2729
- const ensures = fn.ensures.map(transformExpr);
3079
+ const ensures = fn.ensures.map(transformSpecExpr);
2730
3080
  _forofCounters.clear();
2731
- const body = promoteAssignedLets(transformStmts(fn.body, mod.typeDecls));
3081
+ _writeBackFrames = [];
3082
+ _varTypes = new Map(fn.params.map(p => [p.name, p.ty]));
3083
+ let body = promoteAssignedLets(transformStmts(fn.body, mod.typeDecls));
3084
+ const paramNames = new Set(fn.params.map(p => p.name));
3085
+ const reassigned = findReassignedNames(fn.body, paramNames);
3086
+ for (const target of collectAssignedIrTargets(body)) {
3087
+ if (paramNames.has(target))
3088
+ reassigned.add(target);
3089
+ }
3090
+ if (reassigned.size > 0) {
3091
+ const shadows = fn.params
3092
+ .filter(p => reassigned.has(p.name))
3093
+ .map(p => ({ kind: "let", name: p.name, type: p.ty, mutable: true, value: { kind: "var", name: p.name } }));
3094
+ body = [...shadows, ...body];
3095
+ }
2732
3096
  return {
2733
3097
  kind: "method",
2734
3098
  name: fn.name,
2735
3099
  typeParams: fn.typeParams,
2736
3100
  params: fn.params.map(p => ({ name: p.name, type: p.ty })),
2737
3101
  returnType: fn.returnTy,
2738
- requires: fn.requires.map(transformExpr),
3102
+ requires: fn.requires.map(transformSpecExpr),
2739
3103
  ensures,
2740
- decreases: fn.decreases ? transformExpr(fn.decreases) : null,
3104
+ decreases: fn.decreases ? transformSpecExpr(fn.decreases) : null,
2741
3105
  body,
2742
3106
  };
2743
3107
  });