lemmascript 0.6.11 → 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.
- package/package.json +1 -1
- package/tools/dist/alias-check-pass.js +1038 -0
- package/tools/dist/alias-check.js +67 -0
- package/tools/dist/autohavoc.js +4 -0
- package/tools/dist/checked-reads.js +384 -0
- package/tools/dist/dafny-commands.js +19 -7
- package/tools/dist/dafny-emit.js +28 -23
- package/tools/dist/dafny-proof-additions.js +285 -14
- package/tools/dist/extract.js +118 -260
- package/tools/dist/ir.js +2 -1
- package/tools/dist/lean-emit.js +34 -2
- package/tools/dist/lexical-names.js +212 -0
- package/tools/dist/lsc.js +7 -6
- package/tools/dist/names.js +4 -0
- package/tools/dist/narrow-checks.js +415 -0
- package/tools/dist/narrow.js +93 -7
- package/tools/dist/peephole.js +1 -0
- package/tools/dist/place-lowering.js +219 -0
- package/tools/dist/places.js +123 -0
- package/tools/dist/resolve.js +350 -23
- package/tools/dist/specparser.js +41 -12
- package/tools/dist/transform.js +447 -113
package/tools/dist/transform.js
CHANGED
|
@@ -5,13 +5,14 @@
|
|
|
5
5
|
* No type lookups, no string parsing, no re-inference.
|
|
6
6
|
*/
|
|
7
7
|
import { isBigInt, tyEqual } from "./typedir.js";
|
|
8
|
-
import { anyExpr, anyExprInStmts, pWild, pCtor, pLiteral, patternBinders,
|
|
8
|
+
import { anyExpr, anyExprInStmts, pWild, pCtor, pLiteral, patternBinders, patternCtor } from "./ir.js";
|
|
9
9
|
import { parseTsType } from "./types.js";
|
|
10
10
|
import { freshName } from "./names.js";
|
|
11
11
|
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) };
|
|
@@ -85,50 +87,7 @@ function mapStmt(s, f) {
|
|
|
85
87
|
case "assert": return { ...s, expr: r(s.expr) };
|
|
86
88
|
}
|
|
87
89
|
}
|
|
88
|
-
/** Rename free occurrences of `from` to `to`, stopping at every construct that
|
|
89
|
-
* rebinds `from` — lambda params, `let`/`let-bind`/`ghostLet` (shadows the
|
|
90
|
-
* rest of the block), `match` arm patterns, `forall`/`exists`, and `for-in`
|
|
91
|
-
* indices. Capture-avoiding: a nested scope that reintroduces `from` keeps its
|
|
92
|
-
* own binding untouched. `mapExpr` doesn't descend into lambda bodies, so this
|
|
93
|
-
* walks them by hand — statement binders are tracked only at that body's top
|
|
94
|
-
* level, which is enough for the sole caller (dafny-emit's
|
|
95
|
-
* `comprehensionBinder`). TODO: generalize if more callers need this. */
|
|
96
90
|
const varE = (name) => ({ kind: "var", name });
|
|
97
|
-
export function renameFreeVar(e, from, to) {
|
|
98
|
-
const f = (x) => {
|
|
99
|
-
if (x.kind === "var")
|
|
100
|
-
return x.name === from ? { ...x, name: to } : x;
|
|
101
|
-
// let-expression: `value` is in the outer scope (rename), `body` sees the
|
|
102
|
-
// rebound `from` (leave it), so handle the recursion here to stop descent.
|
|
103
|
-
if (x.kind === "let" && x.name === from)
|
|
104
|
-
return { ...x, value: mapExpr(x.value, f) };
|
|
105
|
-
if ((x.kind === "forall" || x.kind === "exists") && x.var === from)
|
|
106
|
-
return x;
|
|
107
|
-
if (x.kind === "match") {
|
|
108
|
-
return { ...x, scrutinee: mapExpr(x.scrutinee, f), arms: x.arms.map(a => patternBinds(a.pattern, from) ? a : { ...a, body: mapExpr(a.body, f) }) };
|
|
109
|
-
}
|
|
110
|
-
if (x.kind === "lambda") {
|
|
111
|
-
if (x.params.some(p => p.name === from))
|
|
112
|
-
return x; // param shadows `from`
|
|
113
|
-
const body = [];
|
|
114
|
-
let shadowed = false;
|
|
115
|
-
for (const s of x.body) {
|
|
116
|
-
if (shadowed) {
|
|
117
|
-
body.push(s);
|
|
118
|
-
continue;
|
|
119
|
-
}
|
|
120
|
-
body.push(s.kind === "forin" && s.idx === from
|
|
121
|
-
? { ...s, bound: mapExpr(s.bound, f) } // idx shadows in the loop body
|
|
122
|
-
: mapStmt(s, f));
|
|
123
|
-
if ((s.kind === "let" || s.kind === "let-bind" || s.kind === "ghostLet") && s.name === from)
|
|
124
|
-
shadowed = true;
|
|
125
|
-
}
|
|
126
|
-
return { ...x, body };
|
|
127
|
-
}
|
|
128
|
-
return null;
|
|
129
|
-
};
|
|
130
|
-
return mapExpr(e, f);
|
|
131
|
-
}
|
|
132
91
|
/** Map over all sub-expressions in a TExpr (typed IR). */
|
|
133
92
|
function mapTExpr(e, f) {
|
|
134
93
|
const hit = f(e);
|
|
@@ -156,6 +115,7 @@ function mapTExpr(e, f) {
|
|
|
156
115
|
: s) };
|
|
157
116
|
case "nullish": return { ...e, left: r(e.left), right: r(e.right) };
|
|
158
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) };
|
|
159
119
|
case "tagMatch": return { ...e, scrutinee: r(e.scrutinee),
|
|
160
120
|
cases: e.cases.map(c => ({ ...c, body: r(c.body) })),
|
|
161
121
|
fallthrough: e.fallthrough ? r(e.fallthrough) : null };
|
|
@@ -176,9 +136,12 @@ function mapTStmt(s, f) {
|
|
|
176
136
|
case "throw": return s;
|
|
177
137
|
case "expr": return { ...s, expr: r(s.expr) };
|
|
178
138
|
case "if": return { ...s, cond: r(s.cond), then: s.then.map(t => mapTStmt(t, f)), else: s.else.map(t => mapTStmt(t, f)) };
|
|
179
|
-
case "while": return { ...s, cond: r(s.cond), invariants: s.invariants.map(r),
|
|
139
|
+
case "while": return { ...s, cond: r(s.cond), invariants: s.invariants.map(r),
|
|
140
|
+
decreases: s.decreases ? r(s.decreases) : null,
|
|
141
|
+
doneWith: s.doneWith ? r(s.doneWith) : null, body: s.body.map(t => mapTStmt(t, f)) };
|
|
180
142
|
case "switch": return { ...s, expr: r(s.expr), cases: s.cases.map(c => ({ ...c, body: c.body.map(t => mapTStmt(t, f)) })), defaultBody: s.defaultBody.map(t => mapTStmt(t, f)) };
|
|
181
|
-
case "forof": return { ...s, iterable: r(s.iterable), invariants: s.invariants.map(r),
|
|
143
|
+
case "forof": return { ...s, iterable: r(s.iterable), invariants: s.invariants.map(r),
|
|
144
|
+
doneWith: s.doneWith ? r(s.doneWith) : null, body: s.body.map(t => mapTStmt(t, f)) };
|
|
182
145
|
case "ghostLet": return { ...s, init: r(s.init) };
|
|
183
146
|
case "ghostAssign": return { ...s, value: r(s.value) };
|
|
184
147
|
case "assert": return { ...s, expr: r(s.expr) };
|
|
@@ -446,7 +409,9 @@ function promoteAssignedLets(stmts) {
|
|
|
446
409
|
}
|
|
447
410
|
/** Build a nested record-update assigning `newVal` to a field-path receiver
|
|
448
411
|
* rooted at a var: `b.a.items` → `b := b.(a := b.a.(items := newVal))`.
|
|
449
|
-
*
|
|
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. */
|
|
450
415
|
function buildNestedFieldUpdate(recv, newVal) {
|
|
451
416
|
if (recv.kind !== "field")
|
|
452
417
|
return null;
|
|
@@ -455,6 +420,13 @@ function buildNestedFieldUpdate(recv, newVal) {
|
|
|
455
420
|
return { root: recv.obj.name, value: upd };
|
|
456
421
|
if (recv.obj.kind === "field")
|
|
457
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
|
+
}
|
|
458
430
|
return null;
|
|
459
431
|
}
|
|
460
432
|
/** Promote every spread segment before concatenation, preserving evaluation
|
|
@@ -621,12 +593,34 @@ function lowerExpr(e, binds) {
|
|
|
621
593
|
const valExpr = valSide.kind === "str" && innerTy.kind === "user"
|
|
622
594
|
? { kind: "constructor", name: valSide.value, type: innerTy.name, args: [] }
|
|
623
595
|
: lowerExpr(valSide, binds);
|
|
624
|
-
//
|
|
625
|
-
//
|
|
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).
|
|
626
605
|
const op = e.left.ty.kind === "optional" ? e.op : MIRROR_OP[e.op] ?? e.op;
|
|
627
606
|
const cmpOp = BOOL_OP_MAP[op] ?? op;
|
|
628
607
|
const noneVal = e.op === "!==" ? true : false;
|
|
629
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
|
+
}
|
|
630
624
|
return {
|
|
631
625
|
kind: "match", scrutinee: optExpr,
|
|
632
626
|
arms: [
|
|
@@ -1250,6 +1244,8 @@ function lowerExpr(e, binds) {
|
|
|
1250
1244
|
return { kind: "var", name };
|
|
1251
1245
|
}
|
|
1252
1246
|
return { kind: "havoc", type: e.ty };
|
|
1247
|
+
case "checkedUnwrap":
|
|
1248
|
+
return { kind: "checkedUnwrap", expr: lowerExpr(e.expr, binds) };
|
|
1253
1249
|
case "someMatch": {
|
|
1254
1250
|
let someBody;
|
|
1255
1251
|
let scrutinee;
|
|
@@ -1736,12 +1732,13 @@ function transformStmts(stmts, typeDecls) {
|
|
|
1736
1732
|
const iterExpr = transformExpr(s.iterable);
|
|
1737
1733
|
// All for-of shapes lower to the same range loop `for idx in 0..seq.size`;
|
|
1738
1734
|
// they differ only in (a) which indexable `seq` is iterated and (b) the
|
|
1739
|
-
// per-iteration `let`s that bind the loop names.
|
|
1740
|
-
//
|
|
1735
|
+
// per-iteration `let`s that bind the loop names. The counter name was
|
|
1736
|
+
// minted by resolve, where specs naming it are resolved; the suffix
|
|
1737
|
+
// numbers this loop's helper names. Each shape fills in `seq` + `perIter`.
|
|
1741
1738
|
const count = _forofCounters.get(headName) ?? 0;
|
|
1742
1739
|
_forofCounters.set(headName, count + 1);
|
|
1743
1740
|
const suffix = count === 0 ? "" : `${count + 1}`;
|
|
1744
|
-
const idxName =
|
|
1741
|
+
const idxName = s.idx;
|
|
1745
1742
|
const idxVar = { kind: "var", name: idxName };
|
|
1746
1743
|
let seq;
|
|
1747
1744
|
let perIter;
|
|
@@ -1796,7 +1793,7 @@ function transformStmts(stmts, typeDecls) {
|
|
|
1796
1793
|
const bodyStmts = insertIncrementBeforeContinue(eliminateTopLevelContinue(transformStmts(s.body, typeDecls)), idxName);
|
|
1797
1794
|
result.push({
|
|
1798
1795
|
kind: "forin", idx: idxName, bound: arrSize,
|
|
1799
|
-
invariants: [boundInv, ...s.invariants.map(
|
|
1796
|
+
invariants: [boundInv, ...s.invariants.map(transformSpecExpr)],
|
|
1800
1797
|
body: [...perIter, ...bodyStmts],
|
|
1801
1798
|
});
|
|
1802
1799
|
i++;
|
|
@@ -1811,6 +1808,88 @@ let _liftCounter = 0;
|
|
|
1811
1808
|
let _callbackCounter = 0;
|
|
1812
1809
|
// Branch results must not renumber the existing lifted-call temporaries.
|
|
1813
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
|
+
}
|
|
1814
1893
|
function liftMethodCalls(e) {
|
|
1815
1894
|
const binds = [];
|
|
1816
1895
|
return { binds, expr: lowerExpr(e, binds) };
|
|
@@ -1819,6 +1898,7 @@ function liftMethodCalls(e) {
|
|
|
1819
1898
|
function transformStmt(s, typeDecls) {
|
|
1820
1899
|
switch (s.kind) {
|
|
1821
1900
|
case "let": {
|
|
1901
|
+
_varTypes.set(s.name, s.ty);
|
|
1822
1902
|
// Whole-init havoc: emit directly, no lifting
|
|
1823
1903
|
if (s.init.kind === "havoc") {
|
|
1824
1904
|
return [{ kind: "let", name: s.name, type: s.ty, mutable: s.mutable, value: { kind: "havoc", type: s.init.ty } }];
|
|
@@ -1833,7 +1913,7 @@ function transformStmt(s, typeDecls) {
|
|
|
1833
1913
|
value: { kind: "index", arr: arrVar, idx: { kind: "num", value: 0 } } };
|
|
1834
1914
|
const sliceTail = { kind: "assign", target: arrName,
|
|
1835
1915
|
value: { kind: "methodCall", obj: arrVar, objTy: init.fn.obj.ty, method: "slice", args: [{ kind: "num", value: 1 }], monadic: false } };
|
|
1836
|
-
return [letHead, sliceTail];
|
|
1916
|
+
return [letHead, sliceTail, ...emitWriteBacksForTarget(arrName, _writeBackFrames)];
|
|
1837
1917
|
}
|
|
1838
1918
|
}
|
|
1839
1919
|
// let x = arr.pop() → let x: T? = (Option-expr); arr := (truncated-or-self)
|
|
@@ -1844,6 +1924,7 @@ function transformStmt(s, typeDecls) {
|
|
|
1844
1924
|
return [
|
|
1845
1925
|
{ kind: "let", name: s.name, type: s.ty, mutable: s.mutable, value: optValue },
|
|
1846
1926
|
{ kind: "assign", target: arrName, value: guardedTrunc },
|
|
1927
|
+
...emitWriteBacksForTarget(arrName, _writeBackFrames),
|
|
1847
1928
|
];
|
|
1848
1929
|
}
|
|
1849
1930
|
}
|
|
@@ -1898,7 +1979,7 @@ function transformStmt(s, typeDecls) {
|
|
|
1898
1979
|
return [...binds, { kind: "let", name: s.name, type: s.ty, mutable: s.mutable, value: expr }];
|
|
1899
1980
|
}
|
|
1900
1981
|
case "assign": {
|
|
1901
|
-
// x = arr.pop() → x := (Option-expr); arr := (truncated-or-self)
|
|
1982
|
+
// x = arr.pop() → x := (Option-expr); arr := (truncated-or-self) + Place write-back
|
|
1902
1983
|
if (s.value.kind === "call" && s.value.fn.kind === "field" &&
|
|
1903
1984
|
s.value.fn.field === "pop" && s.value.fn.obj.ty.kind === "array" &&
|
|
1904
1985
|
s.value.fn.obj.kind === "var") {
|
|
@@ -1907,13 +1988,108 @@ function transformStmt(s, typeDecls) {
|
|
|
1907
1988
|
return [
|
|
1908
1989
|
{ kind: "assign", target: s.target, value: optValue },
|
|
1909
1990
|
{ kind: "assign", target: arrName, value: guardedTrunc },
|
|
1991
|
+
...emitWriteBacksForTarget(arrName, _writeBackFrames),
|
|
1910
1992
|
];
|
|
1911
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
|
+
}
|
|
1912
2088
|
// Top-level method call → direct monadic bind, no lifting needed
|
|
1913
2089
|
if (s.value.kind === "call" && s.value.callKind === "method")
|
|
1914
|
-
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)];
|
|
1915
2091
|
const { binds, expr } = liftMethodCalls(s.value);
|
|
1916
|
-
return [...binds, { kind: "assign", target: s.target, value: expr }];
|
|
2092
|
+
return [...binds, { kind: "assign", target: s.target, value: expr }, ...emitWriteBacksForTarget(s.target, _writeBackFrames)];
|
|
1917
2093
|
}
|
|
1918
2094
|
case "return": {
|
|
1919
2095
|
const { binds, expr } = liftMethodCalls(s.value);
|
|
@@ -1923,22 +2099,57 @@ function transformStmt(s, typeDecls) {
|
|
|
1923
2099
|
case "continue": return [{ kind: "continue" }];
|
|
1924
2100
|
case "expr": {
|
|
1925
2101
|
// Mutating collection call: m.set(k, v) → m := m.set(k, v) (same for set
|
|
1926
|
-
// .add/.delete and array .push). The receiver may be a bare
|
|
1927
|
-
// field path rooted at a var
|
|
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.
|
|
1928
2107
|
if (s.expr.kind === "call" && s.expr.fn.kind === "field") {
|
|
1929
2108
|
const recv = s.expr.fn.obj;
|
|
1930
2109
|
const f = s.expr.fn.field;
|
|
1931
|
-
|
|
1932
|
-
(recv.
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
if (
|
|
1941
|
-
|
|
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).`);
|
|
1942
2153
|
}
|
|
1943
2154
|
}
|
|
1944
2155
|
// Optional chaining on map.get at statement level: m.get(k)?.push(v)
|
|
@@ -1960,7 +2171,12 @@ function transformStmt(s, typeDecls) {
|
|
|
1960
2171
|
const pushed = { kind: "methodCall", obj: directGet, objTy: mapExpr.ty.value, method: "push", args: [pushArg], monadic: false };
|
|
1961
2172
|
const updated = { kind: "methodCall", obj: mapVar, objTy: mapExpr.ty, method: "set", args: [keyExpr, pushed], monadic: false };
|
|
1962
2173
|
const hasCond = { kind: "methodCall", obj: mapVar, objTy: mapExpr.ty, method: "has", args: [keyExpr], monadic: false };
|
|
1963
|
-
return [{
|
|
2174
|
+
return [{
|
|
2175
|
+
kind: "if",
|
|
2176
|
+
cond: hasCond,
|
|
2177
|
+
then: [{ kind: "assign", target: mapName, value: updated }, ...emitWriteBacksForTarget(mapName, _writeBackFrames)],
|
|
2178
|
+
else: [],
|
|
2179
|
+
}];
|
|
1964
2180
|
}
|
|
1965
2181
|
}
|
|
1966
2182
|
const { binds, expr } = liftMethodCalls(s.expr);
|
|
@@ -1975,9 +2191,9 @@ function transformStmt(s, typeDecls) {
|
|
|
1975
2191
|
return [{
|
|
1976
2192
|
kind: "while",
|
|
1977
2193
|
cond: transformExpr(asCondition(s.cond)),
|
|
1978
|
-
invariants: s.invariants.map(
|
|
1979
|
-
decreasing: s.decreases ?
|
|
1980
|
-
doneWith: s.doneWith ?
|
|
2194
|
+
invariants: s.invariants.map(transformSpecExpr),
|
|
2195
|
+
decreasing: s.decreases ? transformSpecExpr(s.decreases) : null,
|
|
2196
|
+
doneWith: s.doneWith ? transformSpecExpr(s.doneWith) : null,
|
|
1981
2197
|
body: eliminateTopLevelContinue(transformStmts(s.body, typeDecls)),
|
|
1982
2198
|
}];
|
|
1983
2199
|
case "throw":
|
|
@@ -1996,7 +2212,21 @@ function transformStmt(s, typeDecls) {
|
|
|
1996
2212
|
const path = asTAccessPath(s.scrutinee);
|
|
1997
2213
|
if (path) {
|
|
1998
2214
|
const replaced = replacePathInTStmts(s.someBody, path, s.binder, s.binderTy);
|
|
1999
|
-
|
|
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
|
+
}
|
|
2000
2230
|
const noneBody = transformStmts(s.noneBody, typeDecls);
|
|
2001
2231
|
const scrutinee = path.fields.length === 0 ? varE(path.rootVar) : transformExpr(s.scrutinee);
|
|
2002
2232
|
return [{
|
|
@@ -2068,7 +2298,8 @@ function emitMatchStmt(scrutinee, typeName, cases, fallthrough, typeDecls) {
|
|
|
2068
2298
|
const path = asTAccessPath(scrutinee);
|
|
2069
2299
|
const isPath = !!path && path.fields.length > 0;
|
|
2070
2300
|
const prefix = path ? [path.rootVar, ...path.fields].join("_") : "?";
|
|
2071
|
-
|
|
2301
|
+
const baseUnionName = tyBaseName(typeName);
|
|
2302
|
+
function transformArmBody(body, fields, ctorName) {
|
|
2072
2303
|
let stmts;
|
|
2073
2304
|
if (isPath && path) {
|
|
2074
2305
|
// Path scrutinee: the matched value is referred to by the bare path, so
|
|
@@ -2085,10 +2316,36 @@ function emitMatchStmt(scrutinee, typeName, cases, fallthrough, typeDecls) {
|
|
|
2085
2316
|
stmts = replaceVarInTStmts(stmts, prefix, matchBinder(f.name, prefix), f.type ?? parseTsType(f.tsType));
|
|
2086
2317
|
}
|
|
2087
2318
|
}
|
|
2088
|
-
|
|
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;
|
|
2089
2346
|
}
|
|
2090
2347
|
const armCases = cases.map(c => ({ name: c.variant, body: c.body }));
|
|
2091
|
-
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));
|
|
2092
2349
|
// Add the fallthrough arm whenever the listed cases don't cover every
|
|
2093
2350
|
// variant — needed for exhaustiveness even when there's no `else`
|
|
2094
2351
|
// (`fallthrough` empty), e.g. `if (Array.isArray(x)) {...}` with no else
|
|
@@ -2100,14 +2357,14 @@ function emitMatchStmt(scrutinee, typeName, cases, fallthrough, typeDecls) {
|
|
|
2100
2357
|
// Exactly one variant left — destructure so the fallthrough body can
|
|
2101
2358
|
// access variant-specific fields (Lean requires this; Dafny tolerates `_`).
|
|
2102
2359
|
const pattern = buildMatchPattern(remaining.name, remaining.fields, prefix);
|
|
2103
|
-
const body = transformArmBody(fallthrough, remaining.fields);
|
|
2360
|
+
const body = transformArmBody(fallthrough, remaining.fields, remaining.name);
|
|
2104
2361
|
arms.push({ pattern, body });
|
|
2105
2362
|
}
|
|
2106
2363
|
else {
|
|
2107
2364
|
arms.push({ pattern: pWild(), body: transformStmts(fallthrough, typeDecls) });
|
|
2108
2365
|
}
|
|
2109
2366
|
}
|
|
2110
|
-
return { kind: "match", scrutinee: isPath ? transformExpr(scrutinee) : varE(prefix), arms };
|
|
2367
|
+
return { kind: "match", scrutinee: (isPath || scrutinee.kind === "checkedUnwrap") ? transformExpr(scrutinee) : varE(prefix), arms };
|
|
2111
2368
|
}
|
|
2112
2369
|
/** Replace bare `var(oldName)` references → `var(newName)` with the given type.
|
|
2113
2370
|
* Used by emitMatchStmt for synth array-unions where the variant has a single
|
|
@@ -2190,9 +2447,36 @@ function emitSwitchStmt(s, typeDecls) {
|
|
|
2190
2447
|
: ef
|
|
2191
2448
|
? buildMatchArms(cases, undefined, ctorDecl.name, typeDecls, (body) => transformStmts(body, typeDecls))
|
|
2192
2449
|
: buildMatchArms(cases, s.expr.kind === "var" ? s.expr.name : "?", ctorDecl.name, typeDecls, (body, vn, fields, ctorName) => {
|
|
2193
|
-
|
|
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
|
+
}
|
|
2194
2467
|
if (ctorName && vn && baseName)
|
|
2195
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
|
+
}
|
|
2196
2480
|
return out;
|
|
2197
2481
|
});
|
|
2198
2482
|
if (s.defaultBody.length > 0)
|
|
@@ -2205,7 +2489,9 @@ function replaceFieldsInTStmts(stmts, objName, replacements) {
|
|
|
2205
2489
|
if (replacements.length === 0)
|
|
2206
2490
|
return stmts;
|
|
2207
2491
|
return stmts.map(s => mapTStmt(s, e => {
|
|
2208
|
-
|
|
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") {
|
|
2209
2495
|
const r = replacements.find(r => r.fieldName === e.field);
|
|
2210
2496
|
if (r) {
|
|
2211
2497
|
const ty = e.ty.kind !== "unknown" ? e.ty : r.fallbackTy;
|
|
@@ -2280,6 +2566,8 @@ function projectStructuralCallArgsInTStmts(stmts, varName, fields) {
|
|
|
2280
2566
|
function asTAccessPath(e) {
|
|
2281
2567
|
if (e.kind === "var")
|
|
2282
2568
|
return { rootVar: e.name, fields: [] };
|
|
2569
|
+
if (e.kind === "checkedUnwrap")
|
|
2570
|
+
return asTAccessPath(e.expr);
|
|
2283
2571
|
if (e.kind === "field") {
|
|
2284
2572
|
const inner = asTAccessPath(e.obj);
|
|
2285
2573
|
if (!inner)
|
|
@@ -2292,9 +2580,14 @@ function asTAccessPath(e) {
|
|
|
2292
2580
|
function matchesAccessPath(e, path) {
|
|
2293
2581
|
const collected = [];
|
|
2294
2582
|
let cur = e;
|
|
2295
|
-
while (cur.kind === "field") {
|
|
2296
|
-
|
|
2297
|
-
|
|
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
|
+
}
|
|
2298
2591
|
}
|
|
2299
2592
|
if (cur.kind !== "var" || cur.name !== path.rootVar)
|
|
2300
2593
|
return false;
|
|
@@ -2302,14 +2595,23 @@ function matchesAccessPath(e, path) {
|
|
|
2302
2595
|
return false;
|
|
2303
2596
|
return collected.every((f, i) => f === path.fields[i]);
|
|
2304
2597
|
}
|
|
2305
|
-
/** Replace every
|
|
2598
|
+
/** Replace every read of `path` with `var(binder, binderTy)`. Extraction
|
|
2599
|
+
* leaves no binding that shadows another (see LexicalNames), so the name
|
|
2600
|
+
* identifies the variable, also inside a lambda that captures it. */
|
|
2306
2601
|
function replacePathInTExpr(expr, path, binder, binderTy) {
|
|
2307
|
-
return mapTExpr(expr, e =>
|
|
2308
|
-
|
|
2602
|
+
return mapTExpr(expr, e => {
|
|
2603
|
+
if (matchesAccessPath(e, path))
|
|
2604
|
+
return { kind: "var", name: binder, ty: binderTy };
|
|
2605
|
+
if (e.kind === "lambda")
|
|
2606
|
+
return { ...e,
|
|
2607
|
+
params: e.params.map(p => p.defaultValue
|
|
2608
|
+
? { ...p, defaultValue: replacePathInTExpr(p.defaultValue, path, binder, binderTy) } : p),
|
|
2609
|
+
body: replacePathInTStmts(e.body, path, binder, binderTy) };
|
|
2610
|
+
return null;
|
|
2611
|
+
});
|
|
2309
2612
|
}
|
|
2310
2613
|
function replacePathInTStmts(stmts, path, binder, binderTy) {
|
|
2311
|
-
return stmts.map(s => mapTStmt(s, e =>
|
|
2312
|
-
? { kind: "var", name: binder, ty: binderTy } : null));
|
|
2614
|
+
return stmts.map(s => mapTStmt(s, e => replacePathInTExpr(e, path, binder, binderTy)));
|
|
2313
2615
|
}
|
|
2314
2616
|
// ── Pure function generation ─────────────────────────────────
|
|
2315
2617
|
function transformPureBody(stmts, typeDecls) {
|
|
@@ -2603,6 +2905,9 @@ export function transformModule(mod, specImport, moduleBaseOverride) {
|
|
|
2603
2905
|
_liftCounter = 0;
|
|
2604
2906
|
_callbackCounter = 0;
|
|
2605
2907
|
_branchCounter = 0;
|
|
2908
|
+
_cmpCounter = 0;
|
|
2909
|
+
_inSpec = false;
|
|
2910
|
+
_writeBackFrames = [];
|
|
2606
2911
|
_typeDecls = mod.typeDecls;
|
|
2607
2912
|
_neededKindHelpers = new Map();
|
|
2608
2913
|
_pureDefNames = new Set(mod.functions.filter(f => f.isPure).map(f => f.name));
|
|
@@ -2624,22 +2929,23 @@ export function transformModule(mod, specImport, moduleBaseOverride) {
|
|
|
2624
2929
|
if (body) {
|
|
2625
2930
|
// For pure-function lemmas, replace \result with the function call.
|
|
2626
2931
|
const fnCall = { kind: "app", fn: fn.name, args: fn.params.map(p => ({ kind: "var", name: p.name })) };
|
|
2627
|
-
const ensures = fn.ensures.map(e => replaceVar(
|
|
2932
|
+
const ensures = fn.ensures.map(e => replaceVar(transformSpecExpr(e), "\\result", fnCall));
|
|
2628
2933
|
pureDefs.push({
|
|
2629
2934
|
kind: "def",
|
|
2630
2935
|
name: fn.name,
|
|
2631
2936
|
typeParams: fn.typeParams,
|
|
2632
2937
|
params: fn.params.map(p => ({ name: p.name, type: p.ty })),
|
|
2633
2938
|
returnType: fn.returnTy,
|
|
2634
|
-
requires: fn.requires.map(
|
|
2939
|
+
requires: fn.requires.map(transformSpecExpr),
|
|
2635
2940
|
ensures,
|
|
2636
|
-
decreases: fn.decreases ?
|
|
2941
|
+
decreases: fn.decreases ? transformSpecExpr(fn.decreases) : null,
|
|
2637
2942
|
body,
|
|
2638
2943
|
});
|
|
2639
2944
|
}
|
|
2640
2945
|
else if (fn.forcePure) {
|
|
2641
2946
|
// //@ pure but body can't be auto-converted — emit function by method
|
|
2642
2947
|
_forofCounters.clear();
|
|
2948
|
+
_writeBackFrames = [];
|
|
2643
2949
|
const methodBody = promoteAssignedLets(transformStmts(fn.body, mod.typeDecls));
|
|
2644
2950
|
defByMethods.push({
|
|
2645
2951
|
kind: "def-by-method",
|
|
@@ -2647,9 +2953,9 @@ export function transformModule(mod, specImport, moduleBaseOverride) {
|
|
|
2647
2953
|
typeParams: fn.typeParams,
|
|
2648
2954
|
params: fn.params.map(p => ({ name: p.name, type: p.ty })),
|
|
2649
2955
|
returnType: fn.returnTy,
|
|
2650
|
-
requires: fn.requires.map(
|
|
2651
|
-
ensures: fn.ensures.map(
|
|
2652
|
-
decreases: fn.decreases ?
|
|
2956
|
+
requires: fn.requires.map(transformSpecExpr),
|
|
2957
|
+
ensures: fn.ensures.map(transformSpecExpr),
|
|
2958
|
+
decreases: fn.decreases ? transformSpecExpr(fn.decreases) : null,
|
|
2653
2959
|
methodBody,
|
|
2654
2960
|
});
|
|
2655
2961
|
}
|
|
@@ -2694,10 +3000,10 @@ export function transformModule(mod, specImport, moduleBaseOverride) {
|
|
|
2694
3000
|
typeParams: ext.typeParams,
|
|
2695
3001
|
params: ext.params.map(p => ({ name: p.name, type: p.ty })),
|
|
2696
3002
|
returnType: ext.returnTy,
|
|
2697
|
-
requires: ext.requires.map(
|
|
3003
|
+
requires: ext.requires.map(transformSpecExpr),
|
|
2698
3004
|
ensures: ext.ensures.map(e => ext.impure
|
|
2699
|
-
?
|
|
2700
|
-
: replaceVar(
|
|
3005
|
+
? transformSpecExpr(e)
|
|
3006
|
+
: replaceVar(transformSpecExpr(e), "\\result", fnCall)),
|
|
2701
3007
|
impure: ext.impure,
|
|
2702
3008
|
};
|
|
2703
3009
|
});
|
|
@@ -2708,14 +3014,23 @@ export function transformModule(mod, specImport, moduleBaseOverride) {
|
|
|
2708
3014
|
const pureDefNames = new Set([...pureDefs.map(d => d.name), ...defByMethods.map(d => d.name)]);
|
|
2709
3015
|
const methods = mod.functions.map(fn => {
|
|
2710
3016
|
const ensures = [];
|
|
2711
|
-
|
|
2712
|
-
|
|
2713
|
-
|
|
2714
|
-
|
|
2715
|
-
|
|
2716
|
-
|
|
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;
|
|
2717
3030
|
}
|
|
2718
3031
|
_forofCounters.clear();
|
|
3032
|
+
_writeBackFrames = [];
|
|
3033
|
+
_varTypes = new Map(fn.params.map(p => [p.name, p.ty]));
|
|
2719
3034
|
let body = pureDefNames.has(fn.name)
|
|
2720
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 })) } }]
|
|
2721
3036
|
: promoteAssignedLets(transformStmts(fn.body, mod.typeDecls));
|
|
@@ -2728,13 +3043,18 @@ export function transformModule(mod, specImport, moduleBaseOverride) {
|
|
|
2728
3043
|
// since loom's default loop-exit fact `¬guard` does not hold across a break.
|
|
2729
3044
|
if (_opts.backend === "lean" && !pureDefNames.has(fn.name)) {
|
|
2730
3045
|
body = matchToIfChains(body);
|
|
2731
|
-
const resultInvariants = fn.ensures.map(e => replaceVar(
|
|
3046
|
+
const resultInvariants = fn.ensures.map(e => replaceVar(transformSpecExpr(e), "\\result", { kind: "var", name: "_loopRet" }));
|
|
2732
3047
|
body = eliminateReturnInLoops(body, fn.returnTy, resultInvariants);
|
|
2733
3048
|
requireDoneWithForBreaks(body, fn.name);
|
|
2734
3049
|
}
|
|
2735
|
-
// 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`).
|
|
2736
3052
|
const paramNames = new Set(fn.params.map(p => p.name));
|
|
2737
3053
|
const reassigned = findReassignedNames(fn.body, paramNames);
|
|
3054
|
+
for (const target of collectAssignedIrTargets(body)) {
|
|
3055
|
+
if (paramNames.has(target))
|
|
3056
|
+
reassigned.add(target);
|
|
3057
|
+
}
|
|
2738
3058
|
if (reassigned.size > 0) {
|
|
2739
3059
|
const shadows = fn.params
|
|
2740
3060
|
.filter(p => reassigned.has(p.name))
|
|
@@ -2747,27 +3067,41 @@ export function transformModule(mod, specImport, moduleBaseOverride) {
|
|
|
2747
3067
|
typeParams: fn.typeParams,
|
|
2748
3068
|
params: fn.params.map(p => ({ name: p.name, type: p.ty })),
|
|
2749
3069
|
returnType: fn.returnTy,
|
|
2750
|
-
requires: fn.requires.map(
|
|
3070
|
+
requires: fn.requires.map(transformSpecExpr),
|
|
2751
3071
|
ensures,
|
|
2752
|
-
decreases: fn.decreases ?
|
|
3072
|
+
decreases: fn.decreases ? transformSpecExpr(fn.decreases) : null,
|
|
2753
3073
|
body,
|
|
2754
3074
|
};
|
|
2755
3075
|
});
|
|
2756
3076
|
// Class declarations
|
|
2757
3077
|
const classDecls = (mod.classes ?? []).map(cls => {
|
|
2758
3078
|
const classMethods = cls.methods.map(fn => {
|
|
2759
|
-
const ensures = fn.ensures.map(
|
|
3079
|
+
const ensures = fn.ensures.map(transformSpecExpr);
|
|
2760
3080
|
_forofCounters.clear();
|
|
2761
|
-
|
|
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
|
+
}
|
|
2762
3096
|
return {
|
|
2763
3097
|
kind: "method",
|
|
2764
3098
|
name: fn.name,
|
|
2765
3099
|
typeParams: fn.typeParams,
|
|
2766
3100
|
params: fn.params.map(p => ({ name: p.name, type: p.ty })),
|
|
2767
3101
|
returnType: fn.returnTy,
|
|
2768
|
-
requires: fn.requires.map(
|
|
3102
|
+
requires: fn.requires.map(transformSpecExpr),
|
|
2769
3103
|
ensures,
|
|
2770
|
-
decreases: fn.decreases ?
|
|
3104
|
+
decreases: fn.decreases ? transformSpecExpr(fn.decreases) : null,
|
|
2771
3105
|
body,
|
|
2772
3106
|
};
|
|
2773
3107
|
});
|