lemmascript 0.6.12 → 0.6.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,415 @@
1
+ /**
2
+ * Output checks for the narrow pass.
3
+ *
4
+ * These checks read narrow's output and report shapes that the later passes
5
+ * would emit incorrectly. They do not trust the types that `resolve` stamped on
6
+ * expression nodes: `resolve` copies TypeScript's flow narrowing onto a read of
7
+ * an optional, and that stamp is exactly what is wrong when narrow fails to
8
+ * bind the read inside a `someMatch`. Instead, the type of an access path is
9
+ * recomputed from declarations:
10
+ *
11
+ * - parameters, `let`/`ghostLet`, `for…of` names, lambda parameters and
12
+ * quantifier variables take their declared `ty`;
13
+ * - `\result` takes the function's return type;
14
+ * - inside the `Some` arm of a `someMatch`, the binder and (for a path
15
+ * scrutinee) the scrutinee path itself take the binder's type, because
16
+ * `transform` substitutes the binder for that path;
17
+ * - a field takes its declared type from the receiver's record, union variant,
18
+ * or class declaration. A field declared with `?` is optional.
19
+ *
20
+ * Paths whose declaration cannot be found (generic records, built-in members,
21
+ * globals) are not checked.
22
+ *
23
+ * Unwrapped-optional check. A violation is reported when
24
+ * - an access path is optional by declaration but `resolve` stamped it
25
+ * non-optional (it would be emitted as the raw `Option`), or
26
+ * - an optional value is the receiver of a field or index read, an operand of
27
+ * arithmetic (`+ - * / % **`, unary `-`), one of two optional operands of
28
+ * a relational comparison, or an argument for a parameter whose resolved
29
+ * type is a primitive or a collection, or
30
+ * - an arithmetic node stamped optional is an operand of a comparison
31
+ * (`=== !== < <= > >=`). Arithmetic never yields an optional; the stamp is
32
+ * left over from before narrow bound its operand, and `transform` lowers the
33
+ * comparison as a match on an `Option`. Elsewhere the stale stamp is unused.
34
+ * Allowed positions for an optional value: either side of `===`/`!==` (compared
35
+ * with `undefined`, `null`, or a value; `transform` lowers this when exactly one
36
+ * side is optional), one side of a relational comparison (lowered the same
37
+ * way), the left of `??` and the receiver of `?.`, a `someMatch` scrutinee,
38
+ * boolean positions (truthiness), arguments for optional, user-typed or
39
+ * unresolved parameters, and stored values.
40
+ *
41
+ * Binder-collision check. A violation is reported when a `someMatch` binder
42
+ * - equals an identifier in the user's source, or
43
+ * - reuses the name of an enclosing `someMatch` binder whose scrutinee is a
44
+ * different access path (or is not an access path), which would shadow the
45
+ * outer value.
46
+ */
47
+ import { parseTsType } from "./types.js";
48
+ const ARITH = new Set(["+", "-", "*", "/", "%", "**"]);
49
+ const RELATIONAL = new Set(["<", "<=", ">", ">="]);
50
+ // Operators `transform` lowers as a match when exactly one side is typed optional.
51
+ const COMPARISON = new Set([...RELATIONAL, "===", "!=="]);
52
+ const STALE_ARITH = "arithmetic result typed as optional; transform will treat the value as an Option";
53
+ const isStaleArith = (e) => ((e.kind === "binop" && ARITH.has(e.op)) || (e.kind === "unop" && e.op === "-")) && isOptional(e.ty);
54
+ // Parameter types that cannot accept an optional argument. A user type may be a
55
+ // type parameter instantiated with an optional, so it is not included.
56
+ const CONCRETE_PARAM = new Set(["bool", "nat", "int", "real", "string", "array", "tuple", "map", "set"]);
57
+ /** Run both checks over every function, method, and constant of a narrowed
58
+ * module. `userNames` is the set of identifiers in the user's source. */
59
+ export function checkNarrowedModule(mod, userNames) {
60
+ const out = [];
61
+ const globals = new Map();
62
+ for (const c of mod.constants)
63
+ globals.set(c.name, c.ty);
64
+ for (const fn of mod.functions)
65
+ checkFunction(fn, fn.name, null, globals, mod, userNames, out);
66
+ for (const cls of mod.classes) {
67
+ for (const m of cls.methods) {
68
+ checkFunction(m, `${cls.name}.${m.name}`, cls.name, globals, mod, userNames, out);
69
+ }
70
+ }
71
+ for (const c of mod.constants) {
72
+ walkExpr(c.value, { types: new Map(globals), binders: [] }, { mod, fn: c.name, userNames, out });
73
+ }
74
+ return out;
75
+ }
76
+ function checkFunction(fn, label, className, globals, mod, userNames, out) {
77
+ const types = new Map(globals);
78
+ for (const p of fn.params)
79
+ types.set(p.name, p.ty);
80
+ if (className !== null)
81
+ types.set("this", { kind: "user", name: className });
82
+ const ctx = { mod, fn: label, userNames, out };
83
+ const scope = { types, binders: [] };
84
+ for (const r of fn.requires)
85
+ walkExpr(r, scope, ctx);
86
+ if (fn.decreases)
87
+ walkExpr(fn.decreases, scope, ctx);
88
+ const post = { types: new Map(types), binders: [] };
89
+ post.types.set("\\result", fn.returnTy);
90
+ for (const e of fn.ensures)
91
+ walkExpr(e, post, ctx);
92
+ walkStmts(fn.body, { types: new Map(types), binders: [] }, ctx);
93
+ }
94
+ // ── Declared types ──────────────────────────────────────────
95
+ export function pathKey(e) {
96
+ if (e.kind === "var")
97
+ return e.name;
98
+ if (e.kind === "field") {
99
+ const inner = pathKey(e.obj);
100
+ return inner === null ? null : `${inner}.${e.field}`;
101
+ }
102
+ return null;
103
+ }
104
+ function declaredTy(e, scope, ctx) {
105
+ if (e.kind === "checkedUnwrap")
106
+ return e.ty;
107
+ const key = pathKey(e);
108
+ if (key !== null) {
109
+ const bound = scope.types.get(key);
110
+ if (bound)
111
+ return bound;
112
+ }
113
+ if (e.kind !== "field")
114
+ return null;
115
+ const objTy = declaredTy(e.obj, scope, ctx);
116
+ if (!objTy || objTy.kind === "optional")
117
+ return null;
118
+ return fieldTy(objTy, e.field, e.ofVariant, ctx);
119
+ }
120
+ function fieldTy(ty, field, ofVariant, ctx, depth = 0) {
121
+ if (depth > 8 || ty.kind !== "user")
122
+ return null;
123
+ const cls = ctx.mod.classes.find(c => c.name === ty.name);
124
+ if (cls)
125
+ return cls.fields.find(f => f.name === field)?.ty ?? null;
126
+ const decl = ctx.mod.typeDecls.find(d => d.name === ty.name);
127
+ if (!decl || (decl.typeParams && decl.typeParams.length > 0))
128
+ return null;
129
+ if (decl.kind === "alias" && decl.aliasOfTy)
130
+ return fieldTy(decl.aliasOfTy, field, ofVariant, ctx, depth + 1);
131
+ return fieldInfoTy(declField(decl, field, ofVariant));
132
+ }
133
+ function declField(decl, field, ofVariant) {
134
+ if (decl.kind === "record")
135
+ return decl.fields?.find(f => f.name === field) ?? null;
136
+ if (decl.kind !== "discriminated-union" || !decl.variants)
137
+ return null;
138
+ const variants = ofVariant ? decl.variants.filter(v => v.name === ofVariant) : decl.variants;
139
+ const found = variants.map(v => v.fields.find(f => f.name === field)).filter((f) => !!f);
140
+ // Without a known variant, only trust a field that every variant declaring it agrees is (non-)optional.
141
+ if (found.length === 0)
142
+ return null;
143
+ const optional = found.map(f => isOptional(fieldInfoTy(f)));
144
+ return optional.every(o => o === optional[0]) ? found[0] : null;
145
+ }
146
+ function fieldInfoTy(f) {
147
+ if (!f)
148
+ return null;
149
+ const ty = f.type ?? parseTsType(f.tsType);
150
+ return f.optionalKey && ty.kind !== "optional" ? { kind: "optional", inner: ty } : ty;
151
+ }
152
+ const isOptional = (ty) => ty?.kind === "optional";
153
+ /** The type to judge a value by: declared for an access path, otherwise the stamp. */
154
+ function valueTy(e, scope, ctx) {
155
+ return declaredTy(e, scope, ctx) ?? exprTy(e);
156
+ }
157
+ function exprTy(e) {
158
+ return "ty" in e ? e.ty : { kind: "unknown" };
159
+ }
160
+ // ── Walkers ─────────────────────────────────────────────────
161
+ function report(ctx, check, e, detail) {
162
+ ctx.out.push({ check, fn: ctx.fn, expr: typeof e === "string" ? e : show(e), detail });
163
+ }
164
+ function requireUnwrapped(e, role, scope, ctx) {
165
+ // Emitted arithmetic is never an Option; a stale stamp matters only under a comparison.
166
+ if (isStaleArith(e))
167
+ return;
168
+ if (isOptional(valueTy(e, scope, ctx)))
169
+ report(ctx, "unwrapped-optional", e, `optional value used as ${role}`);
170
+ }
171
+ function withBinder(scope, binder, binderTy, scrutinee, ctx) {
172
+ const path = pathKey(scrutinee);
173
+ if (ctx.userNames.has(binder)) {
174
+ report(ctx, "binder-collision", binder, `binder for ${show(scrutinee)} equals a user identifier`);
175
+ }
176
+ const outer = scope.binders.find(b => b.binder === binder);
177
+ if (outer && (outer.path === null || outer.path !== path)) {
178
+ report(ctx, "binder-collision", binder, `binder for ${show(scrutinee)} rebinds the enclosing binder for ${outer.path ?? "a non-path scrutinee"}`);
179
+ }
180
+ const types = new Map(scope.types);
181
+ types.set(binder, binderTy);
182
+ if (path !== null) {
183
+ // Facts about the scrutinee's subpaths came from the optional value; keep them.
184
+ types.set(path, binderTy);
185
+ }
186
+ return { types, binders: [...scope.binders, { binder, path }] };
187
+ }
188
+ function extend(scope, names) {
189
+ if (names.length === 0)
190
+ return scope;
191
+ const types = new Map(scope.types);
192
+ for (const n of names) {
193
+ types.set(n.name, n.ty);
194
+ // A rebound name hides any facts about its old subpaths.
195
+ for (const k of [...types.keys()])
196
+ if (k.startsWith(`${n.name}.`))
197
+ types.delete(k);
198
+ }
199
+ return { types, binders: scope.binders };
200
+ }
201
+ function walkExpr(e, scope, ctx) {
202
+ switch (e.kind) {
203
+ case "var": {
204
+ const d = declaredTy(e, scope, ctx);
205
+ if (isOptional(d) && !isOptional(e.ty)) {
206
+ report(ctx, "unwrapped-optional", e, "optional by declaration but typed as unwrapped, with no someMatch binding it");
207
+ }
208
+ return;
209
+ }
210
+ case "num":
211
+ case "bigint":
212
+ case "str":
213
+ case "bool":
214
+ case "havoc":
215
+ return;
216
+ case "checkedUnwrap":
217
+ walkScrutinee(e.expr, scope, ctx);
218
+ return;
219
+ case "field": {
220
+ requireUnwrapped(e.obj, "a field receiver", scope, ctx);
221
+ walkExpr(e.obj, scope, ctx);
222
+ const d = declaredTy(e, scope, ctx);
223
+ if (isOptional(d) && !isOptional(e.ty)) {
224
+ report(ctx, "unwrapped-optional", e, "optional by declaration but typed as unwrapped, with no someMatch binding it");
225
+ }
226
+ return;
227
+ }
228
+ case "index":
229
+ requireUnwrapped(e.obj, "an index receiver", scope, ctx);
230
+ walkExpr(e.obj, scope, ctx);
231
+ walkExpr(e.idx, scope, ctx);
232
+ return;
233
+ case "binop":
234
+ if (ARITH.has(e.op)) {
235
+ requireUnwrapped(e.left, `an operand of ${e.op}`, scope, ctx);
236
+ requireUnwrapped(e.right, `an operand of ${e.op}`, scope, ctx);
237
+ }
238
+ else if (COMPARISON.has(e.op)) {
239
+ for (const side of [e.left, e.right])
240
+ if (isStaleArith(side))
241
+ report(ctx, "unwrapped-optional", side, STALE_ARITH);
242
+ if (RELATIONAL.has(e.op) && isOptional(valueTy(e.left, scope, ctx)) && isOptional(valueTy(e.right, scope, ctx))) {
243
+ report(ctx, "unwrapped-optional", e, `both operands of ${e.op} are optional`);
244
+ }
245
+ }
246
+ walkExpr(e.left, scope, ctx);
247
+ walkExpr(e.right, scope, ctx);
248
+ return;
249
+ case "unop":
250
+ if (e.op === "-")
251
+ requireUnwrapped(e.expr, "an operand of unary -", scope, ctx);
252
+ walkExpr(e.expr, scope, ctx);
253
+ return;
254
+ case "call":
255
+ walkExpr(e.fn, scope, ctx);
256
+ e.args.forEach((a, i) => {
257
+ const p = e.paramTys?.[i];
258
+ if (p && CONCRETE_PARAM.has(p.kind))
259
+ requireUnwrapped(a, `an argument for a parameter of type ${p.kind}`, scope, ctx);
260
+ walkExpr(a, scope, ctx);
261
+ });
262
+ return;
263
+ case "record":
264
+ if (e.spread)
265
+ walkExpr(e.spread, scope, ctx);
266
+ for (const f of e.fields)
267
+ walkExpr(f.value, scope, ctx);
268
+ return;
269
+ case "arrayLiteral":
270
+ for (const x of e.elems)
271
+ walkExpr(x, scope, ctx);
272
+ return;
273
+ case "lambda":
274
+ walkStmts(e.body, extend(scope, e.params), ctx);
275
+ return;
276
+ case "conditional":
277
+ walkExpr(e.cond, scope, ctx);
278
+ walkExpr(e.then, scope, ctx);
279
+ walkExpr(e.else, scope, ctx);
280
+ return;
281
+ case "optChain":
282
+ walkExpr(e.obj, scope, ctx);
283
+ for (const step of e.chain) {
284
+ if (step.kind === "call")
285
+ for (const a of step.args)
286
+ walkExpr(a, scope, ctx);
287
+ if (step.kind === "index")
288
+ walkExpr(step.idx, scope, ctx);
289
+ }
290
+ return;
291
+ case "nullish":
292
+ walkExpr(e.left, scope, ctx);
293
+ walkExpr(e.right, scope, ctx);
294
+ return;
295
+ case "someMatch":
296
+ walkScrutinee(e.scrutinee, scope, ctx);
297
+ walkExpr(e.someBody, withBinder(scope, e.binder, e.binderTy, e.scrutinee, ctx), ctx);
298
+ walkExpr(e.noneBody, scope, ctx);
299
+ return;
300
+ case "tagMatch":
301
+ walkExpr(e.scrutinee, scope, ctx);
302
+ for (const c of e.cases)
303
+ walkExpr(c.body, scope, ctx);
304
+ if (e.fallthrough)
305
+ walkExpr(e.fallthrough, scope, ctx);
306
+ return;
307
+ case "forall":
308
+ case "exists":
309
+ walkExpr(e.body, extend(scope, [{ name: e.var, ty: e.varTy }]), ctx);
310
+ return;
311
+ }
312
+ }
313
+ /** A scrutinee is read as an optional, so its own stamp is not checked. */
314
+ function walkScrutinee(e, scope, ctx) {
315
+ if (e.kind === "field") {
316
+ requireUnwrapped(e.obj, "a field receiver", scope, ctx);
317
+ walkExpr(e.obj, scope, ctx);
318
+ }
319
+ else if (e.kind !== "var") {
320
+ walkExpr(e, scope, ctx);
321
+ }
322
+ }
323
+ function walkStmts(stmts, scope, ctx) {
324
+ let cur = scope;
325
+ for (const s of stmts)
326
+ cur = walkStmt(s, cur, ctx);
327
+ }
328
+ /** Walk one statement; returns the scope for the statements after it. */
329
+ function walkStmt(s, scope, ctx) {
330
+ switch (s.kind) {
331
+ case "let":
332
+ case "ghostLet":
333
+ walkExpr(s.init, scope, ctx);
334
+ return extend(scope, [{ name: s.name, ty: s.ty }]);
335
+ case "assign":
336
+ case "ghostAssign":
337
+ walkExpr(s.value, scope, ctx);
338
+ return scope;
339
+ case "return":
340
+ walkExpr(s.value, scope, ctx);
341
+ return scope;
342
+ case "expr":
343
+ walkExpr(s.expr, scope, ctx);
344
+ return scope;
345
+ case "assert":
346
+ walkExpr(s.expr, scope, ctx);
347
+ return scope;
348
+ case "break":
349
+ case "continue":
350
+ case "throw":
351
+ return scope;
352
+ case "if":
353
+ walkExpr(s.cond, scope, ctx);
354
+ walkStmts(s.then, scope, ctx);
355
+ walkStmts(s.else, scope, ctx);
356
+ return scope;
357
+ case "while":
358
+ walkExpr(s.cond, scope, ctx);
359
+ for (const inv of s.invariants)
360
+ walkExpr(inv, scope, ctx);
361
+ if (s.decreases)
362
+ walkExpr(s.decreases, scope, ctx);
363
+ if (s.doneWith)
364
+ walkExpr(s.doneWith, scope, ctx);
365
+ walkStmts(s.body, scope, ctx);
366
+ return scope;
367
+ case "switch":
368
+ walkExpr(s.expr, scope, ctx);
369
+ for (const c of s.cases)
370
+ walkStmts(c.body, scope, ctx);
371
+ walkStmts(s.defaultBody, scope, ctx);
372
+ return scope;
373
+ case "forof": {
374
+ walkExpr(s.iterable, scope, ctx);
375
+ const inner = extend(scope, s.names.map((name, i) => ({ name, ty: s.nameTypes[i] ?? { kind: "unknown" } })));
376
+ for (const inv of s.invariants)
377
+ walkExpr(inv, inner, ctx);
378
+ if (s.doneWith)
379
+ walkExpr(s.doneWith, inner, ctx);
380
+ walkStmts(s.body, inner, ctx);
381
+ return scope;
382
+ }
383
+ case "someMatch":
384
+ walkScrutinee(s.scrutinee, scope, ctx);
385
+ walkStmts(s.someBody, withBinder(scope, s.binder, s.binderTy, s.scrutinee, ctx), ctx);
386
+ walkStmts(s.noneBody, scope, ctx);
387
+ return scope;
388
+ case "tagMatch":
389
+ walkExpr(s.scrutinee, scope, ctx);
390
+ for (const c of s.cases)
391
+ walkStmts(c.body, scope, ctx);
392
+ walkStmts(s.fallthrough, scope, ctx);
393
+ return scope;
394
+ }
395
+ }
396
+ // ── Display ─────────────────────────────────────────────────
397
+ export function show(e) {
398
+ switch (e.kind) {
399
+ case "var": return e.name;
400
+ case "num": return String(e.value);
401
+ case "bigint": return `${e.value}n`;
402
+ case "str": return JSON.stringify(e.value);
403
+ case "bool": return String(e.value);
404
+ case "binop": return `(${show(e.left)} ${e.op} ${show(e.right)})`;
405
+ case "unop": return `${e.op}${show(e.expr)}`;
406
+ case "call": return `${show(e.fn)}(${e.args.map(show).join(", ")})`;
407
+ case "index": return `${show(e.obj)}[${show(e.idx)}]`;
408
+ case "field": return `${show(e.obj)}.${e.field}`;
409
+ case "conditional": return `(${show(e.cond)} ? ${show(e.then)} : ${show(e.else)})`;
410
+ case "nullish": return `(${show(e.left)} ?? ${show(e.right)})`;
411
+ case "someMatch": return `someMatch ${show(e.scrutinee)} { Some(${e.binder}) => ${show(e.someBody)}, None => ${show(e.noneBody)} }`;
412
+ case "checkedUnwrap": return `(${show(e.expr)}).value`;
413
+ default: return `<${e.kind}>`;
414
+ }
415
+ }
@@ -36,10 +36,11 @@
36
36
  import { isTerminatorKind } from "./typedir.js";
37
37
  import { builtinSpec } from "./builtins.js";
38
38
  import { presentFact, leadingPresent, leadingIsArray, flattenOr, noneDetector, bindPresentFact, freshPathBinder, binderHintForMapAccess, freshOcBinder, applyChain, restoreDiscriminantFlag, arrayBoundsCond, exprEqual, isArrayFact, typeofStringFact, variantFact, negVariantFact, presentMatchStmts, presentMatchExpr, } from "./condition-facts.js";
39
+ import { insertCheckedUnwraps } from "./checked-reads.js";
39
40
  // ── Walkers ──────────────────────────────────────────────────
40
41
  function walkExpr(e, ctx) {
41
42
  const r = recurseExpr(e, ctx);
42
- return ruleNullish(r, ctx) ?? ruleNullishIndex(r) ?? ruleOptChainIndex(r) ?? ruleOptChain(r, ctx) ?? ruleImplOptional(r, ctx) ?? ruleImplArrayIsArray(r, ctx) ?? ruleConditionalArrayIsArray(r, ctx) ?? ruleConditionalAndArrayIsArray(r, ctx) ?? ruleConditionalAndOptional(r, ctx) ?? ruleConditionalOptionalSimple(r, ctx) ?? ruleConditionalInMap(r, ctx) ?? ruleConditionalOptionalTruthy(r, ctx) ?? r;
43
+ return ruleNullishIndex(r) ?? ruleNullish(r, ctx) ?? ruleOptChainIndex(r) ?? ruleOptChain(r, ctx) ?? ruleImplOptional(r, ctx) ?? ruleImplArrayIsArray(r, ctx) ?? ruleConditionalArrayIsArray(r, ctx) ?? ruleConditionalAndArrayIsArray(r, ctx) ?? ruleConditionalAndOptional(r, ctx) ?? ruleConditionalOptionalSimple(r, ctx) ?? ruleConditionalInMap(r, ctx) ?? ruleConditionalOptionalTruthy(r, ctx) ?? r;
43
44
  }
44
45
  function recurseExpr(e, ctx) {
45
46
  const re = (x) => walkExpr(x, ctx);
@@ -69,6 +70,7 @@ function recurseExpr(e, ctx) {
69
70
  case "forall": return { ...e, body: re(e.body) };
70
71
  case "exists": return { ...e, body: re(e.body) };
71
72
  case "someMatch": return { ...e, someBody: re(e.someBody), noneBody: re(e.noneBody) };
73
+ case "checkedUnwrap": return { ...e, expr: re(e.expr) };
72
74
  case "tagMatch": return { ...e, scrutinee: re(e.scrutinee),
73
75
  cases: e.cases.map(c => ({ ...c, body: re(c.body) })),
74
76
  fallthrough: e.fallthrough ? re(e.fallthrough) : null };
@@ -155,9 +157,70 @@ function isTerminating(stmts) {
155
157
  return isTerminatorKind(stmts[stmts.length - 1].kind);
156
158
  }
157
159
  // ── Presence drivers ────────────────────────────────────────
160
+ /** Dotted path key for a pure variable/field expression, or null. */
161
+ function exprPathStr(e) {
162
+ if (e.kind === "var")
163
+ return e.name;
164
+ if (e.kind === "checkedUnwrap")
165
+ return exprPathStr(e.expr);
166
+ if (e.kind === "field") {
167
+ const inner = exprPathStr(e.obj);
168
+ return inner === null ? null : `${inner}.${e.field}`;
169
+ }
170
+ return null;
171
+ }
172
+ /** True if `stmts` contains an assignment to `pathStr` (or any prefix of
173
+ * `pathStr`, e.g. `box = ...` when narrowing `box.val`) that could clear it
174
+ * to `undefined` or an arbitrary `Option<T>` (not a `Some(...)` wrapper),
175
+ * meaning a `someMatch` binder would become stale (#342). */
176
+ function stmtsMayClearPath(stmts, pathStr) {
177
+ for (const s of stmts) {
178
+ if (s.kind === "assign") {
179
+ if (s.target === pathStr) {
180
+ const isSomeWrap = s.value.kind === "call" && s.value.fn.kind === "var" &&
181
+ s.value.fn.name === "Some" && s.value.args.length === 1;
182
+ if (!isSomeWrap && (s.value.ty.kind === "optional" || s.value.ty.kind === "void" ||
183
+ (s.value.kind === "var" && s.value.name === "undefined"))) {
184
+ return true;
185
+ }
186
+ }
187
+ else if (pathStr.startsWith(`${s.target}.`)) {
188
+ // Reassigning a container prefix (e.g. `box = newBox`) can replace the
189
+ // narrowed field with None, making a binder on `box.val` stale.
190
+ return true;
191
+ }
192
+ }
193
+ else if (s.kind === "if") {
194
+ if (stmtsMayClearPath(s.then, pathStr) || stmtsMayClearPath(s.else, pathStr))
195
+ return true;
196
+ }
197
+ else if (s.kind === "while" || s.kind === "forof") {
198
+ if (stmtsMayClearPath(s.body, pathStr))
199
+ return true;
200
+ }
201
+ else if (s.kind === "switch") {
202
+ if (s.cases.some(c => stmtsMayClearPath(c.body, pathStr)) || stmtsMayClearPath(s.defaultBody, pathStr))
203
+ return true;
204
+ }
205
+ else if (s.kind === "someMatch") {
206
+ if (stmtsMayClearPath(s.someBody, pathStr) || stmtsMayClearPath(s.noneBody, pathStr))
207
+ return true;
208
+ }
209
+ else if (s.kind === "tagMatch") {
210
+ if (s.cases.some(c => stmtsMayClearPath(c.body, pathStr)) || stmtsMayClearPath(s.fallthrough, pathStr))
211
+ return true;
212
+ }
213
+ }
214
+ return false;
215
+ }
216
+ function scrutineeMayBeCleared(scrutinee, stmts) {
217
+ const pathStr = exprPathStr(scrutinee);
218
+ return pathStr !== null && stmtsMayClearPath(stmts, pathStr);
219
+ }
158
220
  /** Driver: `if (e !== undefined) then else` — presence fact in if position.
159
221
  * → `someMatch e { Some(_e_val) => then, None => else }`. Requires a
160
- * non-empty Some branch. */
222
+ * non-empty Some branch, and defers to checked reads when `someBody` may
223
+ * clear `e` (or a prefix of `e`) to `undefined`/optional (#342). */
161
224
  function ruleIfOptionalSimple(s, ctx) {
162
225
  if (s.kind !== "if")
163
226
  return null;
@@ -168,6 +231,8 @@ function ruleIfOptionalSimple(s, ctx) {
168
231
  const noneBody = check.negated ? s.then : s.else;
169
232
  if (someBody.length === 0)
170
233
  return null;
234
+ if (scrutineeMayBeCleared(check.scrutinee, someBody))
235
+ return null;
171
236
  return presentMatchStmts(check, someBody, noneBody, ctx);
172
237
  }
173
238
  /** Driver: `if (e === undefined) terminate; rest` — presence fact in
@@ -187,6 +252,8 @@ function ruleEarlyReturnConsume(s, rest, ctx) {
187
252
  return null;
188
253
  if (!isTerminating(noneBranch))
189
254
  return null;
255
+ if (scrutineeMayBeCleared(check.scrutinee, rest))
256
+ return null;
190
257
  return presentMatchStmts(check, rest, noneBranch, ctx);
191
258
  }
192
259
  /** Driver: `if (D1 || … || Dn) terminate; rest` — De-Morgan position. Each `Di`
@@ -226,6 +293,8 @@ function ruleEarlyReturnOrChain(s, rest, ctx) {
226
293
  }
227
294
  if (detectors.length === 0)
228
295
  return null;
296
+ if (detectors.some(d => scrutineeMayBeCleared(d.scrutinee, rest)))
297
+ return null;
229
298
  let inner = residualLeaves.length === 0
230
299
  ? rest
231
300
  : [{ kind: "if", cond: residualLeaves.reduce((a, b) => ({ kind: "binop", op: "||", left: a, right: b, ty: { kind: "bool" } })), then: s.then, else: [] }, ...rest];
@@ -256,6 +325,8 @@ function ruleEarlyReturnOptChainCompare(s, rest, ctx) {
256
325
  const oc = c.left.kind === "optChain" ? c.left : c.right.kind === "optChain" ? c.right : null;
257
326
  if (!oc || oc.kind !== "optChain" || oc.obj.ty.kind !== "optional")
258
327
  return null;
328
+ if (scrutineeMayBeCleared(oc.obj, rest))
329
+ return null;
259
330
  const lit = c.left === oc ? c.right : c.left;
260
331
  const innerTy = oc.obj.ty.inner;
261
332
  const binder = freshPathBinder(oc.obj, ctx);
@@ -327,8 +398,14 @@ function ruleImplOptional(e, ctx) {
327
398
  function ruleNullish(e, ctx) {
328
399
  if (e.kind !== "nullish")
329
400
  return null;
330
- if (e.left.ty.kind !== "optional")
331
- return null;
401
+ // Non-optional left operand (#352): `undefined ?? r` -> `r`; plain `x ?? r` -> `x`.
402
+ if (e.left.ty.kind !== "optional") {
403
+ if (e.left.kind === "var" && e.left.name === "undefined")
404
+ return e.right;
405
+ if (e.left.ty.kind === "void")
406
+ return e.right;
407
+ return e.left;
408
+ }
332
409
  const innerTy = e.left.ty.inner;
333
410
  const binder = freshOcBinder(ctx);
334
411
  return {
@@ -404,8 +481,13 @@ function ruleOptionalIndexBinding(s) {
404
481
  function ruleOptChain(e, ctx) {
405
482
  if (e.kind !== "optChain")
406
483
  return null;
407
- if (e.obj.ty.kind !== "optional")
408
- return null;
484
+ // Non-optional receiver (#352): `undefined?.foo` -> `undefined`; plain `s?.length` -> `s.length`.
485
+ if (e.obj.ty.kind !== "optional") {
486
+ if ((e.obj.kind === "var" && e.obj.name === "undefined") || e.obj.ty.kind === "void") {
487
+ return { kind: "var", name: "undefined", ty: { kind: "void" } };
488
+ }
489
+ return applyChain(e.obj, e.chain);
490
+ }
409
491
  const innerTy = e.obj.ty.inner;
410
492
  const binder = freshOcBinder(ctx);
411
493
  const body = applyChain({ kind: "var", name: binder, ty: innerTy }, e.chain);
@@ -485,6 +567,8 @@ function ruleIfAndOptional(s, ctx) {
485
567
  if (!extracted)
486
568
  return null;
487
569
  const { check, restCond } = extracted;
570
+ if (scrutineeMayBeCleared(check.scrutinee, s.then))
571
+ return null;
488
572
  const innerIf = { kind: "if", cond: restCond, then: s.then, else: [] };
489
573
  return presentMatchStmts(check, [walkStmt(innerIf, ctx)], [], ctx);
490
574
  }
@@ -549,6 +633,7 @@ function containsMethodCall(e) {
549
633
  return false;
550
634
  case "binop": return containsMethodCall(e.left) || containsMethodCall(e.right);
551
635
  case "unop": return containsMethodCall(e.expr);
636
+ case "checkedUnwrap": return containsMethodCall(e.expr);
552
637
  case "call": return containsMethodCall(e.fn) || e.args.some(containsMethodCall);
553
638
  case "index": return containsMethodCall(e.obj) || containsMethodCall(e.idx);
554
639
  case "field": return containsMethodCall(e.obj);
@@ -778,7 +863,7 @@ function narrowFunction(fn, ctx) {
778
863
  }
779
864
  export function narrowModule(mod) {
780
865
  const ctx = { decls: mod.typeDecls, oc: { n: 0 } };
781
- return {
866
+ const narrowed = {
782
867
  ...mod,
783
868
  constants: mod.constants.map(c => ({ ...c, value: walkExpr(c.value, ctx) })),
784
869
  functions: mod.functions.map(fn => narrowFunction(fn, ctx)),
@@ -787,4 +872,5 @@ export function narrowModule(mod) {
787
872
  methods: cls.methods.map(m => narrowFunction(m, ctx)),
788
873
  })),
789
874
  };
875
+ return insertCheckedUnwraps(narrowed);
790
876
  }
@@ -247,6 +247,7 @@ function rewriteChildrenExpr(e) {
247
247
  case "toNat": return { ...e, expr: r(e.expr) };
248
248
  case "toInt": return { ...e, expr: r(e.expr) };
249
249
  case "toReal": return { ...e, expr: r(e.expr) };
250
+ case "checkedUnwrap": return { ...e, expr: r(e.expr) };
250
251
  case "index": return { ...e, arr: r(e.arr), idx: r(e.idx) };
251
252
  case "stringIndex": return { ...e, str: r(e.str), idx: r(e.idx) };
252
253
  case "tupleLiteral": return { ...e, elems: e.elems.map(r) };