lemmascript 0.6.14 → 0.6.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -0
- package/package.json +1 -1
- package/tools/dist/alias-check-pass.js +2 -1
- package/tools/dist/builtins.js +19 -19
- package/tools/dist/checked-reads.js +74 -9
- package/tools/dist/condition-facts.js +49 -5
- package/tools/dist/config.js +42 -6
- package/tools/dist/dafny-commands.js +22 -6
- package/tools/dist/dafny-emit.js +1 -1
- package/tools/dist/dafny-proof-additions.js +1 -1
- package/tools/dist/lean-emit.js +64 -13
- package/tools/dist/lsc.js +10 -5
- package/tools/dist/narrow.js +24 -31
- package/tools/dist/place-lowering.js +22 -63
- package/tools/dist/resolve.js +470 -116
- package/tools/dist/run-log.js +15 -1
- package/tools/dist/transform.js +529 -443
- package/tools/dist/typedecls.js +7 -0
package/tools/dist/transform.js
CHANGED
|
@@ -7,12 +7,12 @@
|
|
|
7
7
|
import { isBigInt, optAbsent, tyEqual } from "./typedir.js";
|
|
8
8
|
import { anyExpr, anyExprInStmts, pWild, pCtor, pLiteral, patternBinders, patternCtor } from "./ir.js";
|
|
9
9
|
import { parseTsType } from "./types.js";
|
|
10
|
-
import { freshName } from "./names.js";
|
|
10
|
+
import { freshName, freshNameWhere, isUserName } 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
|
-
import { declOf, declOfKind, declOfTy, unionDeclOfTy, declWithVariant, tyBaseName } from "./typedecls.js";
|
|
15
|
-
import { buildNestedFieldExpr, collectAssignedIrTargets, describeReceiver, emitWriteBacksForTarget, findActiveUnwrapFrame, isMutatingCollectionMethod, makeUnwrapFrame,
|
|
14
|
+
import { declOf, declOfKind, declOfTy, unionDeclOfTy, declWithVariant, tyBaseName, remainingVariant } from "./typedecls.js";
|
|
15
|
+
import { buildNestedFieldExpr, collectAssignedIrTargets, describeReceiver, emitWriteBacksForTarget, findActiveUnwrapFrame, isMutatingCollectionMethod, makeUnwrapFrame, resolveWriteTargetThroughFrames, } from "./place-lowering.js";
|
|
16
16
|
// ── Generic IR walkers ──────────────────────────────────────
|
|
17
17
|
/**
|
|
18
18
|
* Map over all sub-expressions in an Expr. `f` is called on each node;
|
|
@@ -80,15 +80,69 @@ function mapStmt(s, f) {
|
|
|
80
80
|
const scr = r(s.scrutinee);
|
|
81
81
|
return { ...s, scrutinee: scr, arms: s.arms.map(a => ({ ...a, body: a.body.map(t => mapStmt(t, f)) })) };
|
|
82
82
|
}
|
|
83
|
-
case "while": return { ...s, cond: r(s.cond), invariants: s.invariants.map(r),
|
|
84
|
-
|
|
83
|
+
case "while": return { ...s, cond: r(s.cond), invariants: s.invariants.map(r),
|
|
84
|
+
decreasing: s.decreasing ? r(s.decreasing) : null,
|
|
85
|
+
doneWith: s.doneWith ? r(s.doneWith) : null,
|
|
86
|
+
body: s.body.map(t => mapStmt(t, f)) };
|
|
87
|
+
case "forin": return { ...s, bound: r(s.bound), invariants: s.invariants.map(r),
|
|
88
|
+
body: s.body.map(t => mapStmt(t, f)) };
|
|
85
89
|
case "ghostLet": return { ...s, value: r(s.value) };
|
|
86
90
|
case "ghostAssign": return { ...s, value: r(s.value) };
|
|
87
91
|
case "assert": return { ...s, expr: r(s.expr) };
|
|
88
92
|
}
|
|
89
93
|
}
|
|
90
94
|
const varE = (name) => ({ kind: "var", name });
|
|
91
|
-
/** Map over
|
|
95
|
+
/** Map `f` over a lambda body unless a parameter rebinds `name`. `mapExpr`
|
|
96
|
+
* doesn't descend into lambda bodies, so substitutions that must reach
|
|
97
|
+
* closures call this. Statement binders are tracked only at the body's top
|
|
98
|
+
* level: a `let`/`let-bind`/`ghostLet` of `name` shadows it for the rest of
|
|
99
|
+
* the body, and a `for-in` index of `name` shadows it inside that loop. */
|
|
100
|
+
function mapLambdaBody(x, name, f) {
|
|
101
|
+
if (x.params.some(p => p.name === name))
|
|
102
|
+
return x;
|
|
103
|
+
const body = [];
|
|
104
|
+
let shadowed = false;
|
|
105
|
+
for (const s of x.body) {
|
|
106
|
+
if (shadowed) {
|
|
107
|
+
body.push(s);
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
body.push(s.kind === "forin" && s.idx === name
|
|
111
|
+
? { ...s, bound: mapExpr(s.bound, f) }
|
|
112
|
+
: mapStmt(s, f));
|
|
113
|
+
if ((s.kind === "let" || s.kind === "let-bind" || s.kind === "ghostLet") && s.name === name)
|
|
114
|
+
shadowed = true;
|
|
115
|
+
}
|
|
116
|
+
return { ...x, body };
|
|
117
|
+
}
|
|
118
|
+
/** Rename free occurrences of `from` to `to`, stopping at every construct that
|
|
119
|
+
* rebinds `from` — lambda params, `let`/`let-bind`/`ghostLet` (shadows the
|
|
120
|
+
* rest of the block), `match` arm patterns, `forall`/`exists`, and `for-in`
|
|
121
|
+
* indices. Capture-avoiding: a nested scope that reintroduces `from` keeps its
|
|
122
|
+
* own binding untouched. Lambda bodies are walked by `mapLambdaBody`. */
|
|
123
|
+
function renameFreeVar(e, from, to) {
|
|
124
|
+
const f = (x) => {
|
|
125
|
+
if (x.kind === "var")
|
|
126
|
+
return x.name === from ? { ...x, name: to } : x;
|
|
127
|
+
// let-expression: `value` is in the outer scope (rename), `body` sees the
|
|
128
|
+
// rebound `from` (leave it), so handle the recursion here to stop descent.
|
|
129
|
+
if (x.kind === "let" && x.name === from)
|
|
130
|
+
return { ...x, value: mapExpr(x.value, f) };
|
|
131
|
+
if ((x.kind === "forall" || x.kind === "exists") && x.var === from)
|
|
132
|
+
return x;
|
|
133
|
+
if (x.kind === "match") {
|
|
134
|
+
return { ...x, scrutinee: mapExpr(x.scrutinee, f), arms: x.arms.map(a => patternBinders(a.pattern).includes(from) ? a : { ...a, body: mapExpr(a.body, f) }) };
|
|
135
|
+
}
|
|
136
|
+
if (x.kind === "lambda")
|
|
137
|
+
return mapLambdaBody(x, from, f);
|
|
138
|
+
return null;
|
|
139
|
+
};
|
|
140
|
+
return mapExpr(e, f);
|
|
141
|
+
}
|
|
142
|
+
/** Map over all sub-expressions in a TExpr (typed IR), including lambda
|
|
143
|
+
* defaults and bodies. Extraction leaves no binding that shadows another
|
|
144
|
+
* (see LexicalNames), so callers substituting for a narrowed name can rely
|
|
145
|
+
* on names identifying their variables across nested scopes (#353). */
|
|
92
146
|
function mapTExpr(e, f) {
|
|
93
147
|
const hit = f(e);
|
|
94
148
|
if (hit)
|
|
@@ -121,7 +175,9 @@ function mapTExpr(e, f) {
|
|
|
121
175
|
fallthrough: e.fallthrough ? r(e.fallthrough) : null };
|
|
122
176
|
case "forall": return { ...e, body: r(e.body) };
|
|
123
177
|
case "exists": return { ...e, body: r(e.body) };
|
|
124
|
-
case "lambda": return e
|
|
178
|
+
case "lambda": return { ...e,
|
|
179
|
+
params: e.params.map(p => p.defaultValue ? { ...p, defaultValue: r(p.defaultValue) } : p),
|
|
180
|
+
body: e.body.map(s => mapTStmt(s, f)) };
|
|
125
181
|
}
|
|
126
182
|
}
|
|
127
183
|
/** Map over all expressions in a TStmt tree (typed IR). */
|
|
@@ -199,16 +255,24 @@ function kindHelperDecl(decl) {
|
|
|
199
255
|
* collisions in nested matches on different variables. `freshName` closes
|
|
200
256
|
* the residual gap: a user variable literally named `_value`/`_x_field` in an
|
|
201
257
|
* arm body would still be captured, so prime on any module-wide collision.
|
|
202
|
-
* Deterministic, so the pattern binder and its body substitutions agree.
|
|
203
|
-
|
|
258
|
+
* Deterministic, so the pattern binder and its body substitutions agree.
|
|
259
|
+
* `taken` adds names the arm already reads, such as an outer narrowing's
|
|
260
|
+
* binder substituted into the arm before this match was lowered. */
|
|
261
|
+
function matchBinder(fieldName, prefix, taken) {
|
|
204
262
|
const safePrefix = prefix === "\\result"
|
|
205
263
|
? "result"
|
|
206
264
|
: prefix?.replace(/[^A-Za-z0-9_]/g, "_");
|
|
207
|
-
|
|
265
|
+
const base = safePrefix ? `_${safePrefix}_${fieldName}` : `_${fieldName}`;
|
|
266
|
+
return taken ? freshNameWhere(base, n => isUserName(n) || taken(n)) : freshName(base);
|
|
208
267
|
}
|
|
209
268
|
/** Build a match arm pattern like `.VariantName _v_field1 _v_field2` from variant info. */
|
|
210
|
-
function buildMatchPattern(variantName, fields, scopePrefix) {
|
|
211
|
-
return pCtor(variantName, ...fields.map(f => matchBinder(f.name, scopePrefix)));
|
|
269
|
+
function buildMatchPattern(variantName, fields, scopePrefix, taken) {
|
|
270
|
+
return pCtor(variantName, ...fields.map(f => matchBinder(f.name, scopePrefix, taken)));
|
|
271
|
+
}
|
|
272
|
+
/** Build a binder-free wildcard match pattern like `.VariantName _ _` for
|
|
273
|
+
* imperative union matches that read and update live storage directly (#405). */
|
|
274
|
+
function buildWildcardMatchPattern(variantName, fields) {
|
|
275
|
+
return pCtor(variantName, ...fields.map(() => "_"));
|
|
212
276
|
}
|
|
213
277
|
const _forofCounters = new Map();
|
|
214
278
|
function isNat(ty) { return ty.kind === "nat"; }
|
|
@@ -458,6 +522,31 @@ function promoteAssignedLets(stmts) {
|
|
|
458
522
|
});
|
|
459
523
|
return fix(stmts);
|
|
460
524
|
}
|
|
525
|
+
/** Lower an in-place write assigning `newVal` to any writable Place receiver
|
|
526
|
+
* (`var`, `field` chain, or `checkedUnwrap` around either). */
|
|
527
|
+
function buildPlaceWrite(recv, newVal) {
|
|
528
|
+
if (recv.kind === "var")
|
|
529
|
+
return { target: recv.name, value: newVal };
|
|
530
|
+
if (recv.kind === "field") {
|
|
531
|
+
const upd = buildNestedFieldUpdate(recv, newVal);
|
|
532
|
+
return upd ? { target: upd.root, value: upd.value } : null;
|
|
533
|
+
}
|
|
534
|
+
if (recv.kind === "checkedUnwrap") {
|
|
535
|
+
const wrapped = wrapCheckedUnwrapValue(newVal, recv.expr.ty);
|
|
536
|
+
return buildPlaceWrite(recv.expr, wrapped);
|
|
537
|
+
}
|
|
538
|
+
return null;
|
|
539
|
+
}
|
|
540
|
+
/** Root variable of a writable Place receiver (`var`, `field` chain, or `checkedUnwrap`). */
|
|
541
|
+
function placeRootVar(recv) {
|
|
542
|
+
if (recv.kind === "var")
|
|
543
|
+
return recv.name;
|
|
544
|
+
if (recv.kind === "field")
|
|
545
|
+
return placeRootVar(recv.obj);
|
|
546
|
+
if (recv.kind === "checkedUnwrap")
|
|
547
|
+
return placeRootVar(recv.expr);
|
|
548
|
+
return null;
|
|
549
|
+
}
|
|
461
550
|
/** Build a nested record-update assigning `newVal` to a field-path receiver
|
|
462
551
|
* rooted at a var: `b.a.items` → `b := b.(a := b.a.(items := newVal))`.
|
|
463
552
|
* Handles `checkedUnwrap` hops along the path by wrapping the updated record
|
|
@@ -466,7 +555,16 @@ function promoteAssignedLets(stmts) {
|
|
|
466
555
|
function buildNestedFieldUpdate(recv, newVal) {
|
|
467
556
|
if (recv.kind !== "field")
|
|
468
557
|
return null;
|
|
469
|
-
const
|
|
558
|
+
const objTy = recv.obj.ty.kind === "optional" || recv.obj.ty.kind === "nullish" ? recv.obj.ty.inner : recv.obj.ty;
|
|
559
|
+
const unionBase = objTy.kind === "user" && declOfKind(_typeDecls, tyBaseName(objTy.name), "discriminated-union")
|
|
560
|
+
? tyBaseName(objTy.name)
|
|
561
|
+
: undefined;
|
|
562
|
+
const upd = {
|
|
563
|
+
kind: "record",
|
|
564
|
+
spread: lowerExpr(recv.obj, null),
|
|
565
|
+
fields: [{ name: recv.field, value: newVal }],
|
|
566
|
+
...(unionBase ? { ctor: recv.ofVariant, ctorOf: unionBase } : {}),
|
|
567
|
+
};
|
|
470
568
|
if (recv.obj.kind === "var")
|
|
471
569
|
return { root: recv.obj.name, value: upd };
|
|
472
570
|
if (recv.obj.kind === "field")
|
|
@@ -1120,16 +1218,19 @@ function lowerExpr(e, binds) {
|
|
|
1120
1218
|
const owners = decl?.variants?.filter(v => v.fields.some(f => f.name === e.field)) ?? [];
|
|
1121
1219
|
if (owners.length > 0) {
|
|
1122
1220
|
// Shared field name with differing declared types: those destructors
|
|
1123
|
-
// are renamed per-constructor
|
|
1124
|
-
//
|
|
1125
|
-
//
|
|
1221
|
+
// are renamed per-constructor (e.g. `value` → `value_a`, `value_a` →
|
|
1222
|
+
// `value_a_a`), so falling through to plain `sh.<field>` can resolve to
|
|
1223
|
+
// a different renamed destructor and verify a false contract. Require a
|
|
1224
|
+
// known variant (`e.ofVariant`) for mixed-type union projections.
|
|
1126
1225
|
const ownerTy = (v) => v.fields.find(f => f.name === e.field)?.type;
|
|
1127
1226
|
const differ = owners.some(v => {
|
|
1128
1227
|
const a = ownerTy(v), b = ownerTy(owners[0]);
|
|
1129
1228
|
return a && b && !tyEqual(a, b);
|
|
1130
1229
|
});
|
|
1131
|
-
|
|
1132
|
-
|
|
1230
|
+
if (differ && !e.ofVariant) {
|
|
1231
|
+
throw new Error(`cannot read '${e.field}' on '${baseName}' without narrowing to a variant first (variants give '${e.field}' different types)`);
|
|
1232
|
+
}
|
|
1233
|
+
const ctor = e.ofVariant;
|
|
1133
1234
|
return { kind: "field", obj: transformExpr(e.obj), field: e.field, fromUnion: baseName, ctor, datatypeField: true };
|
|
1134
1235
|
}
|
|
1135
1236
|
}
|
|
@@ -1385,9 +1486,43 @@ function lowerExpr(e, binds) {
|
|
|
1385
1486
|
};
|
|
1386
1487
|
}
|
|
1387
1488
|
const prefix = e.callKind === "spec-pure" && _opts.backend === "lean" ? "Pure." : "";
|
|
1388
|
-
|
|
1489
|
+
const callArgs = e.args.map(a => lowerExpr(a, binds));
|
|
1490
|
+
// Zero-parameter closures are emitted as `fun () => ...` in Lean (`Unit → T`),
|
|
1491
|
+
// so calling one must supply `()`. Top-level 0-arg defs/methods do not carry
|
|
1492
|
+
// a `fn` variable type and stay bare names.
|
|
1493
|
+
if (_opts.backend === "lean" && callArgs.length === 0 && e.fn.ty.kind === "fn" && e.fn.ty.params.length === 0) {
|
|
1494
|
+
callArgs.push({ kind: "var", name: "()" });
|
|
1495
|
+
}
|
|
1496
|
+
return { kind: "app", fn: prefix + e.fn.name, args: callArgs };
|
|
1389
1497
|
}
|
|
1390
1498
|
case "record": {
|
|
1499
|
+
const lowerTypedField = (rawVal, declaredTy) => {
|
|
1500
|
+
const fieldValue = declaredTy && rawVal.ty.kind === "unknown"
|
|
1501
|
+
? { ...rawVal, ty: declaredTy }
|
|
1502
|
+
: rawVal;
|
|
1503
|
+
let value = lowerExpr(fieldValue, binds);
|
|
1504
|
+
if (declaredTy?.kind === "optional") {
|
|
1505
|
+
const isUndef = rawVal.kind === "var" && (rawVal.name === "undefined" || rawVal.name === "null");
|
|
1506
|
+
if (rawVal.ty.kind !== "optional" && !isUndef) {
|
|
1507
|
+
value = { kind: "app", fn: "Some", args: [value] };
|
|
1508
|
+
}
|
|
1509
|
+
}
|
|
1510
|
+
else if (declaredTy?.kind === "nullish") {
|
|
1511
|
+
value = wrapNullishBranch(value, rawVal);
|
|
1512
|
+
}
|
|
1513
|
+
return value;
|
|
1514
|
+
};
|
|
1515
|
+
const buildVariantCtor = (variantName, tyName, baseName, variant, resolveArg) => {
|
|
1516
|
+
// Bare-constructor shortcut only when the variant truly has no fields —
|
|
1517
|
+
// a variant with only optional fields still needs its argument list.
|
|
1518
|
+
if (variant.fields.length === 0) {
|
|
1519
|
+
return { kind: "constructor", name: variantName, type: tyName, args: [] };
|
|
1520
|
+
}
|
|
1521
|
+
// Constructor with args: match variant field order. Emit a bare `app`
|
|
1522
|
+
// (Dafny renders `variantName(args)`) tagged with `ctorOf` so Lean
|
|
1523
|
+
// qualifies it as `BaseType.variantName args` (using the base name).
|
|
1524
|
+
return { kind: "app", fn: variantName, args: variant.fields.map(resolveArg), ctorOf: baseName };
|
|
1525
|
+
};
|
|
1391
1526
|
// Discriminated union: { kind: 'NoOp' } → constructor NoOp
|
|
1392
1527
|
if (e.ty.kind === "user" && !e.spread) {
|
|
1393
1528
|
const tyName = e.ty.name;
|
|
@@ -1397,23 +1532,11 @@ function lowerExpr(e, binds) {
|
|
|
1397
1532
|
if (decl && decl.discriminant) {
|
|
1398
1533
|
const discField = e.fields.find(f => f.name === decl.discriminant);
|
|
1399
1534
|
if (discField && (discField.value.kind === "str" || discField.value.kind === "bool")) {
|
|
1400
|
-
const variantName = String(discField.value.
|
|
1535
|
+
const variantName = String(discField.value.value);
|
|
1401
1536
|
const variant = decl.variants?.find(v => v.name === variantName);
|
|
1402
1537
|
if (variant) {
|
|
1403
1538
|
const nonDiscFields = e.fields.filter(f => f.name !== decl.discriminant);
|
|
1404
|
-
|
|
1405
|
-
// fields — a variant with only optional fields still needs its
|
|
1406
|
-
// None-filled argument list (`int_(None)`, not `int_`).
|
|
1407
|
-
if (variant.fields.length === 0) {
|
|
1408
|
-
return { kind: "constructor", name: variantName, type: tyName, args: [] };
|
|
1409
|
-
}
|
|
1410
|
-
// Constructor with args: match variant field order. Emit a bare `app`
|
|
1411
|
-
// (Dafny renders `variantName(args)`, a valid unqualified constructor
|
|
1412
|
-
// call — unchanged output) tagged with `ctorOf` so the Lean emitter,
|
|
1413
|
-
// which CANNOT take a bare constructor name, qualifies it as
|
|
1414
|
-
// `BaseType.variantName args`. Use the BASE type name (no generic args):
|
|
1415
|
-
// `Result.true_` is valid in Lean; `Result<Model,Err>.true_` is not.
|
|
1416
|
-
const args = variant.fields.map(vf => {
|
|
1539
|
+
return buildVariantCtor(variantName, tyName, baseName, variant, vf => {
|
|
1417
1540
|
const ef = nonDiscFields.find(f => f.name === vf.name);
|
|
1418
1541
|
if (ef)
|
|
1419
1542
|
return lowerExpr(ef.value, binds);
|
|
@@ -1422,7 +1545,6 @@ function lowerExpr(e, binds) {
|
|
|
1422
1545
|
}
|
|
1423
1546
|
return { kind: "var", name: "None" };
|
|
1424
1547
|
});
|
|
1425
|
-
return { kind: "app", fn: variantName, args, ctorOf: baseName };
|
|
1426
1548
|
}
|
|
1427
1549
|
}
|
|
1428
1550
|
}
|
|
@@ -1431,17 +1553,117 @@ function lowerExpr(e, binds) {
|
|
|
1431
1553
|
if (e.spread) {
|
|
1432
1554
|
const spreadTy = e.spread.ty.kind === "optional" ? e.spread.ty.inner : e.spread.ty;
|
|
1433
1555
|
const structName = spreadTy.kind === "user" ? spreadTy.name : undefined;
|
|
1434
|
-
const
|
|
1556
|
+
const baseName = structName ? tyBaseName(structName) : undefined;
|
|
1557
|
+
const structDecl = baseName ? declOfKind(_typeDecls, baseName, "record") : undefined;
|
|
1435
1558
|
// Also check discriminated-union variants for field types
|
|
1436
|
-
const unionDecl =
|
|
1559
|
+
const unionDecl = baseName ? declOfKind(_typeDecls, baseName, "discriminated-union") : undefined;
|
|
1560
|
+
// Tag-overriding spread on a discriminated union (`{ ...sh, kind: "b", ... }`):
|
|
1561
|
+
// once a spread explicitly overrides the discriminant, ordinary field update
|
|
1562
|
+
// is the wrong operation (it can silently write a colliding renamed payload
|
|
1563
|
+
// destructor such as `value_a` and preserve the old constructor). Either
|
|
1564
|
+
// construct the target variant faithfully or reject with a diagnostic.
|
|
1565
|
+
if (unionDecl?.discriminant) {
|
|
1566
|
+
const discField = e.fields.find(f => f.name === unionDecl.discriminant);
|
|
1567
|
+
if (discField) {
|
|
1568
|
+
if (discField.value.kind !== "str" && discField.value.kind !== "bool") {
|
|
1569
|
+
throw new Error(`spread on '${unionDecl.name}' must set '${unionDecl.discriminant}' to a literal tag`);
|
|
1570
|
+
}
|
|
1571
|
+
const variantName = String(discField.value.value);
|
|
1572
|
+
const targetVariant = unionDecl.variants?.find(v => v.name === variantName);
|
|
1573
|
+
if (!targetVariant) {
|
|
1574
|
+
throw new Error(`unknown '${unionDecl.name}' variant '${variantName}' in spread`);
|
|
1575
|
+
}
|
|
1576
|
+
const sourceVariant = e.spreadOfVariant
|
|
1577
|
+
? unionDecl.variants?.find(v => v.name === e.spreadOfVariant)
|
|
1578
|
+
: undefined;
|
|
1579
|
+
const possibleSources = sourceVariant ? [sourceVariant] : (unionDecl.variants ?? []);
|
|
1580
|
+
const spreadExpr = lowerExpr(e.spread, binds);
|
|
1581
|
+
const overriddenByName = new Map();
|
|
1582
|
+
for (const f of e.fields) {
|
|
1583
|
+
if (f.name === unionDecl.discriminant)
|
|
1584
|
+
continue;
|
|
1585
|
+
const declaredTy = targetVariant.fields.find(vf => vf.name === f.name)?.type;
|
|
1586
|
+
overriddenByName.set(f.name, lowerTypedField(f.value, declaredTy));
|
|
1587
|
+
}
|
|
1588
|
+
return buildVariantCtor(variantName, structName, baseName, targetVariant, vf => {
|
|
1589
|
+
const explicit = overriddenByName.get(vf.name);
|
|
1590
|
+
if (explicit !== undefined)
|
|
1591
|
+
return explicit;
|
|
1592
|
+
for (const sv of possibleSources) {
|
|
1593
|
+
const sf = sv.fields.find(f => f.name === vf.name);
|
|
1594
|
+
if (!sf?.type || !vf.type || !tyEqual(sf.type, vf.type)) {
|
|
1595
|
+
throw new Error(`cannot change '${unionDecl.name}' from '${sv.name}' to '${variantName}' via spread: pass '${vf.name}' explicitly`);
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
return {
|
|
1599
|
+
kind: "field",
|
|
1600
|
+
obj: spreadExpr,
|
|
1601
|
+
field: vf.name,
|
|
1602
|
+
fromUnion: baseName,
|
|
1603
|
+
ctor: sourceVariant?.name,
|
|
1604
|
+
datatypeField: true,
|
|
1605
|
+
};
|
|
1606
|
+
});
|
|
1607
|
+
}
|
|
1608
|
+
}
|
|
1609
|
+
const pinnedVariant = unionDecl && e.ofVariant
|
|
1610
|
+
? unionDecl.variants?.find(v => v.name === e.ofVariant)
|
|
1611
|
+
: undefined;
|
|
1612
|
+
// Un-narrowed union spread where an overridden field has differing types
|
|
1613
|
+
// across variants (e.g. `a.value: number` vs `b.value: number | undefined`):
|
|
1614
|
+
// expand to a per-variant `match` so each constructor receives the right
|
|
1615
|
+
// coercion (`5` vs `Some(5)`) and destructor in both Dafny and Lean.
|
|
1616
|
+
if (unionDecl?.variants && !pinnedVariant) {
|
|
1617
|
+
const hasMixedField = e.fields.some(f => {
|
|
1618
|
+
const tys = unionDecl.variants
|
|
1619
|
+
.map(v => v.fields.find(vf => vf.name === f.name)?.type)
|
|
1620
|
+
.filter((t) => t !== undefined);
|
|
1621
|
+
return tys.length > 1 && tys.some(t => !tyEqual(t, tys[0]));
|
|
1622
|
+
});
|
|
1623
|
+
if (hasMixedField) {
|
|
1624
|
+
const spreadExpr = lowerExpr(e.spread, binds);
|
|
1625
|
+
const baseFieldExprs = new Map(e.fields.map(f => [f.name, lowerExpr(f.value, binds)]));
|
|
1626
|
+
const rawFieldByName = new Map(e.fields.map(f => [f.name, f.value]));
|
|
1627
|
+
const arms = unionDecl.variants.map(v => {
|
|
1628
|
+
const binders = [];
|
|
1629
|
+
const fieldExprs = new Map();
|
|
1630
|
+
v.fields.forEach((vf, idx) => {
|
|
1631
|
+
const rawVal = rawFieldByName.get(vf.name);
|
|
1632
|
+
if (rawVal !== undefined) {
|
|
1633
|
+
binders.push("_");
|
|
1634
|
+
let val = baseFieldExprs.get(vf.name);
|
|
1635
|
+
if (vf.type?.kind === "optional") {
|
|
1636
|
+
const isUndef = rawVal.kind === "var" && (rawVal.name === "undefined" || rawVal.name === "null");
|
|
1637
|
+
if (rawVal.ty.kind !== "optional" && !isUndef) {
|
|
1638
|
+
val = { kind: "app", fn: "Some", args: [val] };
|
|
1639
|
+
}
|
|
1640
|
+
}
|
|
1641
|
+
else if (vf.type?.kind === "nullish") {
|
|
1642
|
+
val = wrapNullishBranch(val, rawVal);
|
|
1643
|
+
}
|
|
1644
|
+
fieldExprs.set(vf.name, val);
|
|
1645
|
+
}
|
|
1646
|
+
else {
|
|
1647
|
+
const bv = freshName(`_sp${idx}`);
|
|
1648
|
+
binders.push(bv);
|
|
1649
|
+
fieldExprs.set(vf.name, { kind: "var", name: bv });
|
|
1650
|
+
}
|
|
1651
|
+
});
|
|
1652
|
+
const body = buildVariantCtor(v.name, structName, baseName, v, vf => fieldExprs.get(vf.name));
|
|
1653
|
+
return { pattern: { kind: "ctor", ctor: v.name, binders }, body };
|
|
1654
|
+
});
|
|
1655
|
+
return { kind: "match", scrutinee: spreadExpr, arms };
|
|
1656
|
+
}
|
|
1657
|
+
}
|
|
1437
1658
|
const loweredFields = e.fields.map(f => {
|
|
1438
|
-
// Propagate declared field type onto value if it has unknown type
|
|
1439
|
-
let fieldValue = f.value;
|
|
1440
1659
|
const fieldDecl = structDecl?.fields?.find(sf => sf.name === f.name);
|
|
1441
1660
|
let declaredTy;
|
|
1442
1661
|
if (fieldDecl) {
|
|
1443
1662
|
declaredTy = fieldDecl.type;
|
|
1444
1663
|
}
|
|
1664
|
+
else if (pinnedVariant) {
|
|
1665
|
+
declaredTy = pinnedVariant.fields.find(vf => vf.name === f.name)?.type;
|
|
1666
|
+
}
|
|
1445
1667
|
else if (unionDecl?.variants) {
|
|
1446
1668
|
for (const v of unionDecl.variants) {
|
|
1447
1669
|
const vf = v.fields.find(vf => vf.name === f.name);
|
|
@@ -1451,23 +1673,14 @@ function lowerExpr(e, binds) {
|
|
|
1451
1673
|
}
|
|
1452
1674
|
}
|
|
1453
1675
|
}
|
|
1454
|
-
|
|
1455
|
-
fieldValue = { ...fieldValue, ty: declaredTy };
|
|
1456
|
-
}
|
|
1457
|
-
let value = lowerExpr(fieldValue, binds);
|
|
1458
|
-
// Wrap non-optional/non-nullish values for optional/nullish fields
|
|
1459
|
-
if (declaredTy?.kind === "optional") {
|
|
1460
|
-
const isUndef = f.value.kind === "var" && (f.value.name === "undefined" || f.value.name === "null");
|
|
1461
|
-
if (f.value.ty.kind !== "optional" && !isUndef) {
|
|
1462
|
-
value = { kind: "app", fn: "Some", args: [value] };
|
|
1463
|
-
}
|
|
1464
|
-
}
|
|
1465
|
-
else if (declaredTy?.kind === "nullish") {
|
|
1466
|
-
value = wrapNullishBranch(value, f.value);
|
|
1467
|
-
}
|
|
1468
|
-
return { name: f.name, value };
|
|
1676
|
+
return { name: f.name, value: lowerTypedField(f.value, declaredTy) };
|
|
1469
1677
|
});
|
|
1470
|
-
return {
|
|
1678
|
+
return {
|
|
1679
|
+
kind: "record",
|
|
1680
|
+
spread: lowerExpr(e.spread, binds),
|
|
1681
|
+
fields: loweredFields,
|
|
1682
|
+
...(unionDecl && baseName ? { ctor: e.ofVariant, ctorOf: baseName } : {}),
|
|
1683
|
+
};
|
|
1471
1684
|
}
|
|
1472
1685
|
// Empty record with map type → empty map
|
|
1473
1686
|
if (e.fields.length === 0 && !e.spread && e.ty.kind === "map") {
|
|
@@ -1684,30 +1897,43 @@ function lowerExpr(e, binds) {
|
|
|
1684
1897
|
const pathHint = varName ?? scrutineeHint(e.scrutinee);
|
|
1685
1898
|
const wrapOpt = e.ty.kind === "optional";
|
|
1686
1899
|
const wrapNullish = e.ty.kind === "nullish";
|
|
1687
|
-
const
|
|
1900
|
+
const lowered = e.cases.map(c => lowerExpr(c.body, binds));
|
|
1901
|
+
const loweredFallthrough = e.fallthrough ? lowerExpr(e.fallthrough, binds) : null;
|
|
1902
|
+
// The arms may already read a binder minted for an enclosing narrowing
|
|
1903
|
+
// with the same hint (`u` and `m.u` both give `_u_arr`). Prime this
|
|
1904
|
+
// match's binders past those names so the arm does not capture them.
|
|
1905
|
+
const read = new Set();
|
|
1906
|
+
for (const b of [...lowered, ...(loweredFallthrough ? [loweredFallthrough] : [])])
|
|
1907
|
+
anyExpr(b, x => { if (x.kind === "var")
|
|
1908
|
+
read.add(x.name); return false; });
|
|
1909
|
+
const taken = (n) => read.has(n);
|
|
1910
|
+
const arms = e.cases.map((c, i) => {
|
|
1688
1911
|
const variant = decl?.variants?.find(v => v.name === c.variant);
|
|
1689
1912
|
const fields = variant?.fields ?? [];
|
|
1690
|
-
let body =
|
|
1913
|
+
let body = lowered[i];
|
|
1691
1914
|
if (varName && fields.length > 0) {
|
|
1692
|
-
body = replaceFieldAccess(body, varName, fields, c.variant, tyBaseName(e.typeName));
|
|
1915
|
+
body = replaceFieldAccess(body, varName, fields, c.variant, tyBaseName(e.typeName), taken);
|
|
1693
1916
|
if (isSynthArrayUnion && fields.length === 1) {
|
|
1694
|
-
body = replaceVarInExpr(body, varName, matchBinder(fields[0].name, varName));
|
|
1917
|
+
body = replaceVarInExpr(body, varName, matchBinder(fields[0].name, varName, taken));
|
|
1695
1918
|
}
|
|
1696
1919
|
}
|
|
1697
1920
|
else if (!varName && isSynthArrayUnion && fields.length === 1) {
|
|
1698
|
-
// Path scrutinee (e.g. `m.content`): replace
|
|
1921
|
+
// Path scrutinee (e.g. `m.content`): replace both projected
|
|
1922
|
+
// `m.content.arr` (inserted by checked-reads) and bare `m.content`
|
|
1699
1923
|
// with the binder var ref.
|
|
1700
|
-
const binderName = matchBinder(fields[0].name, pathHint);
|
|
1924
|
+
const binderName = matchBinder(fields[0].name, pathHint, taken);
|
|
1925
|
+
const projectedField = { kind: "field", obj: scrutinee, field: fields[0].name };
|
|
1926
|
+
body = replaceExprInExpr(body, projectedField, { kind: "var", name: binderName });
|
|
1701
1927
|
body = replaceExprInExpr(body, scrutinee, { kind: "var", name: binderName });
|
|
1702
1928
|
}
|
|
1703
1929
|
if (wrapOpt)
|
|
1704
1930
|
body = wrapOptionalBranch(body, c.body);
|
|
1705
1931
|
else if (wrapNullish)
|
|
1706
1932
|
body = wrapNullishBranch(body, c.body);
|
|
1707
|
-
return { pattern: buildMatchPattern(c.variant, fields, pathHint), body };
|
|
1933
|
+
return { pattern: buildMatchPattern(c.variant, fields, pathHint, taken), body };
|
|
1708
1934
|
});
|
|
1709
|
-
if (e.fallthrough) {
|
|
1710
|
-
let body =
|
|
1935
|
+
if (e.fallthrough && loweredFallthrough) {
|
|
1936
|
+
let body = loweredFallthrough;
|
|
1711
1937
|
if (wrapOpt)
|
|
1712
1938
|
body = wrapOptionalBranch(body, e.fallthrough);
|
|
1713
1939
|
else if (wrapNullish)
|
|
@@ -1756,14 +1982,49 @@ function ensuresToMatch(e, typeDecls) {
|
|
|
1756
1982
|
rhs = replaceFieldAccess(rhs, obj.name, fields);
|
|
1757
1983
|
return { kind: "match", scrutinee: varE(obj.name), arms: [{ pattern, body: rhs }, { pattern: pWild(), body: { kind: "bool", value: true } }] };
|
|
1758
1984
|
}
|
|
1759
|
-
|
|
1760
|
-
|
|
1985
|
+
/** Substitution into a nested `match` that is capture-avoiding. An arm whose
|
|
1986
|
+
* pattern rebinds `oldName` keeps its body. An arm that binds one of the
|
|
1987
|
+
* `introduced` names, while its body still reads `oldName`, has that binder
|
|
1988
|
+
* renamed to a fresh name first. Without the rename, the substituted
|
|
1989
|
+
* reference would resolve to the inner binder instead of the outer one. */
|
|
1990
|
+
function substIntoMatch(x, oldName, introduced, sub) {
|
|
1991
|
+
return { ...x, scrutinee: sub(x.scrutinee), arms: x.arms.map(a => {
|
|
1992
|
+
if (patternBinders(a.pattern).includes(oldName))
|
|
1993
|
+
return a;
|
|
1994
|
+
const readsOld = anyExpr(a.body, y => y.kind === "var" && y.name === oldName);
|
|
1995
|
+
if (!readsOld || a.pattern.kind !== "ctor")
|
|
1996
|
+
return { ...a, body: sub(a.body) };
|
|
1997
|
+
const binders = [...a.pattern.binders];
|
|
1998
|
+
let body = a.body;
|
|
1999
|
+
for (let i = 0; i < binders.length; i++) {
|
|
2000
|
+
const b = binders[i];
|
|
2001
|
+
if (!introduced.includes(b))
|
|
2002
|
+
continue;
|
|
2003
|
+
const fresh = freshNameWhere(b, n => isUserName(n) || introduced.includes(n) || binders.includes(n) ||
|
|
2004
|
+
anyExpr(body, y => y.kind === "var" && y.name === n));
|
|
2005
|
+
binders[i] = fresh;
|
|
2006
|
+
body = renameFreeVar(body, b, fresh);
|
|
2007
|
+
}
|
|
2008
|
+
const pattern = { ...a.pattern, binders };
|
|
2009
|
+
return { ...a, pattern, body: sub(body) };
|
|
2010
|
+
}) };
|
|
2011
|
+
}
|
|
2012
|
+
function replaceFieldAccess(e, varName, fields, ctorName, ctorOf, taken) {
|
|
2013
|
+
const introduced = fields.map(f => matchBinder(f.name, varName, taken));
|
|
2014
|
+
const fn = (x) => {
|
|
2015
|
+
if (x.kind === "lambda")
|
|
2016
|
+
return mapLambdaBody(x, varName, fn);
|
|
2017
|
+
if ((x.kind === "forall" || x.kind === "exists") && x.var === varName)
|
|
2018
|
+
return x;
|
|
2019
|
+
if (x.kind === "match") {
|
|
2020
|
+
return substIntoMatch(x, varName, introduced, y => replaceFieldAccess(y, varName, fields, ctorName, ctorOf, taken));
|
|
2021
|
+
}
|
|
1761
2022
|
const objMatches = x.kind === "field" && ((x.obj.kind === "var" && x.obj.name === varName) ||
|
|
1762
2023
|
(x.obj.kind === "checkedUnwrap" && x.obj.expr.kind === "var" && x.obj.expr.name === varName));
|
|
1763
2024
|
if (objMatches && x.kind === "field") {
|
|
1764
2025
|
const f = fields.find(f => f.name === x.field);
|
|
1765
2026
|
if (f)
|
|
1766
|
-
return { kind: "var", name: matchBinder(f.name, varName) };
|
|
2027
|
+
return { kind: "var", name: matchBinder(f.name, varName, taken) };
|
|
1767
2028
|
}
|
|
1768
2029
|
// Datatype update of the scrutinee (`{ ...vn, f: v }`): the arm knows the
|
|
1769
2030
|
// variant, so stamp it — emitters need it for per-constructor destructor
|
|
@@ -1771,27 +2032,35 @@ function replaceFieldAccess(e, varName, fields, ctorName, ctorOf) {
|
|
|
1771
2032
|
if (ctorName && x.kind === "record" && !x.ctor && x.spread &&
|
|
1772
2033
|
x.spread.kind === "var" && x.spread.name === varName) {
|
|
1773
2034
|
return { ...x, ctor: ctorName, ctorOf,
|
|
1774
|
-
fields: x.fields.map(f => ({ ...f, value: replaceFieldAccess(f.value, varName, fields, ctorName, ctorOf) })) };
|
|
2035
|
+
fields: x.fields.map(f => ({ ...f, value: replaceFieldAccess(f.value, varName, fields, ctorName, ctorOf, taken) })) };
|
|
1775
2036
|
}
|
|
1776
2037
|
// If this let shadows the matched variable, stop replacing in the body
|
|
1777
2038
|
if (x.kind === "let" && x.name === varName)
|
|
1778
|
-
return { ...x, value: replaceFieldAccess(x.value, varName, fields, ctorName, ctorOf) };
|
|
2039
|
+
return { ...x, value: replaceFieldAccess(x.value, varName, fields, ctorName, ctorOf, taken) };
|
|
1779
2040
|
return null;
|
|
1780
|
-
}
|
|
2041
|
+
};
|
|
2042
|
+
return mapExpr(e, fn);
|
|
1781
2043
|
}
|
|
1782
2044
|
/** Replace bare `var(oldName)` references → `var(newName)` in lowered IR.
|
|
1783
2045
|
* Used inside synth array-union match arms: the user code refers to the
|
|
1784
2046
|
* scrutinee by its bare name (`content`), but in the arm body that name
|
|
1785
2047
|
* must refer to the variant's sole payload binder (`i_content_arr`). */
|
|
1786
2048
|
function replaceVarInExpr(e, oldName, newName) {
|
|
1787
|
-
|
|
2049
|
+
const fn = (x) => {
|
|
1788
2050
|
if (x.kind === "var" && x.name === oldName)
|
|
1789
2051
|
return { kind: "var", name: newName };
|
|
2052
|
+
if (x.kind === "match")
|
|
2053
|
+
return substIntoMatch(x, oldName, [newName], y => replaceVarInExpr(y, oldName, newName));
|
|
2054
|
+
if (x.kind === "lambda")
|
|
2055
|
+
return mapLambdaBody(x, oldName, fn);
|
|
1790
2056
|
// If a binding shadows the name, stop substituting inside its body.
|
|
1791
2057
|
if (x.kind === "let" && x.name === oldName)
|
|
1792
2058
|
return { ...x, value: replaceVarInExpr(x.value, oldName, newName) };
|
|
2059
|
+
if ((x.kind === "forall" || x.kind === "exists") && x.var === oldName)
|
|
2060
|
+
return x;
|
|
1793
2061
|
return null;
|
|
1794
|
-
}
|
|
2062
|
+
};
|
|
2063
|
+
return mapExpr(e, fn);
|
|
1795
2064
|
}
|
|
1796
2065
|
/** Structural equality on Expr access-paths (var / field chain). Enough to
|
|
1797
2066
|
* match the scrutinee `m.content` against later occurrences in a match arm. */
|
|
@@ -1804,16 +2073,36 @@ function exprPathEqual(a, b) {
|
|
|
1804
2073
|
return a.field === b.field && exprPathEqual(a.obj, b.obj);
|
|
1805
2074
|
return false;
|
|
1806
2075
|
}
|
|
2076
|
+
/** Extract the root variable name of an access-path Expr (e.g. `m.u` → `m`). */
|
|
2077
|
+
function exprPathRoot(e) {
|
|
2078
|
+
let cur = e;
|
|
2079
|
+
while (cur.kind === "field")
|
|
2080
|
+
cur = cur.obj;
|
|
2081
|
+
return cur.kind === "var" ? cur.name : null;
|
|
2082
|
+
}
|
|
1807
2083
|
/** Substitute every occurrence of `target` (an access-path Expr) with `repl`
|
|
1808
2084
|
* inside `e`. Mirror of `replaceVarInExpr` but keyed on a sub-path rather
|
|
1809
2085
|
* than a bare name — needed when the narrowing scrutinee is `m.content`
|
|
1810
2086
|
* (field access) rather than a bare `content` (var). */
|
|
1811
2087
|
function replaceExprInExpr(e, target, repl) {
|
|
1812
|
-
|
|
2088
|
+
const root = exprPathRoot(target);
|
|
2089
|
+
const introduced = repl.kind === "var" ? [repl.name] : [];
|
|
2090
|
+
const fn = (x) => {
|
|
1813
2091
|
if (exprPathEqual(x, target))
|
|
1814
2092
|
return repl;
|
|
2093
|
+
if (root) {
|
|
2094
|
+
if (x.kind === "match")
|
|
2095
|
+
return substIntoMatch(x, root, introduced, y => replaceExprInExpr(y, target, repl));
|
|
2096
|
+
if (x.kind === "lambda")
|
|
2097
|
+
return mapLambdaBody(x, root, fn);
|
|
2098
|
+
if (x.kind === "let" && x.name === root)
|
|
2099
|
+
return { ...x, value: replaceExprInExpr(x.value, target, repl) };
|
|
2100
|
+
if ((x.kind === "forall" || x.kind === "exists") && x.var === root)
|
|
2101
|
+
return x;
|
|
2102
|
+
}
|
|
1815
2103
|
return null;
|
|
1816
|
-
}
|
|
2104
|
+
};
|
|
2105
|
+
return mapExpr(e, fn);
|
|
1817
2106
|
}
|
|
1818
2107
|
/** Extract a short reader-friendly hint for a TExpr access-path: the last
|
|
1819
2108
|
* field name in a field chain, or the var name. Used to derive a stable
|
|
@@ -1836,22 +2125,50 @@ function negateExpr(e) {
|
|
|
1836
2125
|
return e.expr;
|
|
1837
2126
|
return { kind: "unop", op: "¬", expr: e };
|
|
1838
2127
|
}
|
|
1839
|
-
/**
|
|
1840
|
-
*
|
|
1841
|
-
* - `
|
|
1842
|
-
*
|
|
1843
|
-
|
|
2128
|
+
/** Lower an array `.pop()` or `.shift()` call on any writable Place receiver
|
|
2129
|
+
* into `{ method, result, writeStmts }`:
|
|
2130
|
+
* - `result` reads the removed element from the original receiver,
|
|
2131
|
+
* - `writeStmts` writes the shortened array
|
|
2132
|
+
* back through the original receiver Place + enclosing `someMatch` frames.
|
|
2133
|
+
* A consumed nonoptional result reads an element directly, already requiring
|
|
2134
|
+
* nonemptiness. Optional or discarded results still need an empty-array guard.
|
|
2135
|
+
* Value callers evaluate `result` before `writeStmts` and only assign to the
|
|
2136
|
+
* destination afterward so `t = t.children.shift()!` mutates the original `t`. */
|
|
2137
|
+
function lowerArrayPopOrShift(e, usage) {
|
|
2138
|
+
if (e.kind !== "call" || e.fn.kind !== "field" || e.fn.obj.ty.kind !== "array")
|
|
2139
|
+
return null;
|
|
2140
|
+
const method = e.fn.field;
|
|
2141
|
+
if (method !== "pop" && method !== "shift")
|
|
2142
|
+
return null;
|
|
2143
|
+
const obj = e.fn.obj;
|
|
2144
|
+
const arrExpr = lowerExpr(obj, null);
|
|
1844
2145
|
const arrLen = { kind: "field", obj: arrExpr, field: "size" };
|
|
1845
|
-
const lastIdx = { kind: "binop", op: "-", left: arrLen, right: { kind: "num", value: 1 } };
|
|
1846
|
-
const lastElem = { kind: "index", arr: arrExpr, idx: lastIdx };
|
|
1847
2146
|
const isNonEmpty = { kind: "binop", op: ">", left: arrLen, right: { kind: "num", value: 0 } };
|
|
1848
|
-
const
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
const
|
|
1852
|
-
|
|
1853
|
-
const
|
|
1854
|
-
|
|
2147
|
+
const index = method === "pop"
|
|
2148
|
+
? { kind: "binop", op: "-", left: arrLen, right: { kind: "num", value: 1 } }
|
|
2149
|
+
: { kind: "num", value: 0 };
|
|
2150
|
+
const elemValue = { kind: "index", arr: arrExpr, idx: index };
|
|
2151
|
+
const isOptResult = e.ty.kind === "optional" || e.ty.kind === "nullish";
|
|
2152
|
+
const result = isOptResult
|
|
2153
|
+
? { kind: "if", cond: isNonEmpty, then: { kind: "app", fn: "Some", args: [elemValue] }, else: { kind: "var", name: "undefined" } }
|
|
2154
|
+
: elemValue;
|
|
2155
|
+
const truncated = { kind: "methodCall", obj: arrExpr, objTy: obj.ty, method: "slice",
|
|
2156
|
+
args: method === "pop" ? [{ kind: "num", value: 0 }, index] : [{ kind: "num", value: 1 }], monadic: false };
|
|
2157
|
+
const needsEmptyGuard = usage === "discard" || isOptResult;
|
|
2158
|
+
const nextArr = needsEmptyGuard
|
|
2159
|
+
? { kind: "if", cond: isNonEmpty, then: truncated, else: arrExpr }
|
|
2160
|
+
: truncated;
|
|
2161
|
+
const write = buildPlaceWrite(obj, nextArr);
|
|
2162
|
+
if (!write)
|
|
2163
|
+
return null;
|
|
2164
|
+
return {
|
|
2165
|
+
method,
|
|
2166
|
+
result,
|
|
2167
|
+
writeStmts: [
|
|
2168
|
+
{ kind: "assign", target: write.target, value: write.value },
|
|
2169
|
+
...emitWriteBacksForTarget(write.target, _writeBackFrames),
|
|
2170
|
+
],
|
|
2171
|
+
};
|
|
1855
2172
|
}
|
|
1856
2173
|
/**
|
|
1857
2174
|
* Velvet (Lean backend) rejects `return` inside a loop. For a function shaped as
|
|
@@ -2222,25 +2539,44 @@ function transformSpecExpr(e) {
|
|
|
2222
2539
|
let _writeBackFrames = [];
|
|
2223
2540
|
// Declared types of in-scope variables and narrowing binders (for optional-field wrap checks).
|
|
2224
2541
|
let _varTypes = new Map();
|
|
2225
|
-
/** Look up the declared field type reached by walking
|
|
2226
|
-
|
|
2542
|
+
/** Look up the declared field type and union-owner tags reached by walking
|
|
2543
|
+
* `fields` from `rootTy`. */
|
|
2544
|
+
function lookupFieldPathInfo(rootTy, fields, typeDecls, ownerVariants) {
|
|
2227
2545
|
let cur = rootTy;
|
|
2228
|
-
|
|
2546
|
+
const unionsByDepth = [];
|
|
2547
|
+
for (let i = 0; i < fields.length; i++) {
|
|
2548
|
+
const field = fields[i];
|
|
2229
2549
|
if (!cur)
|
|
2230
|
-
return null;
|
|
2550
|
+
return { fieldTy: null, unionsByDepth };
|
|
2231
2551
|
if (cur.kind === "optional" || cur.kind === "nullish")
|
|
2232
2552
|
cur = cur.inner;
|
|
2233
2553
|
if (cur.kind !== "user")
|
|
2234
|
-
return null;
|
|
2554
|
+
return { fieldTy: null, unionsByDepth };
|
|
2235
2555
|
const decl = declOfTy(typeDecls, cur);
|
|
2236
|
-
if (!decl
|
|
2237
|
-
return null;
|
|
2238
|
-
|
|
2239
|
-
|
|
2240
|
-
|
|
2241
|
-
|
|
2556
|
+
if (!decl)
|
|
2557
|
+
return { fieldTy: null, unionsByDepth };
|
|
2558
|
+
if (decl.kind === "record" && decl.fields) {
|
|
2559
|
+
unionsByDepth.push(undefined);
|
|
2560
|
+
const f = decl.fields.find(fi => fi.name === field);
|
|
2561
|
+
if (!f)
|
|
2562
|
+
return { fieldTy: null, unionsByDepth };
|
|
2563
|
+
cur = f.type ?? parseTsType(f.tsType);
|
|
2564
|
+
}
|
|
2565
|
+
else if (decl.kind === "discriminated-union" && decl.variants) {
|
|
2566
|
+
const ov = ownerVariants?.[i];
|
|
2567
|
+
unionsByDepth.push({ ctor: ov, ctorOf: decl.name });
|
|
2568
|
+
const variant = (ov ? decl.variants.find(v => v.name === ov) : undefined)
|
|
2569
|
+
?? decl.variants.find(v => v.fields.some(fi => fi.name === field));
|
|
2570
|
+
const f = variant?.fields.find(fi => fi.name === field);
|
|
2571
|
+
if (!f)
|
|
2572
|
+
return { fieldTy: null, unionsByDepth };
|
|
2573
|
+
cur = f.type ?? parseTsType(f.tsType);
|
|
2574
|
+
}
|
|
2575
|
+
else {
|
|
2576
|
+
return { fieldTy: null, unionsByDepth };
|
|
2577
|
+
}
|
|
2242
2578
|
}
|
|
2243
|
-
return cur ?? null;
|
|
2579
|
+
return { fieldTy: cur ?? null, unionsByDepth };
|
|
2244
2580
|
}
|
|
2245
2581
|
/** True if `e` contains any subexpression that can carry a backend precondition
|
|
2246
2582
|
* (calls, indexing, checked unwraps, division/modulo). Used to ensure optional
|
|
@@ -2298,41 +2634,15 @@ function transformStmt(s, typeDecls) {
|
|
|
2298
2634
|
if (s.init.kind === "havoc") {
|
|
2299
2635
|
return [{ kind: "let", name: s.name, type: s.ty, mutable: s.mutable, value: { kind: "havoc", type: s.init.ty } }];
|
|
2300
2636
|
}
|
|
2301
|
-
//
|
|
2637
|
+
// let x = recv.shift() / recv.pop(): bind removed element from original receiver,
|
|
2638
|
+
// then write shortened array back through the receiver Place.
|
|
2302
2639
|
const init = s.init.kind === "call" ? s.init : undefined;
|
|
2303
|
-
|
|
2304
|
-
|
|
2305
|
-
|
|
2306
|
-
|
|
2307
|
-
|
|
2308
|
-
|
|
2309
|
-
? { kind: "checkedUnwrap", expr: { kind: "var", name: arrName } }
|
|
2310
|
-
: { kind: "var", name: arrName };
|
|
2311
|
-
const letHead = { kind: "let", name: s.name, type: s.ty, mutable: s.mutable,
|
|
2312
|
-
value: { kind: "index", arr: arrExpr, idx: { kind: "num", value: 0 } } };
|
|
2313
|
-
const sliced = { kind: "methodCall", obj: arrExpr, objTy: init.fn.obj.ty, method: "slice", args: [{ kind: "num", value: 1 }], monadic: false };
|
|
2314
|
-
const tailVal = obj.kind === "checkedUnwrap" ? wrapCheckedUnwrapValue(sliced, obj.expr.ty) : sliced;
|
|
2315
|
-
const sliceTail = { kind: "assign", target: arrName, value: tailVal };
|
|
2316
|
-
return [letHead, sliceTail, ...emitWriteBacksForTarget(arrName, _writeBackFrames)];
|
|
2317
|
-
}
|
|
2318
|
-
}
|
|
2319
|
-
// let x = arr.pop() → let x: T? = (Option-expr); arr := (truncated-or-self)
|
|
2320
|
-
if (init && init.fn.kind === "field" && init.fn.field === "pop" && init.fn.obj.ty.kind === "array") {
|
|
2321
|
-
const obj = init.fn.obj;
|
|
2322
|
-
const arrName = obj.kind === "var" ? obj.name
|
|
2323
|
-
: obj.kind === "checkedUnwrap" && obj.expr.kind === "var" ? obj.expr.name : undefined;
|
|
2324
|
-
if (arrName) {
|
|
2325
|
-
const arrExpr = obj.kind === "checkedUnwrap"
|
|
2326
|
-
? { kind: "checkedUnwrap", expr: { kind: "var", name: arrName } }
|
|
2327
|
-
: { kind: "var", name: arrName };
|
|
2328
|
-
const { optValue, guardedTrunc } = buildPopLoweringExpr(arrExpr, init.fn.obj.ty);
|
|
2329
|
-
const truncVal = obj.kind === "checkedUnwrap" ? wrapCheckedUnwrapValue(guardedTrunc, obj.expr.ty) : guardedTrunc;
|
|
2330
|
-
return [
|
|
2331
|
-
{ kind: "let", name: s.name, type: s.ty, mutable: s.mutable, value: optValue },
|
|
2332
|
-
{ kind: "assign", target: arrName, value: truncVal },
|
|
2333
|
-
...emitWriteBacksForTarget(arrName, _writeBackFrames),
|
|
2334
|
-
];
|
|
2335
|
-
}
|
|
2640
|
+
const popOrShiftLet = lowerArrayPopOrShift(s.init, "value");
|
|
2641
|
+
if (popOrShiftLet) {
|
|
2642
|
+
return [
|
|
2643
|
+
{ kind: "let", name: s.name, type: s.ty, mutable: s.mutable, value: popOrShiftLet.result },
|
|
2644
|
+
...popOrShiftLet.writeStmts,
|
|
2645
|
+
];
|
|
2336
2646
|
}
|
|
2337
2647
|
// new Map(arr.map(n => [n.field, n])) → let m = map[]; for (n of arr) m[n.field] := n
|
|
2338
2648
|
if (init && init.fn.kind === "var" && init.fn.name === "__mapFromArray" &&
|
|
@@ -2385,24 +2695,19 @@ function transformStmt(s, typeDecls) {
|
|
|
2385
2695
|
return [...binds, { kind: "let", name: s.name, type: s.ty, mutable: s.mutable, value: expr }];
|
|
2386
2696
|
}
|
|
2387
2697
|
case "assign": {
|
|
2388
|
-
//
|
|
2389
|
-
|
|
2390
|
-
|
|
2391
|
-
|
|
2392
|
-
|
|
2393
|
-
|
|
2394
|
-
|
|
2395
|
-
|
|
2396
|
-
|
|
2397
|
-
|
|
2398
|
-
|
|
2399
|
-
|
|
2400
|
-
|
|
2401
|
-
{ kind: "assign", target: s.target, value: optValue },
|
|
2402
|
-
{ kind: "assign", target: arrName, value: truncVal },
|
|
2403
|
-
...emitWriteBacksForTarget(arrName, _writeBackFrames),
|
|
2404
|
-
];
|
|
2405
|
-
}
|
|
2698
|
+
// target = recv.shift() / recv.pop(): save the removed element first,
|
|
2699
|
+
// write the shortened array back through the original receiver, and only
|
|
2700
|
+
// then assign the saved result to `s.target` (so `t = t.children.shift()!`
|
|
2701
|
+
// mutates the original `t`, not the shifted child).
|
|
2702
|
+
const popOrShiftAssign = lowerArrayPopOrShift(s.value, "value");
|
|
2703
|
+
if (popOrShiftAssign) {
|
|
2704
|
+
const tmp = freshName(`_${popOrShiftAssign.method}${_liftCounter++}`);
|
|
2705
|
+
const assignTmp = { ...s, value: { kind: "var", name: tmp, ty: s.value.ty } };
|
|
2706
|
+
return [
|
|
2707
|
+
{ kind: "let", name: tmp, type: s.value.ty, mutable: false, value: popOrShiftAssign.result },
|
|
2708
|
+
...popOrShiftAssign.writeStmts,
|
|
2709
|
+
...transformStmt(assignTmp, typeDecls),
|
|
2710
|
+
];
|
|
2406
2711
|
}
|
|
2407
2712
|
// Non-`this.` dotted field assignment on a record, union variant, or narrowed
|
|
2408
2713
|
// optional/nullish record (e.g. `b.count = 5`, `u.v = 99`, `u.items[0] = 10`, `u.box.count = 42`):
|
|
@@ -2432,7 +2737,7 @@ function transformStmt(s, typeDecls) {
|
|
|
2432
2737
|
if (frame.fields.length > 0) {
|
|
2433
2738
|
return [
|
|
2434
2739
|
...binds,
|
|
2435
|
-
{ kind: "assign", target: frame.rootVar, value: buildNestedFieldExpr(frame.rootVar, frame.fields, optExpr) },
|
|
2740
|
+
{ kind: "assign", target: frame.rootVar, value: buildNestedFieldExpr({ kind: "var", name: frame.rootVar }, frame.fields, optExpr) },
|
|
2436
2741
|
...emitWriteBacksForTarget(frame.rootVar, _writeBackFrames),
|
|
2437
2742
|
];
|
|
2438
2743
|
}
|
|
@@ -2442,48 +2747,24 @@ function transformStmt(s, typeDecls) {
|
|
|
2442
2747
|
...emitWriteBacksForTarget(frame.rootVar, _writeBackFrames),
|
|
2443
2748
|
];
|
|
2444
2749
|
}
|
|
2445
|
-
if (resolved.leafVariantBinder) {
|
|
2446
|
-
const binderTy = _varTypes.get(resolved.leafVariantBinder);
|
|
2447
|
-
const rhsExpr = binderTy?.kind === "nullish"
|
|
2448
|
-
? wrapNullishBranch(expr, s.value)
|
|
2449
|
-
: binderTy?.kind === "optional"
|
|
2450
|
-
? wrapOptionalBranch(expr, s.value)
|
|
2451
|
-
: expr;
|
|
2452
|
-
return [
|
|
2453
|
-
...binds,
|
|
2454
|
-
{ kind: "assign", target: resolved.leafVariantBinder, value: rhsExpr },
|
|
2455
|
-
...emitWriteBacksForTarget(resolved.leafVariantBinder, _writeBackFrames),
|
|
2456
|
-
];
|
|
2457
|
-
}
|
|
2458
2750
|
if (resolved.remainingFields.length > 0) {
|
|
2459
2751
|
const rootTy = _varTypes.get(resolved.currentRoot);
|
|
2460
|
-
const
|
|
2752
|
+
const skippedDepth = fields.length - resolved.remainingFields.length;
|
|
2753
|
+
const remOwnerVariants = s.ownerVariants?.slice(skippedDepth);
|
|
2754
|
+
const { fieldTy, unionsByDepth } = lookupFieldPathInfo(rootTy, resolved.remainingFields, typeDecls, remOwnerVariants);
|
|
2461
2755
|
const rhsExpr = fieldTy?.kind === "nullish"
|
|
2462
2756
|
? wrapNullishBranch(expr, s.value)
|
|
2463
2757
|
: fieldTy?.kind === "optional"
|
|
2464
2758
|
? wrapOptionalBranch(expr, s.value)
|
|
2465
2759
|
: expr;
|
|
2466
|
-
|
|
2467
|
-
|
|
2468
|
-
|
|
2469
|
-
|
|
2470
|
-
|
|
2471
|
-
if (fs.length === 1)
|
|
2472
|
-
return { kind: "record", spread: base, fields: [{ name: fs[0], value: val }] };
|
|
2473
|
-
const nextBase = { kind: "field", obj: base, field: fs[0] };
|
|
2474
|
-
return { kind: "record", spread: base, fields: [{ name: fs[0], value: buildNestedFromExpr(nextBase, fs.slice(1), val) }] };
|
|
2475
|
-
};
|
|
2476
|
-
const updatedRecord = buildNestedFromExpr(unwrappedRoot, resolved.remainingFields, rhsExpr);
|
|
2477
|
-
const wrappedRoot = wrapCheckedUnwrapValue(updatedRecord, rootTy);
|
|
2478
|
-
return [
|
|
2479
|
-
...binds,
|
|
2480
|
-
{ kind: "assign", target: resolved.currentRoot, value: wrappedRoot },
|
|
2481
|
-
...emitWriteBacksForTarget(resolved.currentRoot, _writeBackFrames),
|
|
2482
|
-
];
|
|
2483
|
-
}
|
|
2760
|
+
const rootExpr = { kind: "var", name: resolved.currentRoot };
|
|
2761
|
+
const isOptRoot = rootTy?.kind === "nullish" || rootTy?.kind === "optional";
|
|
2762
|
+
const baseExpr = isOptRoot ? { kind: "checkedUnwrap", expr: rootExpr } : rootExpr;
|
|
2763
|
+
const hasAnyUnion = unionsByDepth.some(u => u !== undefined);
|
|
2764
|
+
const updated = buildNestedFieldExpr(baseExpr, resolved.remainingFields, rhsExpr, hasAnyUnion ? unionsByDepth : undefined);
|
|
2484
2765
|
return [
|
|
2485
2766
|
...binds,
|
|
2486
|
-
{ kind: "assign", target: resolved.currentRoot, value:
|
|
2767
|
+
{ kind: "assign", target: resolved.currentRoot, value: isOptRoot ? wrapCheckedUnwrapValue(updated, rootTy) : updated },
|
|
2487
2768
|
...emitWriteBacksForTarget(resolved.currentRoot, _writeBackFrames),
|
|
2488
2769
|
];
|
|
2489
2770
|
}
|
|
@@ -2534,6 +2815,9 @@ function transformStmt(s, typeDecls) {
|
|
|
2534
2815
|
// enclosing narrowing frames (`someMatch` unwrap or union variant arm).
|
|
2535
2816
|
// Non-Place receivers (e.g. `getArr().push(1)`) fail closed instead of
|
|
2536
2817
|
// silently discarding the updated collection.
|
|
2818
|
+
const popOrShiftExpr = lowerArrayPopOrShift(s.expr, "discard");
|
|
2819
|
+
if (popOrShiftExpr)
|
|
2820
|
+
return popOrShiftExpr.writeStmts;
|
|
2537
2821
|
if (s.expr.kind === "call" && s.expr.fn.kind === "field") {
|
|
2538
2822
|
const recv = s.expr.fn.obj;
|
|
2539
2823
|
const f = s.expr.fn.field;
|
|
@@ -2674,10 +2958,9 @@ function transformStmt(s, typeDecls) {
|
|
|
2674
2958
|
}
|
|
2675
2959
|
}
|
|
2676
2960
|
/** Build match arms from variant cases — shared by imperative and pure paths.
|
|
2677
|
-
*
|
|
2678
|
-
*
|
|
2679
|
-
|
|
2680
|
-
function buildMatchArms(cases, varName, typeName, typeDecls, transformBody) {
|
|
2961
|
+
* Pure paths bind constructor fields via `buildMatchPattern`; imperative paths
|
|
2962
|
+
* pass `wildcard: true` so arms read and update live storage directly (#405). */
|
|
2963
|
+
function buildMatchArms(cases, varName, typeName, typeDecls, transformBody, wildcard = false) {
|
|
2681
2964
|
const decl = declOf(typeDecls, typeName);
|
|
2682
2965
|
if (!decl || (decl.kind !== "string-union" && decl.kind !== "discriminated-union")) {
|
|
2683
2966
|
throw new Error(`match type ${typeName} is not a declared union`);
|
|
@@ -2691,7 +2974,9 @@ function buildMatchArms(cases, varName, typeName, typeDecls, transformBody) {
|
|
|
2691
2974
|
if (!declared)
|
|
2692
2975
|
throw new Error(`case ${JSON.stringify(c.name)} is not a variant of ${typeName}`);
|
|
2693
2976
|
const fields = variant?.fields ?? [];
|
|
2694
|
-
const pattern =
|
|
2977
|
+
const pattern = wildcard
|
|
2978
|
+
? buildWildcardMatchPattern(c.name, fields)
|
|
2979
|
+
: buildMatchPattern(c.name, fields, varName);
|
|
2695
2980
|
const body = transformBody(c.body, varName, fields, c.name);
|
|
2696
2981
|
if (body === null)
|
|
2697
2982
|
return null;
|
|
@@ -2714,109 +2999,22 @@ function buildLiteralMatchArms(cases, transformBody) {
|
|
|
2714
2999
|
}
|
|
2715
3000
|
function emitMatchStmt(scrutinee, typeName, cases, fallthrough, typeDecls) {
|
|
2716
3001
|
const decl = declOf(typeDecls, typeName);
|
|
2717
|
-
// Synth array-unions (discriminant "__isArray__") have single-field variants
|
|
2718
|
-
// ArrayBranch(arr) / NonArrayBranch(val). The matched arm refers to the
|
|
2719
|
-
// scrutinee by its bare name/path (`content`, `m.content`), not `.arr`, so
|
|
2720
|
-
// we substitute that whole reference with the variant's sole field binder.
|
|
2721
|
-
const isSynthArrayUnion = decl?.discriminant === "__isArray__";
|
|
2722
|
-
// The scrutinee is a bare var (`current`) or a field-access path
|
|
2723
|
-
// (`current.content`). `prefix` names the binder scope — the var name, or a
|
|
2724
|
-
// safe id derived from the path (`current.content` → `current_content`) —
|
|
2725
|
-
// and is used for both pattern binders and arm-body substitution so they
|
|
2726
|
-
// always agree. A var scrutinee has empty `fields`, so `prefix` is just its
|
|
2727
|
-
// name and the emitted code is unchanged from before this generalization.
|
|
2728
|
-
const path = asTAccessPath(scrutinee);
|
|
2729
|
-
const isPath = !!path && path.fields.length > 0;
|
|
2730
|
-
const prefix = path ? [path.rootVar, ...path.fields].join("_") : "?";
|
|
2731
|
-
const baseUnionName = tyBaseName(typeName);
|
|
2732
|
-
function transformArmBody(body, fields, ctorName) {
|
|
2733
|
-
let stmts;
|
|
2734
|
-
if (isPath && path) {
|
|
2735
|
-
// Path scrutinee: the matched value is referred to by the bare path, so
|
|
2736
|
-
// substitute the whole path (only the synth single-field shape arises
|
|
2737
|
-
// here — discriminant chains require a var scrutinee).
|
|
2738
|
-
stmts = isSynthArrayUnion && fields.length === 1
|
|
2739
|
-
? replacePathInTStmts(body, path, matchBinder(fields[0].name, prefix), fields[0].type ?? parseTsType(fields[0].tsType))
|
|
2740
|
-
: body;
|
|
2741
|
-
}
|
|
2742
|
-
else {
|
|
2743
|
-
stmts = replaceFieldAccessInTStmts(body, prefix, fields);
|
|
2744
|
-
if (isSynthArrayUnion && fields.length === 1) {
|
|
2745
|
-
const f = fields[0];
|
|
2746
|
-
stmts = replaceVarInTStmts(stmts, prefix, matchBinder(f.name, prefix), f.type ?? parseTsType(f.tsType));
|
|
2747
|
-
}
|
|
2748
|
-
}
|
|
2749
|
-
const pushVariant = !isPath && !!ctorName && fields.length > 0;
|
|
2750
|
-
if (pushVariant) {
|
|
2751
|
-
for (const f of fields) {
|
|
2752
|
-
_varTypes.set(matchBinder(f.name, prefix), f.type ?? parseTsType(f.tsType));
|
|
2753
|
-
}
|
|
2754
|
-
_writeBackFrames.push(makeVariantFrame(prefix, baseUnionName, ctorName, fields.map(f => ({ fieldName: f.name, binder: matchBinder(f.name, prefix) }))));
|
|
2755
|
-
}
|
|
2756
|
-
let lowered;
|
|
2757
|
-
try {
|
|
2758
|
-
lowered = transformStmts(stmts, typeDecls);
|
|
2759
|
-
}
|
|
2760
|
-
finally {
|
|
2761
|
-
if (pushVariant)
|
|
2762
|
-
_writeBackFrames.pop();
|
|
2763
|
-
}
|
|
2764
|
-
if (_opts.backend === "lean" && pushVariant) {
|
|
2765
|
-
const assigned = collectAssignedIrTargets(lowered);
|
|
2766
|
-
const mutShadows = fields
|
|
2767
|
-
.filter(f => assigned.has(matchBinder(f.name, prefix)))
|
|
2768
|
-
.map(f => {
|
|
2769
|
-
const b = matchBinder(f.name, prefix);
|
|
2770
|
-
return { kind: "let", name: b, type: f.type ?? parseTsType(f.tsType), mutable: true, value: varE(b) };
|
|
2771
|
-
});
|
|
2772
|
-
if (mutShadows.length > 0)
|
|
2773
|
-
lowered = [...mutShadows, ...lowered];
|
|
2774
|
-
}
|
|
2775
|
-
return lowered;
|
|
2776
|
-
}
|
|
2777
3002
|
const armCases = cases.map(c => ({ name: c.variant, body: c.body }));
|
|
2778
|
-
const arms = buildMatchArms(armCases,
|
|
2779
|
-
// Add the fallthrough arm whenever the listed cases don't cover every
|
|
2780
|
-
// variant — needed for exhaustiveness even when there's no `else`
|
|
2781
|
-
// (`fallthrough` empty), e.g. `if (Array.isArray(x)) {...}` with no else
|
|
2782
|
-
// becomes `match x { case ArrayBranch(..) => ... case NonArrayBranch(..) => }`.
|
|
3003
|
+
const arms = buildMatchArms(armCases, undefined, typeName, typeDecls, (body) => transformStmts(body, typeDecls), /* wildcard */ true);
|
|
2783
3004
|
const allCovered = !!decl?.variants && cases.length >= decl.variants.length;
|
|
2784
3005
|
if (!allCovered) {
|
|
2785
|
-
const remaining = remainingVariant(
|
|
3006
|
+
const remaining = remainingVariant(decl, cases.map(c => c.variant));
|
|
2786
3007
|
if (remaining) {
|
|
2787
|
-
|
|
2788
|
-
|
|
2789
|
-
|
|
2790
|
-
|
|
2791
|
-
arms.push({ pattern, body });
|
|
3008
|
+
arms.push({
|
|
3009
|
+
pattern: buildWildcardMatchPattern(remaining.name, remaining.fields),
|
|
3010
|
+
body: transformStmts(fallthrough, typeDecls),
|
|
3011
|
+
});
|
|
2792
3012
|
}
|
|
2793
3013
|
else {
|
|
2794
3014
|
arms.push({ pattern: pWild(), body: transformStmts(fallthrough, typeDecls) });
|
|
2795
3015
|
}
|
|
2796
3016
|
}
|
|
2797
|
-
return { kind: "match", scrutinee:
|
|
2798
|
-
}
|
|
2799
|
-
/** Replace bare `var(oldName)` references → `var(newName)` with the given type.
|
|
2800
|
-
* Used by emitMatchStmt for synth array-unions where the variant has a single
|
|
2801
|
-
* payload field and the user code refers to the scrutinee by its bare name. */
|
|
2802
|
-
function replaceVarInTStmts(stmts, oldName, newName, newTy) {
|
|
2803
|
-
return stmts.map(s => mapTStmt(s, e => {
|
|
2804
|
-
if (e.kind === "var" && e.name === oldName) {
|
|
2805
|
-
return { kind: "var", name: newName, ty: newTy };
|
|
2806
|
-
}
|
|
2807
|
-
return null;
|
|
2808
|
-
}));
|
|
2809
|
-
}
|
|
2810
|
-
/** If the chain has matched all variants but one, return that remaining variant. */
|
|
2811
|
-
function remainingVariant(typeName, cases, typeDecls) {
|
|
2812
|
-
const decl = declOf(typeDecls, typeName);
|
|
2813
|
-
if (!decl?.variants)
|
|
2814
|
-
return null;
|
|
2815
|
-
const matched = new Set(cases.map(c => c.variant));
|
|
2816
|
-
const remaining = decl.variants.filter(v => !matched.has(v.name));
|
|
2817
|
-
if (remaining.length !== 1)
|
|
2818
|
-
return null;
|
|
2819
|
-
return remaining[0];
|
|
3017
|
+
return { kind: "match", scrutinee: transformExpr(scrutinee), arms };
|
|
2820
3018
|
}
|
|
2821
3019
|
/** `switch(obj.field)` is stripped at extraction to scrutinee `obj` + discriminant
|
|
2822
3020
|
* `field`, assuming `obj` is a discriminated union with `field` as its
|
|
@@ -2846,22 +3044,19 @@ function switchCtorDecl(typeDecls, ty) {
|
|
|
2846
3044
|
const decl = declOfTy(typeDecls, ty);
|
|
2847
3045
|
return decl?.kind === "string-union" || decl?.kind === "discriminated-union" ? decl : undefined;
|
|
2848
3046
|
}
|
|
2849
|
-
/**
|
|
2850
|
-
*
|
|
2851
|
-
|
|
2852
|
-
|
|
2853
|
-
|
|
2854
|
-
const
|
|
2855
|
-
|
|
2856
|
-
|
|
2857
|
-
|
|
2858
|
-
|
|
2859
|
-
}
|
|
2860
|
-
return null;
|
|
2861
|
-
};
|
|
2862
|
-
return body.map(st => mapStmt(st, stamp));
|
|
3047
|
+
/** A default covering one union variant needs the same variant pattern as an
|
|
3048
|
+
* explicit case, in both pure and imperative lowering. */
|
|
3049
|
+
function withExplicitVariantDefault(s, typeDecls) {
|
|
3050
|
+
if (s.defaultBody.length === 0)
|
|
3051
|
+
return s;
|
|
3052
|
+
const decl = unionDeclOfTy(typeDecls, s.expr.ty);
|
|
3053
|
+
if (decl?.discriminant !== s.discriminant)
|
|
3054
|
+
return s;
|
|
3055
|
+
const remaining = remainingVariant(decl, s.cases.map(c => c.label));
|
|
3056
|
+
return remaining ? { ...s, cases: [...s.cases, { label: remaining.name, body: s.defaultBody }], defaultBody: [] } : s;
|
|
2863
3057
|
}
|
|
2864
3058
|
function emitSwitchStmt(s, typeDecls) {
|
|
3059
|
+
s = withExplicitVariantDefault(s, typeDecls);
|
|
2865
3060
|
const cases = s.cases.map(c => ({ name: c.label, body: c.body }));
|
|
2866
3061
|
const ef = enumFieldSwitch(s, typeDecls);
|
|
2867
3062
|
const matchTy = ef ? ef.fieldTy : s.expr.ty;
|
|
@@ -2871,133 +3066,14 @@ function emitSwitchStmt(s, typeDecls) {
|
|
|
2871
3066
|
const typeName = !matchTy ? "unknown" : matchTy.kind === "user" ? matchTy.name : matchTy.kind;
|
|
2872
3067
|
throw new Error(`switch scrutinee must be string-typed or a declared union, got ${typeName}`);
|
|
2873
3068
|
}
|
|
2874
|
-
const baseName = s.expr.ty.kind === "user" ? tyBaseName(s.expr.ty.name) : undefined;
|
|
2875
|
-
const switchVarName = s.expr.kind === "var" ? s.expr.name
|
|
2876
|
-
: s.expr.kind === "checkedUnwrap" && s.expr.expr.kind === "var" ? s.expr.expr.name : "?";
|
|
2877
3069
|
const arms = literalCases
|
|
2878
3070
|
? buildLiteralMatchArms(cases, (body) => transformStmts(body, typeDecls))
|
|
2879
|
-
:
|
|
2880
|
-
? buildMatchArms(cases, undefined, ctorDecl.name, typeDecls, (body) => transformStmts(body, typeDecls))
|
|
2881
|
-
: buildMatchArms(cases, switchVarName, ctorDecl.name, typeDecls, (body, vn, fields, ctorName) => {
|
|
2882
|
-
const pushVariant = !!ctorName && !!vn && vn !== "?" && !!baseName && fields.length > 0 && s.expr.kind !== "checkedUnwrap";
|
|
2883
|
-
const variantMeta = ctorName ? ctorDecl?.variants?.find(v => v.name === ctorName) : undefined;
|
|
2884
|
-
if (pushVariant) {
|
|
2885
|
-
for (const f of fields) {
|
|
2886
|
-
const vf = variantMeta?.fields.find(vf => vf.name === f.name);
|
|
2887
|
-
_varTypes.set(matchBinder(f.name, vn), vf?.type ?? parseTsType(f.tsType));
|
|
2888
|
-
}
|
|
2889
|
-
_writeBackFrames.push(makeVariantFrame(vn, baseName, ctorName, fields.map(f => ({ fieldName: f.name, binder: matchBinder(f.name, vn) }))));
|
|
2890
|
-
}
|
|
2891
|
-
let out;
|
|
2892
|
-
try {
|
|
2893
|
-
out = transformStmts(replaceFieldAccessInTStmts(body, vn, fields), typeDecls);
|
|
2894
|
-
}
|
|
2895
|
-
finally {
|
|
2896
|
-
if (pushVariant)
|
|
2897
|
-
_writeBackFrames.pop();
|
|
2898
|
-
}
|
|
2899
|
-
if (ctorName && vn && baseName)
|
|
2900
|
-
out = stampScrutineeUpdates(out, vn, ctorName, baseName);
|
|
2901
|
-
if (_opts.backend === "lean" && pushVariant) {
|
|
2902
|
-
const assigned = collectAssignedIrTargets(out);
|
|
2903
|
-
const mutShadows = fields
|
|
2904
|
-
.filter(f => assigned.has(matchBinder(f.name, vn)))
|
|
2905
|
-
.map(f => {
|
|
2906
|
-
const b = matchBinder(f.name, vn);
|
|
2907
|
-
return { kind: "let", name: b, type: parseTsType(f.tsType), mutable: true, value: varE(b) };
|
|
2908
|
-
});
|
|
2909
|
-
if (mutShadows.length > 0)
|
|
2910
|
-
out = [...mutShadows, ...out];
|
|
2911
|
-
}
|
|
2912
|
-
return out;
|
|
2913
|
-
});
|
|
3071
|
+
: buildMatchArms(cases, undefined, ctorDecl.name, typeDecls, (body) => transformStmts(body, typeDecls), /* wildcard */ true);
|
|
2914
3072
|
if (s.defaultBody.length > 0)
|
|
2915
3073
|
arms.push({ pattern: pWild(), body: transformStmts(s.defaultBody, typeDecls) });
|
|
2916
|
-
const scrutinee = ef ? ef.scrutinee
|
|
2917
|
-
: s.expr.kind === "checkedUnwrap" ? transformExpr(s.expr)
|
|
2918
|
-
: varE(switchVarName);
|
|
3074
|
+
const scrutinee = ef ? ef.scrutinee : transformExpr(s.expr);
|
|
2919
3075
|
return { kind: "match", scrutinee, arms };
|
|
2920
3076
|
}
|
|
2921
|
-
/** Replace obj.field → replacement var in typed IR.
|
|
2922
|
-
* Uses the TExpr's resolved type when available, falling back to `fallbackTy`. */
|
|
2923
|
-
function replaceFieldsInTStmts(stmts, objName, replacements) {
|
|
2924
|
-
if (replacements.length === 0)
|
|
2925
|
-
return stmts;
|
|
2926
|
-
return stmts.map(s => mapTStmt(s, e => {
|
|
2927
|
-
const objMatches = e.kind === "field" && ((e.obj.kind === "var" && e.obj.name === objName) ||
|
|
2928
|
-
(e.obj.kind === "checkedUnwrap" && e.obj.expr.kind === "var" && e.obj.expr.name === objName));
|
|
2929
|
-
if (objMatches && e.kind === "field") {
|
|
2930
|
-
const r = replacements.find(r => r.fieldName === e.field);
|
|
2931
|
-
if (r) {
|
|
2932
|
-
const ty = e.ty.kind !== "unknown" ? e.ty : r.fallbackTy;
|
|
2933
|
-
return { kind: "var", name: r.newName, ty };
|
|
2934
|
-
}
|
|
2935
|
-
}
|
|
2936
|
-
return null;
|
|
2937
|
-
}));
|
|
2938
|
-
}
|
|
2939
|
-
/** Replace all variant fields of obj → match binder vars in typed IR.
|
|
2940
|
-
* Before replacing field reads, realize TypeScript's structural argument
|
|
2941
|
-
* conversion for calls such as `helper(outcome)` inside a narrowed union arm.
|
|
2942
|
-
* The source value is still the enclosing union in typed IR, while Dafny and
|
|
2943
|
-
* Lean expect the helper's nominal record. Rebuild that record solely from
|
|
2944
|
-
* the fields bound by this arm's match pattern. */
|
|
2945
|
-
function replaceFieldAccessInTStmts(stmts, varName, fields) {
|
|
2946
|
-
const projected = projectStructuralCallArgsInTStmts(stmts, varName, fields);
|
|
2947
|
-
return replaceFieldsInTStmts(projected, varName, fields.map(f => ({
|
|
2948
|
-
fieldName: f.name,
|
|
2949
|
-
newName: matchBinder(f.name, varName),
|
|
2950
|
-
fallbackTy: f.type ?? parseTsType(f.tsType),
|
|
2951
|
-
})));
|
|
2952
|
-
}
|
|
2953
|
-
/** Project a narrowed union scrutinee into a named structural record expected
|
|
2954
|
-
* by a same-module/extern call. Resolution stamps named calls with paramTys;
|
|
2955
|
-
* this pass fires only when every target record field has an identically typed
|
|
2956
|
-
* match-bound source field. That deliberately avoids inventing a broad cast:
|
|
2957
|
-
* it is the nominal-backend witness for the structural call TS already accepts. */
|
|
2958
|
-
function projectStructuralCallArgsInTStmts(stmts, varName, fields) {
|
|
2959
|
-
const sourceFields = fields.map(f => ({
|
|
2960
|
-
...f,
|
|
2961
|
-
resolvedTy: f.type ?? parseTsType(f.tsType),
|
|
2962
|
-
}));
|
|
2963
|
-
return stmts.map(s => mapTStmt(s, e => {
|
|
2964
|
-
if (e.kind !== "call" || !e.paramTys)
|
|
2965
|
-
return null;
|
|
2966
|
-
const paramTys = e.paramTys;
|
|
2967
|
-
let changed = false;
|
|
2968
|
-
const args = e.args.map((arg, i) => {
|
|
2969
|
-
if (arg.kind !== "var" || arg.name !== varName || i >= paramTys.length)
|
|
2970
|
-
return arg;
|
|
2971
|
-
const targetTy = paramTys[i];
|
|
2972
|
-
const targetDecl = declOfTy(_typeDecls, targetTy);
|
|
2973
|
-
if (targetTy.kind !== "user" || targetDecl?.kind !== "record" || !targetDecl.fields)
|
|
2974
|
-
return arg;
|
|
2975
|
-
const matched = [];
|
|
2976
|
-
for (const targetField of targetDecl.fields) {
|
|
2977
|
-
const sourceField = sourceFields.find(f => f.name === targetField.name);
|
|
2978
|
-
const targetFieldTy = targetField.type ?? parseTsType(targetField.tsType);
|
|
2979
|
-
if (!sourceField || !tyEqual(sourceField.resolvedTy, targetFieldTy))
|
|
2980
|
-
return arg;
|
|
2981
|
-
matched.push({ targetField, sourceField });
|
|
2982
|
-
}
|
|
2983
|
-
changed = true;
|
|
2984
|
-
return {
|
|
2985
|
-
kind: "record",
|
|
2986
|
-
spread: null,
|
|
2987
|
-
fields: matched.map(m => ({
|
|
2988
|
-
name: m.targetField.name,
|
|
2989
|
-
value: {
|
|
2990
|
-
kind: "var",
|
|
2991
|
-
name: matchBinder(m.sourceField.name, varName),
|
|
2992
|
-
ty: m.sourceField.resolvedTy,
|
|
2993
|
-
},
|
|
2994
|
-
})),
|
|
2995
|
-
ty: targetTy,
|
|
2996
|
-
};
|
|
2997
|
-
});
|
|
2998
|
-
return changed ? { ...e, args } : null;
|
|
2999
|
-
}));
|
|
3000
|
-
}
|
|
3001
3077
|
function asTAccessPath(e) {
|
|
3002
3078
|
if (e.kind === "var")
|
|
3003
3079
|
return { rootVar: e.name, fields: [] };
|
|
@@ -3034,19 +3110,10 @@ function matchesAccessPath(e, path) {
|
|
|
3034
3110
|
* leaves no binding that shadows another (see LexicalNames), so the name
|
|
3035
3111
|
* identifies the variable, also inside a lambda that captures it. */
|
|
3036
3112
|
function replacePathInTExpr(expr, path, binder, binderTy) {
|
|
3037
|
-
return mapTExpr(expr, e => {
|
|
3038
|
-
if (matchesAccessPath(e, path))
|
|
3039
|
-
return { kind: "var", name: binder, ty: binderTy };
|
|
3040
|
-
if (e.kind === "lambda")
|
|
3041
|
-
return { ...e,
|
|
3042
|
-
params: e.params.map(p => p.defaultValue
|
|
3043
|
-
? { ...p, defaultValue: replacePathInTExpr(p.defaultValue, path, binder, binderTy) } : p),
|
|
3044
|
-
body: replacePathInTStmts(e.body, path, binder, binderTy) };
|
|
3045
|
-
return null;
|
|
3046
|
-
});
|
|
3113
|
+
return mapTExpr(expr, e => matchesAccessPath(e, path) ? { kind: "var", name: binder, ty: binderTy } : null);
|
|
3047
3114
|
}
|
|
3048
3115
|
function replacePathInTStmts(stmts, path, binder, binderTy) {
|
|
3049
|
-
return stmts.map(s => mapTStmt(s, e =>
|
|
3116
|
+
return stmts.map(s => mapTStmt(s, e => matchesAccessPath(e, path) ? { kind: "var", name: binder, ty: binderTy } : null));
|
|
3050
3117
|
}
|
|
3051
3118
|
// ── Pure function generation ─────────────────────────────────
|
|
3052
3119
|
function transformPureBody(stmts, typeDecls) {
|
|
@@ -3115,6 +3182,7 @@ function transformPureBody(stmts, typeDecls) {
|
|
|
3115
3182
|
return null;
|
|
3116
3183
|
}
|
|
3117
3184
|
function transformPureSwitch(s, typeDecls) {
|
|
3185
|
+
s = withExplicitVariantDefault(s, typeDecls);
|
|
3118
3186
|
const ef = enumFieldSwitch(s, typeDecls);
|
|
3119
3187
|
if (ef) {
|
|
3120
3188
|
const cases = s.cases.map(c => ({ name: c.label, body: c.body }));
|
|
@@ -3143,8 +3211,7 @@ function transformPureSwitch(s, typeDecls) {
|
|
|
3143
3211
|
: s.expr.kind === "checkedUnwrap" && s.expr.expr.kind === "var" ? s.expr.expr.name : undefined;
|
|
3144
3212
|
const cases = s.cases.map(c => ({ name: c.label, body: c.body }));
|
|
3145
3213
|
const arms = buildMatchArms(cases, varName, typeName, typeDecls, (body, vn, fields, ctorName) => {
|
|
3146
|
-
|
|
3147
|
-
let result = transformPureBody(projected, typeDecls);
|
|
3214
|
+
let result = transformPureBody(body, typeDecls);
|
|
3148
3215
|
if (!result)
|
|
3149
3216
|
return null;
|
|
3150
3217
|
if (fields.length > 0 && vn)
|
|
@@ -3173,8 +3240,7 @@ function transformPureMatch(chain, typeDecls) {
|
|
|
3173
3240
|
// the statement-level counterpart of this substitution.
|
|
3174
3241
|
const isSynthArrayUnion = decl?.discriminant === "__isArray__";
|
|
3175
3242
|
const arms = buildMatchArms(cases, chain.varName, chain.typeName, typeDecls, (body, vn, fields, ctorName) => {
|
|
3176
|
-
|
|
3177
|
-
let result = transformPureBody(projected, typeDecls);
|
|
3243
|
+
let result = transformPureBody(body, typeDecls);
|
|
3178
3244
|
if (!result)
|
|
3179
3245
|
return null;
|
|
3180
3246
|
if (fields.length > 0 && vn)
|
|
@@ -3191,11 +3257,10 @@ function transformPureMatch(chain, typeDecls) {
|
|
|
3191
3257
|
// since Lean errors on redundant match arms.
|
|
3192
3258
|
const allCovered = decl?.variants && chain.cases.length >= decl.variants.length;
|
|
3193
3259
|
if (chain.fallthrough.length > 0 && !allCovered) {
|
|
3194
|
-
const remaining = remainingVariant(
|
|
3260
|
+
const remaining = remainingVariant(decl, chain.cases.map(c => c.variant));
|
|
3195
3261
|
if (remaining) {
|
|
3196
3262
|
// Exactly one variant left — destructure for variant-specific field access.
|
|
3197
|
-
|
|
3198
|
-
let body = transformPureBody(projected, typeDecls);
|
|
3263
|
+
let body = transformPureBody(chain.fallthrough, typeDecls);
|
|
3199
3264
|
if (!body)
|
|
3200
3265
|
return null;
|
|
3201
3266
|
if (remaining.fields.length > 0)
|
|
@@ -3256,17 +3321,29 @@ function transformTypeDecl(d) {
|
|
|
3256
3321
|
/** Find parameter names that are reassigned anywhere in the body. */
|
|
3257
3322
|
function findReassignedNames(stmts, names) {
|
|
3258
3323
|
const found = new Set();
|
|
3324
|
+
const markRoot = (root) => {
|
|
3325
|
+
if (root && names.has(root))
|
|
3326
|
+
found.add(root);
|
|
3327
|
+
};
|
|
3259
3328
|
function scan(stmts) {
|
|
3260
3329
|
for (const s of stmts) {
|
|
3261
|
-
if (s.kind === "assign"
|
|
3262
|
-
|
|
3330
|
+
if (s.kind === "assign") {
|
|
3331
|
+
markRoot(s.target.split(".")[0]);
|
|
3332
|
+
if (s.value.kind === "call" && s.value.fn.kind === "field" &&
|
|
3333
|
+
(s.value.fn.field === "pop" || s.value.fn.field === "shift") && s.value.fn.obj.ty.kind === "array") {
|
|
3334
|
+
markRoot(placeRootVar(s.value.fn.obj));
|
|
3335
|
+
}
|
|
3336
|
+
}
|
|
3263
3337
|
if (s.kind === "ghostAssign" && names.has(s.target))
|
|
3264
3338
|
found.add(s.target);
|
|
3265
|
-
|
|
3339
|
+
if (s.kind === "let" && s.init.kind === "call" && s.init.fn.kind === "field" &&
|
|
3340
|
+
(s.init.fn.field === "pop" || s.init.fn.field === "shift") && s.init.fn.obj.ty.kind === "array") {
|
|
3341
|
+
markRoot(placeRootVar(s.init.fn.obj));
|
|
3342
|
+
}
|
|
3343
|
+
// Mutating collection calls: s.add(x), m.set(k,v), s.delete(x), arr.push(x), b.items.pop()
|
|
3266
3344
|
if (s.kind === "expr" && s.expr.kind === "call" && s.expr.fn.kind === "field" &&
|
|
3267
|
-
|
|
3268
|
-
|
|
3269
|
-
found.add(s.expr.fn.obj.name);
|
|
3345
|
+
["add", "set", "delete", "push", "unshift", "sort", "pop", "shift"].includes(s.expr.fn.field)) {
|
|
3346
|
+
markRoot(placeRootVar(s.expr.fn.obj));
|
|
3270
3347
|
}
|
|
3271
3348
|
if (s.kind === "if") {
|
|
3272
3349
|
scan(s.then);
|
|
@@ -3281,6 +3358,15 @@ function findReassignedNames(stmts, names) {
|
|
|
3281
3358
|
scan(c.body);
|
|
3282
3359
|
scan(s.defaultBody);
|
|
3283
3360
|
}
|
|
3361
|
+
if (s.kind === "someMatch") {
|
|
3362
|
+
scan(s.someBody);
|
|
3363
|
+
scan(s.noneBody);
|
|
3364
|
+
}
|
|
3365
|
+
if (s.kind === "tagMatch") {
|
|
3366
|
+
for (const c of s.cases)
|
|
3367
|
+
scan(c.body);
|
|
3368
|
+
scan(s.fallthrough);
|
|
3369
|
+
}
|
|
3284
3370
|
}
|
|
3285
3371
|
}
|
|
3286
3372
|
scan(stmts);
|