lemmascript 0.6.12 → 0.6.14

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,421 @@
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" || objTy.kind === "nullish")
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
+ if (!f.optionalKey)
151
+ return ty;
152
+ if (ty.kind === "nullish")
153
+ return ty;
154
+ if (ty.kind === "optional")
155
+ return ty.absent === "null" ? { kind: "nullish", inner: ty.inner } : ty;
156
+ return { kind: "optional", inner: ty };
157
+ }
158
+ const isOptional = (ty) => ty?.kind === "optional" || ty?.kind === "nullish";
159
+ /** The type to judge a value by: declared for an access path, otherwise the stamp. */
160
+ function valueTy(e, scope, ctx) {
161
+ return declaredTy(e, scope, ctx) ?? exprTy(e);
162
+ }
163
+ function exprTy(e) {
164
+ return "ty" in e ? e.ty : { kind: "unknown" };
165
+ }
166
+ // ── Walkers ─────────────────────────────────────────────────
167
+ function report(ctx, check, e, detail) {
168
+ ctx.out.push({ check, fn: ctx.fn, expr: typeof e === "string" ? e : show(e), detail });
169
+ }
170
+ function requireUnwrapped(e, role, scope, ctx) {
171
+ // Emitted arithmetic is never an Option; a stale stamp matters only under a comparison.
172
+ if (isStaleArith(e))
173
+ return;
174
+ if (isOptional(valueTy(e, scope, ctx)))
175
+ report(ctx, "unwrapped-optional", e, `optional value used as ${role}`);
176
+ }
177
+ function withBinder(scope, binder, binderTy, scrutinee, ctx) {
178
+ const path = pathKey(scrutinee);
179
+ if (ctx.userNames.has(binder)) {
180
+ report(ctx, "binder-collision", binder, `binder for ${show(scrutinee)} equals a user identifier`);
181
+ }
182
+ const outer = scope.binders.find(b => b.binder === binder);
183
+ if (outer && (outer.path === null || outer.path !== path)) {
184
+ report(ctx, "binder-collision", binder, `binder for ${show(scrutinee)} rebinds the enclosing binder for ${outer.path ?? "a non-path scrutinee"}`);
185
+ }
186
+ const types = new Map(scope.types);
187
+ types.set(binder, binderTy);
188
+ if (path !== null) {
189
+ // Facts about the scrutinee's subpaths came from the optional value; keep them.
190
+ types.set(path, binderTy);
191
+ }
192
+ return { types, binders: [...scope.binders, { binder, path }] };
193
+ }
194
+ function extend(scope, names) {
195
+ if (names.length === 0)
196
+ return scope;
197
+ const types = new Map(scope.types);
198
+ for (const n of names) {
199
+ types.set(n.name, n.ty);
200
+ // A rebound name hides any facts about its old subpaths.
201
+ for (const k of [...types.keys()])
202
+ if (k.startsWith(`${n.name}.`))
203
+ types.delete(k);
204
+ }
205
+ return { types, binders: scope.binders };
206
+ }
207
+ function walkExpr(e, scope, ctx) {
208
+ switch (e.kind) {
209
+ case "var": {
210
+ const d = declaredTy(e, scope, ctx);
211
+ if (isOptional(d) && !isOptional(e.ty)) {
212
+ report(ctx, "unwrapped-optional", e, "optional by declaration but typed as unwrapped, with no someMatch binding it");
213
+ }
214
+ return;
215
+ }
216
+ case "num":
217
+ case "bigint":
218
+ case "str":
219
+ case "bool":
220
+ case "havoc":
221
+ return;
222
+ case "checkedUnwrap":
223
+ walkScrutinee(e.expr, scope, ctx);
224
+ return;
225
+ case "field": {
226
+ requireUnwrapped(e.obj, "a field receiver", scope, ctx);
227
+ walkExpr(e.obj, scope, ctx);
228
+ const d = declaredTy(e, scope, ctx);
229
+ if (isOptional(d) && !isOptional(e.ty)) {
230
+ report(ctx, "unwrapped-optional", e, "optional by declaration but typed as unwrapped, with no someMatch binding it");
231
+ }
232
+ return;
233
+ }
234
+ case "index":
235
+ requireUnwrapped(e.obj, "an index receiver", scope, ctx);
236
+ walkExpr(e.obj, scope, ctx);
237
+ walkExpr(e.idx, scope, ctx);
238
+ return;
239
+ case "binop":
240
+ if (ARITH.has(e.op)) {
241
+ requireUnwrapped(e.left, `an operand of ${e.op}`, scope, ctx);
242
+ requireUnwrapped(e.right, `an operand of ${e.op}`, scope, ctx);
243
+ }
244
+ else if (COMPARISON.has(e.op)) {
245
+ for (const side of [e.left, e.right])
246
+ if (isStaleArith(side))
247
+ report(ctx, "unwrapped-optional", side, STALE_ARITH);
248
+ if (RELATIONAL.has(e.op) && isOptional(valueTy(e.left, scope, ctx)) && isOptional(valueTy(e.right, scope, ctx))) {
249
+ report(ctx, "unwrapped-optional", e, `both operands of ${e.op} are optional`);
250
+ }
251
+ }
252
+ walkExpr(e.left, scope, ctx);
253
+ walkExpr(e.right, scope, ctx);
254
+ return;
255
+ case "unop":
256
+ if (e.op === "-")
257
+ requireUnwrapped(e.expr, "an operand of unary -", scope, ctx);
258
+ walkExpr(e.expr, scope, ctx);
259
+ return;
260
+ case "call":
261
+ walkExpr(e.fn, scope, ctx);
262
+ e.args.forEach((a, i) => {
263
+ const p = e.paramTys?.[i];
264
+ if (p && CONCRETE_PARAM.has(p.kind))
265
+ requireUnwrapped(a, `an argument for a parameter of type ${p.kind}`, scope, ctx);
266
+ walkExpr(a, scope, ctx);
267
+ });
268
+ return;
269
+ case "record":
270
+ if (e.spread)
271
+ walkExpr(e.spread, scope, ctx);
272
+ for (const f of e.fields)
273
+ walkExpr(f.value, scope, ctx);
274
+ return;
275
+ case "arrayLiteral":
276
+ for (const x of e.elems)
277
+ walkExpr(x, scope, ctx);
278
+ return;
279
+ case "lambda":
280
+ walkStmts(e.body, extend(scope, e.params), ctx);
281
+ return;
282
+ case "conditional":
283
+ walkExpr(e.cond, scope, ctx);
284
+ walkExpr(e.then, scope, ctx);
285
+ walkExpr(e.else, scope, ctx);
286
+ return;
287
+ case "optChain":
288
+ walkExpr(e.obj, scope, ctx);
289
+ for (const step of e.chain) {
290
+ if (step.kind === "call")
291
+ for (const a of step.args)
292
+ walkExpr(a, scope, ctx);
293
+ if (step.kind === "index")
294
+ walkExpr(step.idx, scope, ctx);
295
+ }
296
+ return;
297
+ case "nullish":
298
+ walkExpr(e.left, scope, ctx);
299
+ walkExpr(e.right, scope, ctx);
300
+ return;
301
+ case "someMatch":
302
+ walkScrutinee(e.scrutinee, scope, ctx);
303
+ walkExpr(e.someBody, withBinder(scope, e.binder, e.binderTy, e.scrutinee, ctx), ctx);
304
+ walkExpr(e.noneBody, scope, ctx);
305
+ return;
306
+ case "tagMatch":
307
+ walkExpr(e.scrutinee, scope, ctx);
308
+ for (const c of e.cases)
309
+ walkExpr(c.body, scope, ctx);
310
+ if (e.fallthrough)
311
+ walkExpr(e.fallthrough, scope, ctx);
312
+ return;
313
+ case "forall":
314
+ case "exists":
315
+ walkExpr(e.body, extend(scope, [{ name: e.var, ty: e.varTy }]), ctx);
316
+ return;
317
+ }
318
+ }
319
+ /** A scrutinee is read as an optional, so its own stamp is not checked. */
320
+ function walkScrutinee(e, scope, ctx) {
321
+ if (e.kind === "field") {
322
+ requireUnwrapped(e.obj, "a field receiver", scope, ctx);
323
+ walkExpr(e.obj, scope, ctx);
324
+ }
325
+ else if (e.kind !== "var") {
326
+ walkExpr(e, scope, ctx);
327
+ }
328
+ }
329
+ function walkStmts(stmts, scope, ctx) {
330
+ let cur = scope;
331
+ for (const s of stmts)
332
+ cur = walkStmt(s, cur, ctx);
333
+ }
334
+ /** Walk one statement; returns the scope for the statements after it. */
335
+ function walkStmt(s, scope, ctx) {
336
+ switch (s.kind) {
337
+ case "let":
338
+ case "ghostLet":
339
+ walkExpr(s.init, scope, ctx);
340
+ return extend(scope, [{ name: s.name, ty: s.ty }]);
341
+ case "assign":
342
+ case "ghostAssign":
343
+ walkExpr(s.value, scope, ctx);
344
+ return scope;
345
+ case "return":
346
+ walkExpr(s.value, scope, ctx);
347
+ return scope;
348
+ case "expr":
349
+ walkExpr(s.expr, scope, ctx);
350
+ return scope;
351
+ case "assert":
352
+ walkExpr(s.expr, scope, ctx);
353
+ return scope;
354
+ case "break":
355
+ case "continue":
356
+ case "throw":
357
+ return scope;
358
+ case "if":
359
+ walkExpr(s.cond, scope, ctx);
360
+ walkStmts(s.then, scope, ctx);
361
+ walkStmts(s.else, scope, ctx);
362
+ return scope;
363
+ case "while":
364
+ walkExpr(s.cond, scope, ctx);
365
+ for (const inv of s.invariants)
366
+ walkExpr(inv, scope, ctx);
367
+ if (s.decreases)
368
+ walkExpr(s.decreases, scope, ctx);
369
+ if (s.doneWith)
370
+ walkExpr(s.doneWith, scope, ctx);
371
+ walkStmts(s.body, scope, ctx);
372
+ return scope;
373
+ case "switch":
374
+ walkExpr(s.expr, scope, ctx);
375
+ for (const c of s.cases)
376
+ walkStmts(c.body, scope, ctx);
377
+ walkStmts(s.defaultBody, scope, ctx);
378
+ return scope;
379
+ case "forof": {
380
+ walkExpr(s.iterable, scope, ctx);
381
+ const inner = extend(scope, s.names.map((name, i) => ({ name, ty: s.nameTypes[i] ?? { kind: "unknown" } })));
382
+ for (const inv of s.invariants)
383
+ walkExpr(inv, inner, ctx);
384
+ if (s.doneWith)
385
+ walkExpr(s.doneWith, inner, ctx);
386
+ walkStmts(s.body, inner, ctx);
387
+ return scope;
388
+ }
389
+ case "someMatch":
390
+ walkScrutinee(s.scrutinee, scope, ctx);
391
+ walkStmts(s.someBody, withBinder(scope, s.binder, s.binderTy, s.scrutinee, ctx), ctx);
392
+ walkStmts(s.noneBody, scope, ctx);
393
+ return scope;
394
+ case "tagMatch":
395
+ walkExpr(s.scrutinee, scope, ctx);
396
+ for (const c of s.cases)
397
+ walkStmts(c.body, scope, ctx);
398
+ walkStmts(s.fallthrough, scope, ctx);
399
+ return scope;
400
+ }
401
+ }
402
+ // ── Display ─────────────────────────────────────────────────
403
+ export function show(e) {
404
+ switch (e.kind) {
405
+ case "var": return e.name;
406
+ case "num": return String(e.value);
407
+ case "bigint": return `${e.value}n`;
408
+ case "str": return JSON.stringify(e.value);
409
+ case "bool": return String(e.value);
410
+ case "binop": return `(${show(e.left)} ${e.op} ${show(e.right)})`;
411
+ case "unop": return `${e.op}${show(e.expr)}`;
412
+ case "call": return `${show(e.fn)}(${e.args.map(show).join(", ")})`;
413
+ case "index": return `${show(e.obj)}[${show(e.idx)}]`;
414
+ case "field": return `${show(e.obj)}.${e.field}`;
415
+ case "conditional": return `(${show(e.cond)} ? ${show(e.then)} : ${show(e.else)})`;
416
+ case "nullish": return `(${show(e.left)} ?? ${show(e.right)})`;
417
+ case "someMatch": return `someMatch ${show(e.scrutinee)} { Some(${e.binder}) => ${show(e.someBody)}, None => ${show(e.noneBody)} }`;
418
+ case "checkedUnwrap": return `(${show(e.expr)}).value`;
419
+ default: return `<${e.kind}>`;
420
+ }
421
+ }
@@ -35,11 +35,12 @@
35
35
  */
36
36
  import { isTerminatorKind } from "./typedir.js";
37
37
  import { builtinSpec } from "./builtins.js";
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";
38
+ import { optionalPresentFact, 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,19 +157,83 @@ 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 isPresentWrap = s.value.kind === "call" && s.value.fn.kind === "var" &&
181
+ (s.value.fn.name === "Some" || s.value.fn.name === "NullishValue") && s.value.args.length === 1;
182
+ if (!isPresentWrap && (s.value.ty.kind === "optional" || s.value.ty.kind === "nullish" ||
183
+ s.value.ty.kind === "void" || s.value.ty.kind === "null" ||
184
+ (s.value.kind === "var" && (s.value.name === "undefined" || s.value.name === "null")))) {
185
+ return true;
186
+ }
187
+ }
188
+ else if (pathStr.startsWith(`${s.target}.`)) {
189
+ // Reassigning a container prefix (e.g. `box = newBox`) can replace the
190
+ // narrowed field with None, making a binder on `box.val` stale.
191
+ return true;
192
+ }
193
+ }
194
+ else if (s.kind === "if") {
195
+ if (stmtsMayClearPath(s.then, pathStr) || stmtsMayClearPath(s.else, pathStr))
196
+ return true;
197
+ }
198
+ else if (s.kind === "while" || s.kind === "forof") {
199
+ if (stmtsMayClearPath(s.body, pathStr))
200
+ return true;
201
+ }
202
+ else if (s.kind === "switch") {
203
+ if (s.cases.some(c => stmtsMayClearPath(c.body, pathStr)) || stmtsMayClearPath(s.defaultBody, pathStr))
204
+ return true;
205
+ }
206
+ else if (s.kind === "someMatch") {
207
+ if (stmtsMayClearPath(s.someBody, pathStr) || stmtsMayClearPath(s.noneBody, pathStr))
208
+ return true;
209
+ }
210
+ else if (s.kind === "tagMatch") {
211
+ if (s.cases.some(c => stmtsMayClearPath(c.body, pathStr)) || stmtsMayClearPath(s.fallthrough, pathStr))
212
+ return true;
213
+ }
214
+ }
215
+ return false;
216
+ }
217
+ function scrutineeMayBeCleared(scrutinee, stmts) {
218
+ const pathStr = exprPathStr(scrutinee);
219
+ return pathStr !== null && stmtsMayClearPath(stmts, pathStr);
220
+ }
158
221
  /** Driver: `if (e !== undefined) then else` — presence fact in if position.
159
222
  * → `someMatch e { Some(_e_val) => then, None => else }`. Requires a
160
- * non-empty Some branch. */
223
+ * non-empty Some branch, and defers to checked reads when `someBody` may
224
+ * clear `e` (or a prefix of `e`) to `undefined`/optional (#342). */
161
225
  function ruleIfOptionalSimple(s, ctx) {
162
226
  if (s.kind !== "if")
163
227
  return null;
164
- const check = presentFact(s.cond);
228
+ const check = optionalPresentFact(s.cond);
165
229
  if (!check)
166
230
  return null;
167
231
  const someBody = check.negated ? s.else : s.then;
168
232
  const noneBody = check.negated ? s.then : s.else;
169
233
  if (someBody.length === 0)
170
234
  return null;
235
+ if (scrutineeMayBeCleared(check.scrutinee, someBody))
236
+ return null;
171
237
  return presentMatchStmts(check, someBody, noneBody, ctx);
172
238
  }
173
239
  /** Driver: `if (e === undefined) terminate; rest` — presence fact in
@@ -178,7 +244,7 @@ function ruleEarlyReturnConsume(s, rest, ctx) {
178
244
  return null;
179
245
  if (rest.length === 0)
180
246
  return null;
181
- const check = presentFact(s.cond);
247
+ const check = optionalPresentFact(s.cond);
182
248
  if (!check)
183
249
  return null;
184
250
  const someBranch = check.negated ? s.else : s.then;
@@ -187,6 +253,8 @@ function ruleEarlyReturnConsume(s, rest, ctx) {
187
253
  return null;
188
254
  if (!isTerminating(noneBranch))
189
255
  return null;
256
+ if (scrutineeMayBeCleared(check.scrutinee, rest))
257
+ return null;
190
258
  return presentMatchStmts(check, rest, noneBranch, ctx);
191
259
  }
192
260
  /** Driver: `if (D1 || … || Dn) terminate; rest` — De-Morgan position. Each `Di`
@@ -226,6 +294,8 @@ function ruleEarlyReturnOrChain(s, rest, ctx) {
226
294
  }
227
295
  if (detectors.length === 0)
228
296
  return null;
297
+ if (detectors.some(d => scrutineeMayBeCleared(d.scrutinee, rest)))
298
+ return null;
229
299
  let inner = residualLeaves.length === 0
230
300
  ? rest
231
301
  : [{ kind: "if", cond: residualLeaves.reduce((a, b) => ({ kind: "binop", op: "||", left: a, right: b, ty: { kind: "bool" } })), then: s.then, else: [] }, ...rest];
@@ -254,7 +324,9 @@ function ruleEarlyReturnOptChainCompare(s, rest, ctx) {
254
324
  if (c.kind !== "binop" || c.op !== "!==")
255
325
  return null;
256
326
  const oc = c.left.kind === "optChain" ? c.left : c.right.kind === "optChain" ? c.right : null;
257
- if (!oc || oc.kind !== "optChain" || oc.obj.ty.kind !== "optional")
327
+ if (!oc || oc.kind !== "optChain" || oc.obj.ty.kind !== "optional" || oc.obj.ty.fromNullish)
328
+ return null;
329
+ if (scrutineeMayBeCleared(oc.obj, rest))
258
330
  return null;
259
331
  const lit = c.left === oc ? c.right : c.left;
260
332
  const innerTy = oc.obj.ty.inner;
@@ -277,7 +349,7 @@ function ruleEarlyReturnOptChainCompare(s, rest, ctx) {
277
349
  function ruleConditionalOptionalSimple(e, ctx) {
278
350
  if (e.kind !== "conditional")
279
351
  return null;
280
- const check = presentFact(e.cond);
352
+ const check = optionalPresentFact(e.cond);
281
353
  if (!check)
282
354
  return null;
283
355
  const someBody = check.negated ? e.else : e.then;
@@ -302,7 +374,7 @@ function ruleImplOptional(e, ctx) {
302
374
  restCond = extracted.restCond;
303
375
  }
304
376
  else {
305
- const c = presentFact(e.left);
377
+ const c = optionalPresentFact(e.left);
306
378
  if (!c || c.negated)
307
379
  return null;
308
380
  check = c;
@@ -327,8 +399,17 @@ function ruleImplOptional(e, ctx) {
327
399
  function ruleNullish(e, ctx) {
328
400
  if (e.kind !== "nullish")
329
401
  return null;
330
- if (e.left.ty.kind !== "optional")
402
+ // Nullish<T> (and partially narrowed fromNullish) lowers via a 3-arm match in transform.ts.
403
+ if (e.left.ty.kind === "nullish" || (e.left.ty.kind === "optional" && e.left.ty.fromNullish))
331
404
  return null;
405
+ // Non-optional left operand (#352): `undefined ?? r` / `null ?? r` -> `r`; plain `x ?? r` -> `x`.
406
+ if (e.left.ty.kind !== "optional") {
407
+ if (e.left.kind === "var" && (e.left.name === "undefined" || e.left.name === "null"))
408
+ return e.right;
409
+ if (e.left.ty.kind === "void" || e.left.ty.kind === "null")
410
+ return e.right;
411
+ return e.left;
412
+ }
332
413
  const innerTy = e.left.ty.inner;
333
414
  const binder = freshOcBinder(ctx);
334
415
  return {
@@ -404,8 +485,17 @@ function ruleOptionalIndexBinding(s) {
404
485
  function ruleOptChain(e, ctx) {
405
486
  if (e.kind !== "optChain")
406
487
  return null;
407
- if (e.obj.ty.kind !== "optional")
488
+ // Nullish<T> (and partially narrowed fromNullish) lowers via a 3-arm match in transform.ts.
489
+ if (e.obj.ty.kind === "nullish" || (e.obj.ty.kind === "optional" && e.obj.ty.fromNullish))
408
490
  return null;
491
+ // Non-optional receiver (#352): `undefined?.foo` / `null?.foo` -> `undefined`; plain `s?.length` -> `s.length`.
492
+ if (e.obj.ty.kind !== "optional") {
493
+ if ((e.obj.kind === "var" && (e.obj.name === "undefined" || e.obj.name === "null")) ||
494
+ e.obj.ty.kind === "void" || e.obj.ty.kind === "null") {
495
+ return { kind: "var", name: "undefined", ty: { kind: "void" } };
496
+ }
497
+ return applyChain(e.obj, e.chain);
498
+ }
409
499
  const innerTy = e.obj.ty.inner;
410
500
  const binder = freshOcBinder(ctx);
411
501
  const body = applyChain({ kind: "var", name: binder, ty: innerTy }, e.chain);
@@ -459,7 +549,7 @@ function ruleConditionalInMap(e, ctx) {
459
549
  function ruleConditionalOptionalTruthy(e, ctx) {
460
550
  if (e.kind !== "conditional")
461
551
  return null;
462
- if (e.cond.ty.kind !== "optional")
552
+ if (e.cond.ty.kind !== "optional" || e.cond.ty.fromNullish)
463
553
  return null;
464
554
  const binder = freshPathBinder(e.cond, ctx);
465
555
  if (binder === null)
@@ -485,6 +575,8 @@ function ruleIfAndOptional(s, ctx) {
485
575
  if (!extracted)
486
576
  return null;
487
577
  const { check, restCond } = extracted;
578
+ if (scrutineeMayBeCleared(check.scrutinee, s.then))
579
+ return null;
488
580
  const innerIf = { kind: "if", cond: restCond, then: s.then, else: [] };
489
581
  return presentMatchStmts(check, [walkStmt(innerIf, ctx)], [], ctx);
490
582
  }
@@ -549,6 +641,7 @@ function containsMethodCall(e) {
549
641
  return false;
550
642
  case "binop": return containsMethodCall(e.left) || containsMethodCall(e.right);
551
643
  case "unop": return containsMethodCall(e.expr);
644
+ case "checkedUnwrap": return containsMethodCall(e.expr);
552
645
  case "call": return containsMethodCall(e.fn) || e.args.some(containsMethodCall);
553
646
  case "index": return containsMethodCall(e.obj) || containsMethodCall(e.idx);
554
647
  case "field": return containsMethodCall(e.obj);
@@ -778,7 +871,7 @@ function narrowFunction(fn, ctx) {
778
871
  }
779
872
  export function narrowModule(mod) {
780
873
  const ctx = { decls: mod.typeDecls, oc: { n: 0 } };
781
- return {
874
+ const narrowed = {
782
875
  ...mod,
783
876
  constants: mod.constants.map(c => ({ ...c, value: walkExpr(c.value, ctx) })),
784
877
  functions: mod.functions.map(fn => narrowFunction(fn, ctx)),
@@ -787,4 +880,5 @@ export function narrowModule(mod) {
787
880
  methods: cls.methods.map(m => narrowFunction(m, ctx)),
788
881
  })),
789
882
  };
883
+ return insertCheckedUnwraps(narrowed);
790
884
  }
@@ -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) };