lemmascript 0.6.13 → 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 CHANGED
@@ -63,6 +63,16 @@ From a sibling source checkout, the equivalent of `lsc` is `npx tsx ../LemmaScri
63
63
 
64
64
  The Dafny backend generates two files per TS source: `foo.dfy.gen` (always regeneratable) and `foo.dfy` (source of truth, with LLM/user proof additions). The diff between them must be additions-only.
65
65
 
66
+ Register standalone Dafny laws under their TypeScript source in `lemmascript.json`.
67
+
68
+ ```json
69
+ {
70
+ "proof-files": { "src/search.ts": ["proofs/search.dfy", "proofs/shared.dfy"] }
71
+ }
72
+ ```
73
+
74
+ Paths are relative to the config file. Both `lsc check src/search.ts` and a workspace `lsc check` that includes `src/search.ts` pass its registered files directly to Dafny, so errors point to the law you edit.
75
+
66
76
  ### Lean backend
67
77
 
68
78
  ```sh
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lemmascript",
3
- "version": "0.6.13",
3
+ "version": "0.6.15",
4
4
  "description": "A verification toolchain for TypeScript — generates Lean 4 or Dafny from annotated TS",
5
5
  "type": "module",
6
6
  "engines": {
@@ -30,6 +30,7 @@ export function isMutableRefTy(ty, typeDecls) {
30
30
  case "tuple":
31
31
  return true;
32
32
  case "optional":
33
+ case "nullish":
33
34
  return isMutableRefTy(ty.inner, typeDecls);
34
35
  case "user": {
35
36
  const decl = declOfTy(typeDecls, ty);
@@ -58,6 +59,7 @@ function hasNestedMutableRef(ty, typeDecls, seen = new Set()) {
58
59
  case "tuple":
59
60
  return ty.elems.some(e => isMutableRefTy(e, typeDecls));
60
61
  case "optional":
62
+ case "nullish":
61
63
  return hasNestedMutableRef(ty.inner, typeDecls, seen);
62
64
  case "user": {
63
65
  const decl = declOfTy(typeDecls, ty);
@@ -142,6 +144,15 @@ function aliasSourceInfo(e, typeDecls, allowNonMutableWrap = false) {
142
144
  return { direct: [...base.direct], shallow: [...base.shallow], derefBases: [...new Set(derefs)] };
143
145
  }
144
146
  case "call":
147
+ if (e.fn.kind === "var" && e.args.length === 1 && (e.fn.name === "Some" ||
148
+ e.fn.name === "NullishValue" ||
149
+ e.fn.name === "__optNullToNullish" ||
150
+ e.fn.name === "__optUndefToNullish" ||
151
+ e.fn.name === "__nullishToOption" ||
152
+ e.fn.name === "ArrayBranch" ||
153
+ e.fn.name === "NonArrayBranch")) {
154
+ return aliasSourceInfo(e.args[0], typeDecls, true);
155
+ }
145
156
  if (e.fn.kind === "field") {
146
157
  const m = e.fn.field;
147
158
  const objTy = e.fn.obj.ty.kind;
@@ -347,7 +358,8 @@ function mutationInfoOfStmt(s) {
347
358
  if (s.kind === "expr") {
348
359
  const e = s.expr;
349
360
  if (e.kind === "call" && e.fn.kind === "field" && (isMutatingCollectionMethod(e.fn.obj.ty, e.fn.field) ||
350
- (e.fn.obj.ty.kind === "unknown" && ["push", "unshift", "sort", "set", "add", "delete"].includes(e.fn.field)))) {
361
+ ((e.fn.field === "pop" || e.fn.field === "shift") && e.fn.obj.ty.kind === "array") ||
362
+ (e.fn.obj.ty.kind === "unknown" && ["push", "unshift", "sort", "pop", "shift", "set", "add", "delete"].includes(e.fn.field)))) {
351
363
  const root = accessPathRoot(e.fn.obj);
352
364
  if (!root)
353
365
  return null;
@@ -14,31 +14,31 @@
14
14
  * The registry holds classification only — no lowerings. Namespace builtins
15
15
  * (`Math.*`, `Array.isArray`) are recognized syntactically in resolve and
16
16
  * are not registry entries: they are not methods on receiver values.
17
- *
18
- * Classification values mirror the historical per-pass lists exactly
19
- * (byte-for-byte gauntlet compatibility), including their quirks — e.g.
20
- * `array.shift` returns the element type un-wrapped and `array.with` types
21
- * as `unknown`. Widen such bits deliberately, with tests.
22
17
  */
23
18
  const UNKNOWN = { kind: "unknown" };
24
19
  const BOOL = () => ({ kind: "bool" });
25
20
  const INT = () => ({ kind: "int" });
26
21
  const STRING = () => ({ kind: "string" });
27
22
  const self = (objTy) => objTy;
28
- const elem = (objTy) => objTy.kind === "array" ? objTy.elem : UNKNOWN;
29
23
  const optElem = (objTy) => objTy.kind === "array" ? { kind: "optional", inner: objTy.elem } : UNKNOWN;
24
+ const arrElemAt0 = (objTy, i) => i === 0 && objTy.kind === "array" ? objTy.elem : null;
25
+ const arrElemAll = (objTy) => objTy.kind === "array" ? objTy.elem : null;
26
+ const arrElemAt1 = (objTy, i) => i === 1 && objTy.kind === "array" ? objTy.elem : null;
27
+ const mapKeyAt0 = (objTy, i) => i === 0 && objTy.kind === "map" ? objTy.key : null;
28
+ const mapKeyVal = (objTy, i) => objTy.kind === "map" ? (i === 0 ? objTy.key : i === 1 ? objTy.value : null) : null;
29
+ const setElemAt0 = (objTy, i) => i === 0 && objTy.kind === "set" ? objTy.elem : null;
30
30
  /** The table is the single source: each key is `<RecvKind>.<method>`, which
31
31
  * *is* the `BuiltinId`. */
32
32
  export const BUILTINS = {
33
33
  // ── array ─────────────────────────────────────────────────
34
34
  "array.includes": { ret: BOOL, pure: true,
35
- intArgPositions: [1], argIsKey: true },
35
+ intArgPositions: [1], argIsKey: true, argSlot: arrElemAt0 },
36
36
  "array.indexOf": { ret: INT, pure: true,
37
- intArgPositions: [1] },
38
- "array.shift": { ret: elem, pure: false },
37
+ intArgPositions: [1], argSlot: arrElemAt0 },
38
+ "array.shift": { ret: optElem, pure: false },
39
39
  "array.pop": { ret: optElem, pure: false },
40
- "array.push": { ret: self, pure: false },
41
- "array.unshift": { ret: self, pure: false },
40
+ "array.push": { ret: self, pure: false, argSlot: arrElemAll },
41
+ "array.unshift": { ret: self, pure: false, argSlot: arrElemAll },
42
42
  "array.concat": { ret: self, pure: true },
43
43
  "array.sort": { ret: self, pure: false,
44
44
  hof: { shape: "comparator" } },
@@ -79,8 +79,8 @@ export const BUILTINS = {
79
79
  }
80
80
  return UNKNOWN;
81
81
  } },
82
- "array.with": { ret: () => UNKNOWN, pure: true,
83
- intArgPositions: [0] },
82
+ "array.with": { ret: (objTy) => objTy, pure: true,
83
+ intArgPositions: [0], argSlot: arrElemAt1 },
84
84
  // ── string ────────────────────────────────────────────────
85
85
  "string.trim": { ret: STRING, pure: true },
86
86
  "string.trimEnd": { ret: STRING, pure: true },
@@ -96,18 +96,18 @@ export const BUILTINS = {
96
96
  "string.startsWith": { ret: BOOL, pure: true },
97
97
  "string.endsWith": { ret: BOOL, pure: true },
98
98
  // ── map ───────────────────────────────────────────────────
99
- "map.get": { pure: true, argIsKey: true,
99
+ "map.get": { pure: true, argIsKey: true, argSlot: mapKeyAt0,
100
100
  ret: (objTy, _args, c) => objTy.kind !== "map" ? UNKNOWN
101
101
  : c.inSpec ? objTy.value : { kind: "optional", inner: objTy.value } },
102
- "map.has": { ret: BOOL, pure: true, argIsKey: true },
103
- "map.set": { ret: self, pure: false },
104
- "map.delete": { ret: self, pure: false },
102
+ "map.has": { ret: BOOL, pure: true, argIsKey: true, argSlot: mapKeyAt0 },
103
+ "map.set": { ret: self, pure: false, argSlot: mapKeyVal },
104
+ "map.delete": { ret: self, pure: false, argSlot: mapKeyAt0 },
105
105
  "map.keys": { ret: () => UNKNOWN, pure: true },
106
106
  "map.values": { ret: () => UNKNOWN, pure: true },
107
107
  // ── set ───────────────────────────────────────────────────
108
- "set.has": { ret: BOOL, pure: true, argIsKey: true },
109
- "set.add": { ret: self, pure: false },
110
- "set.delete": { ret: self, pure: false },
108
+ "set.has": { ret: BOOL, pure: true, argIsKey: true, argSlot: setElemAt0 },
109
+ "set.add": { ret: self, pure: false, argSlot: setElemAt0 },
110
+ "set.delete": { ret: self, pure: false, argSlot: setElemAt0 },
111
111
  };
112
112
  /** Recognize a builtin method call by receiver type kind + method name.
113
113
  * Called by resolve (once per call node); everything downstream reads the
@@ -26,14 +26,21 @@ function pathKey(e) {
26
26
  }
27
27
  return null;
28
28
  }
29
- function isOptional(ty) {
30
- return ty !== null && ty.kind === "optional";
29
+ function isNullable(ty) {
30
+ return ty !== null && (ty.kind === "optional" || ty.kind === "nullish");
31
31
  }
32
32
  function fieldInfoTy(f) {
33
33
  if (!f)
34
34
  return null;
35
35
  const ty = f.type ?? parseTsType(f.tsType);
36
- return f.optionalKey && ty.kind !== "optional" ? { kind: "optional", inner: ty } : ty;
36
+ if (!f.optionalKey)
37
+ return ty;
38
+ if (ty.kind === "nullish")
39
+ return ty;
40
+ if (ty.kind === "optional") {
41
+ return ty.absent === "null" ? { kind: "nullish", inner: ty.inner } : ty;
42
+ }
43
+ return { kind: "optional", inner: ty };
37
44
  }
38
45
  function declField(decl, field, ofVariant) {
39
46
  if (decl.kind === "record")
@@ -44,8 +51,8 @@ function declField(decl, field, ofVariant) {
44
51
  const found = variants.map(v => v.fields.find(f => f.name === field)).filter((f) => !!f);
45
52
  if (found.length === 0)
46
53
  return null;
47
- const optional = found.map(f => isOptional(fieldInfoTy(f)));
48
- return optional.every(o => o === optional[0]) ? found[0] : null;
54
+ const nullable = found.map(f => isNullable(fieldInfoTy(f)));
55
+ return nullable.every(o => o === nullable[0]) ? found[0] : null;
49
56
  }
50
57
  function fieldStorageTy(ty, field, ofVariant, mod, depth = 0) {
51
58
  if (depth > 8 || ty.kind !== "user")
@@ -73,7 +80,7 @@ function storageTyOf(e, scope, mod) {
73
80
  if (e.kind !== "field")
74
81
  return null;
75
82
  const objTy = storageTyOf(e.obj, scope, mod);
76
- if (!objTy || objTy.kind === "optional")
83
+ if (!objTy || objTy.kind === "optional" || objTy.kind === "nullish")
77
84
  return null;
78
85
  return fieldStorageTy(objTy, e.field, e.ofVariant, mod);
79
86
  }
@@ -98,36 +105,81 @@ function enterSomeMatch(scope, scrutinee, binder, binderTy) {
98
105
  return { types };
99
106
  }
100
107
  function isDefinitelyUnwrappedStamp(ty) {
101
- return !isOptional(ty) && ty.kind !== "unknown" && ty.kind !== "void";
108
+ return !isNullable(ty) && ty.kind !== "unknown" && ty.kind !== "void" && ty.kind !== "null";
109
+ }
110
+ function synthArrayProjection(storage, flowTy, mod) {
111
+ if (!storage || storage.kind !== "user")
112
+ return null;
113
+ if (flowTy.kind === "unknown" || flowTy.kind === "void" || flowTy.kind === "null")
114
+ return null;
115
+ if (flowTy.kind === "user" && flowTy.name === storage.name)
116
+ return null;
117
+ const decl = mod.typeDecls.find(d => d.name === storage.name);
118
+ if (!decl || decl.kind !== "discriminated-union" || decl.discriminant !== "__isArray__" || !decl.variants)
119
+ return null;
120
+ const variantName = flowTy.kind === "array" ? "ArrayBranch" : "NonArrayBranch";
121
+ const variant = decl.variants.find(v => v.name === variantName);
122
+ const field = variant?.fields[0]?.name;
123
+ return field ? { field, variant: variantName } : null;
124
+ }
125
+ /** Rewrite an expression whose leaf must keep its union storage type (e.g.,
126
+ * `Array.isArray(x)`, `typeof x`, or `tagMatch` scrutinee) while still
127
+ * rewriting any optional/synth-union receiver prefix. */
128
+ function rewriteUnionScrutinee(e, scope, mod) {
129
+ const storage = storageTyOf(e, scope, mod);
130
+ if (e.kind === "var" && storage && synthArrayProjection(storage, e.ty, mod)) {
131
+ return { ...e, ty: storage };
132
+ }
133
+ if (e.kind === "field") {
134
+ const obj = rewriteExpr(e.obj, scope, mod);
135
+ const updated = obj === e.obj ? e : { ...e, obj };
136
+ const fStorage = storageTyOf(updated, scope, mod);
137
+ if (fStorage && synthArrayProjection(fStorage, updated.ty, mod)) {
138
+ return { ...updated, ty: fStorage };
139
+ }
140
+ return updated;
141
+ }
142
+ return rewriteExpr(e, scope, mod);
102
143
  }
103
- /** Rewrite an expression that is the direct operand of `=== undefined` /
104
- * `!== undefined`: never wrap the operand itself in `checkedUnwrap` (restore
105
- * its declared optional storage type so `transform.ts` emits an `Option`
106
- * presence check), while still rewriting any optional receiver prefix. */
144
+ /** Rewrite an expression that is the direct operand of `===`/`!==`/`==`/`!=`
145
+ * with `undefined` or `null`: never wrap the operand itself in `checkedUnwrap`
146
+ * (restore its declared `Option<T>` or `Nullish<T>` storage type so
147
+ * `transform.ts` emits the right presence check), while still rewriting any
148
+ * optional/nullish receiver prefix. */
107
149
  function rewritePresenceOperand(e, scope, mod) {
108
150
  const storage = storageTyOf(e, scope, mod);
109
- if (e.kind === "var" && isOptional(storage)) {
151
+ if (e.kind === "var" && isNullable(storage)) {
110
152
  return { ...e, ty: storage };
111
153
  }
112
154
  if (e.kind === "field") {
113
155
  const obj = rewriteExpr(e.obj, scope, mod);
114
156
  const updated = obj === e.obj ? e : { ...e, obj };
115
157
  const fStorage = storageTyOf(updated, scope, mod);
116
- if (isOptional(fStorage))
158
+ if (isNullable(fStorage))
117
159
  return { ...updated, ty: fStorage };
118
160
  return updated;
119
161
  }
120
162
  return rewriteExpr(e, scope, mod);
121
163
  }
122
- function isUndefinedVar(e) {
123
- return e.kind === "var" && e.name === "undefined";
164
+ function isNullishVar(e) {
165
+ return e.kind === "var" && (e.name === "undefined" || e.name === "null");
124
166
  }
125
167
  function rewriteExpr(e, scope, mod) {
126
168
  switch (e.kind) {
127
169
  case "var": {
128
170
  const storage = storageTyOf(e, scope, mod);
129
- if (isOptional(storage) && isDefinitelyUnwrappedStamp(e.ty)) {
130
- return { kind: "checkedUnwrap", expr: { ...e, ty: storage }, ty: e.ty };
171
+ if (isNullable(storage)) {
172
+ if (isDefinitelyUnwrappedStamp(e.ty)) {
173
+ return { kind: "checkedUnwrap", expr: { ...e, ty: storage }, ty: e.ty };
174
+ }
175
+ // Partially narrowed `fromNullish` value still lives in `Nullish<T>` storage.
176
+ if (storage.kind === "nullish" && e.ty.kind === "optional" && e.ty.fromNullish) {
177
+ return { ...e, ty: storage };
178
+ }
179
+ }
180
+ const synthProj = synthArrayProjection(storage, e.ty, mod);
181
+ if (synthProj && storage) {
182
+ return { kind: "field", obj: { ...e, ty: storage }, field: synthProj.field, ty: e.ty, ofVariant: synthProj.variant };
131
183
  }
132
184
  return e;
133
185
  }
@@ -140,13 +192,22 @@ function rewriteExpr(e, scope, mod) {
140
192
  case "checkedUnwrap":
141
193
  return { ...e, expr: rewriteExpr(e.expr, scope, mod) };
142
194
  case "field": {
143
- // Rewrite receiver first (so an optional receiver `box` becomes `checkedUnwrap(box)`).
195
+ // Rewrite receiver first (so an optional/nullish receiver `box` becomes `checkedUnwrap(box)`).
144
196
  const obj = rewriteExpr(e.obj, scope, mod);
145
197
  const updated = obj === e.obj ? e : { ...e, obj };
146
- // Check if this field itself is optional by declaration (or bound in scope) while stamped non-optional.
198
+ // Check if this field itself is optional/nullish by declaration (or bound in scope) while stamped non-nullable.
147
199
  const storage = storageTyOf(updated, scope, mod);
148
- if (isOptional(storage) && isDefinitelyUnwrappedStamp(updated.ty)) {
149
- return { kind: "checkedUnwrap", expr: { ...updated, ty: storage }, ty: updated.ty };
200
+ if (isNullable(storage)) {
201
+ if (isDefinitelyUnwrappedStamp(updated.ty)) {
202
+ return { kind: "checkedUnwrap", expr: { ...updated, ty: storage }, ty: updated.ty };
203
+ }
204
+ if (storage.kind === "nullish" && updated.ty.kind === "optional" && updated.ty.fromNullish) {
205
+ return { ...updated, ty: storage };
206
+ }
207
+ }
208
+ const synthProj = synthArrayProjection(storage, updated.ty, mod);
209
+ if (synthProj && storage) {
210
+ return { kind: "field", obj: { ...updated, ty: storage }, field: synthProj.field, ty: updated.ty, ofVariant: synthProj.variant };
150
211
  }
151
212
  return updated;
152
213
  }
@@ -155,34 +216,57 @@ function rewriteExpr(e, scope, mod) {
155
216
  case "binop": {
156
217
  let left;
157
218
  let right;
158
- if ((e.op === "===" || e.op === "!==") && (isUndefinedVar(e.left) || isUndefinedVar(e.right))) {
159
- left = isUndefinedVar(e.right) ? rewritePresenceOperand(e.left, scope, mod) : rewriteExpr(e.left, scope, mod);
160
- right = isUndefinedVar(e.left) ? rewritePresenceOperand(e.right, scope, mod) : rewriteExpr(e.right, scope, mod);
219
+ if (["===", "!==", "==", "!="].includes(e.op) && (isNullishVar(e.left) || isNullishVar(e.right))) {
220
+ left = isNullishVar(e.right) ? rewritePresenceOperand(e.left, scope, mod) : rewriteExpr(e.left, scope, mod);
221
+ right = isNullishVar(e.left) ? rewritePresenceOperand(e.right, scope, mod) : rewriteExpr(e.right, scope, mod);
161
222
  }
162
223
  else {
163
224
  left = rewriteExpr(e.left, scope, mod);
164
225
  right = rewriteExpr(e.right, scope, mod);
165
226
  }
166
227
  let ty = e.ty;
167
- // Clear stale optional arithmetic stamp once operands are unwrapped.
168
- if (ARITH.has(e.op) && isOptional(ty) && !isOptional(left.ty) && !isOptional(right.ty)) {
228
+ // Clear stale optional/nullish arithmetic stamp once operands are unwrapped.
229
+ if (ARITH.has(e.op) && isNullable(ty) && !isNullable(left.ty) && !isNullable(right.ty)) {
169
230
  ty = left.ty;
170
231
  }
171
232
  return { ...e, left, right, ty };
172
233
  }
173
234
  case "unop": {
174
- const expr = rewriteExpr(e.expr, scope, mod);
235
+ const expr = e.op === "typeof"
236
+ ? rewriteUnionScrutinee(e.expr, scope, mod)
237
+ : rewriteExpr(e.expr, scope, mod);
175
238
  let ty = e.ty;
176
- if (e.op === "-" && isOptional(ty) && !isOptional(expr.ty))
239
+ if (e.op === "-" && isNullable(ty) && !isNullable(expr.ty))
177
240
  ty = expr.ty;
178
241
  return { ...e, expr, ty };
179
242
  }
180
- case "call":
181
- return {
182
- ...e,
183
- fn: rewriteExpr(e.fn, scope, mod),
184
- args: e.args.map(a => rewriteExpr(a, scope, mod)),
185
- };
243
+ case "call": {
244
+ if (e.fn.kind === "field" && e.fn.field === "isArray" &&
245
+ e.fn.obj.kind === "var" && e.fn.obj.name === "Array" && e.args.length === 1) {
246
+ return { ...e, args: [rewriteUnionScrutinee(e.args[0], scope, mod)] };
247
+ }
248
+ const fn = rewriteExpr(e.fn, scope, mod);
249
+ const args = e.args.map(a => rewriteExpr(a, scope, mod));
250
+ if (fn.kind === "var" && args.length === 1 && args[0].kind === "checkedUnwrap") {
251
+ const inner = args[0].expr;
252
+ // Re-wrapping a same-storage checkedUnwrap (`Some(x.value)` for Option<T>,
253
+ // `Nullish.Value(x.value)` for Nullish<T>) is a no-op; emit `x` directly.
254
+ if (fn.name === "Some" && inner.ty.kind === "optional" && !inner.ty.fromNullish) {
255
+ return inner;
256
+ }
257
+ if (fn.name === "NullishValue" && inner.ty.kind === "nullish") {
258
+ return inner;
259
+ }
260
+ }
261
+ if (fn.kind === "var" && args.length === 1 && args[0].kind === "field" &&
262
+ ((fn.name === "ArrayBranch" && args[0].ofVariant === "ArrayBranch") ||
263
+ (fn.name === "NonArrayBranch" && args[0].ofVariant === "NonArrayBranch")) &&
264
+ args[0].obj.ty.kind === "user" && e.ty.kind === "user" &&
265
+ args[0].obj.ty.name === e.ty.name) {
266
+ return args[0].obj;
267
+ }
268
+ return { ...e, fn, args };
269
+ }
186
270
  case "record":
187
271
  return {
188
272
  ...e,
@@ -216,10 +300,13 @@ function rewriteExpr(e, scope, mod) {
216
300
  return { ...e, left: rewriteExpr(e.left, scope, mod), right: rewriteExpr(e.right, scope, mod) };
217
301
  case "someMatch": {
218
302
  // Do NOT unwrap the scrutinee itself (it is supposed to remain Option<T>),
219
- // but DO rewrite any optional prefix inside a nested scrutinee (e.g. `box.inner`).
303
+ // but DO rewrite subexpressions inside non-var scrutinees (e.g. `box.inner`
304
+ // or `(flag ? x : undefined)`).
220
305
  const scrutinee = e.scrutinee.kind === "field"
221
306
  ? { ...e.scrutinee, obj: rewriteExpr(e.scrutinee.obj, scope, mod) }
222
- : e.scrutinee;
307
+ : e.scrutinee.kind === "var"
308
+ ? e.scrutinee
309
+ : rewriteExpr(e.scrutinee, scope, mod);
223
310
  const someScope = enterSomeMatch(scope, e.scrutinee, e.binder, e.binderTy);
224
311
  return {
225
312
  ...e,
@@ -231,7 +318,7 @@ function rewriteExpr(e, scope, mod) {
231
318
  case "tagMatch":
232
319
  return {
233
320
  ...e,
234
- scrutinee: rewriteExpr(e.scrutinee, scope, mod),
321
+ scrutinee: rewriteUnionScrutinee(e.scrutinee, scope, mod),
235
322
  cases: e.cases.map(c => ({ ...c, body: rewriteExpr(c.body, scope, mod) })),
236
323
  fallthrough: e.fallthrough ? rewriteExpr(e.fallthrough, scope, mod) : null,
237
324
  };
@@ -336,7 +423,7 @@ function rewriteStmts(stmts, scope, mod) {
336
423
  case "tagMatch":
337
424
  out.push({
338
425
  ...s,
339
- scrutinee: rewriteExpr(s.scrutinee, cur, mod),
426
+ scrutinee: rewriteUnionScrutinee(s.scrutinee, cur, mod),
340
427
  cases: s.cases.map(c => ({ ...c, body: rewriteStmts(c.body, cur, mod) })),
341
428
  fallthrough: rewriteStmts(s.fallthrough, cur, mod),
342
429
  });
@@ -19,8 +19,9 @@
19
19
  * State is explicit (§6.1): detection that mints binders or consults type
20
20
  * declarations takes a `CondCtx`; nothing module-level.
21
21
  */
22
+ import { isNullishStorageTy, optAbsent } from "./typedir.js";
22
23
  import { freshName, freshNameWhere, isUserName } from "./names.js";
23
- import { unionDeclOfTy, discriminantOf } from "./typedecls.js";
24
+ import { unionDeclOfTy, discriminantOf, declOfDotted, tyBaseName } from "./typedecls.js";
24
25
  /** Allocate within this context, retaining a path's name on repeated
25
26
  * detection. Semantic-only callers need no registry. */
26
27
  function freshBinder(ctx, hint, key) {
@@ -67,47 +68,93 @@ export function freshPathBinder(e, ctx) {
67
68
  export function bindPresentFact(f, ctx) {
68
69
  return { ...f, binder: freshPathBinder(f.scrutinee, ctx) };
69
70
  }
70
- /** Detect optional checks: `e !== undefined`, `e === undefined`, `!e`, or a
71
- * bare optional `e` — for a pure-access-path optional-typed `e`. `!e` and
72
- * bare `e` are truthiness forms. `!!c` is the same check as `c`. Following
73
- * TS, only pure access paths narrow; complex scrutinees return null. */
71
+ /** Detect optional/nullish checks: `e !== undefined`, `e === undefined`,
72
+ * `e !== null`, `e === null`, loose `e == null`/`e != null`/`e == undefined`/`e != undefined`,
73
+ * `!e`, or a bare nullable `e` — for a pure-access-path `Option<T>` or `Nullish<T>`.
74
+ * `!e` and bare `e` are truthiness forms. `!!c` is the same check as `c`.
75
+ * Following TS, only pure access paths narrow; complex scrutinees return null. */
74
76
  export function presentFact(cond) {
75
- if (cond.kind === "unop" && cond.op === "!" && cond.expr.kind === "unop" && cond.expr.op === "!")
76
- return presentFact(cond.expr.expr);
77
- // `!e` where e is optional — a truthiness form: false iff e is absent OR its
78
- // inner value is itself falsy (so `Some(0)`/`Some("")` count as falsy too).
79
- if (cond.kind === "unop" && cond.op === "!" && cond.expr.ty.kind === "optional") {
77
+ if (cond.kind === "unop" && cond.op === "!") {
78
+ if (cond.expr.kind === "unop" && cond.expr.op === "!")
79
+ return presentFact(cond.expr.expr);
80
+ // Negated explicit sentinel check: `!(x === undefined)`, `!(x !== undefined)`,
81
+ // `!(x === null)`, `!(x == null)`, etc. (#338). Non-truthiness facts invert
82
+ // cleanly by flipping `negated`.
83
+ const inner = presentFact(cond.expr);
84
+ if (inner && !inner.truthiness) {
85
+ return { ...inner, negated: !inner.negated };
86
+ }
87
+ }
88
+ // `!e` where e is optional or nullish — a truthiness form: false iff e is
89
+ // absent (None / Null / Undefined) OR its inner value is itself falsy.
90
+ if (cond.kind === "unop" && cond.op === "!" && (cond.expr.ty.kind === "optional" || cond.expr.ty.kind === "nullish")) {
80
91
  const e = cond.expr;
81
92
  const innerTy = cond.expr.ty.inner;
82
93
  const hint = binderHintFor(e);
83
94
  if (hint === null)
84
95
  return null;
85
- return { scrutinee: e, innerTy, negated: true, binder: freshName(hint), truthiness: true };
96
+ const isNullish = isNullishStorageTy(e.ty) ? true : undefined;
97
+ return { scrutinee: e, innerTy, negated: true, binder: freshName(hint), truthiness: true, ...(isNullish ? { isNullish } : {}) };
86
98
  }
87
- if (cond.kind !== "binop" || (cond.op !== "!==" && cond.op !== "===")) {
88
- // Bare optional truthiness: `if (e)` where e: T | undefined — true iff e is
89
- // present AND its inner value is truthy.
90
- if (cond.ty.kind === "optional") {
99
+ if (cond.kind !== "binop" || !["!==", "===", "!=", "=="].includes(cond.op)) {
100
+ // Bare nullable truthiness: `if (e)` where e: T | undefined | null.
101
+ if (cond.ty.kind === "optional" || cond.ty.kind === "nullish") {
91
102
  const hint = binderHintFor(cond);
92
103
  if (hint === null)
93
104
  return null;
94
- return { scrutinee: cond, innerTy: cond.ty.inner, negated: false, binder: freshName(hint), truthiness: true };
105
+ const isNullish = isNullishStorageTy(cond.ty) ? true : undefined;
106
+ return { scrutinee: cond, innerTy: cond.ty.inner, negated: false, binder: freshName(hint), truthiness: true, ...(isNullish ? { isNullish } : {}) };
95
107
  }
96
108
  return null;
97
109
  }
98
- // Explicit `e === undefined` / `e !== undefined` — a pure presence check,
99
- // independent of the inner value (so NOT a truthiness form).
110
+ // Explicit sentinel comparison: `e === undefined`, `e === null`, `e == null`, etc.
100
111
  let e = null;
101
- if (cond.right.kind === "var" && cond.right.name === "undefined")
112
+ let sentinel = null;
113
+ if (cond.right.kind === "var" && (cond.right.name === "undefined" || cond.right.name === "null")) {
102
114
  e = cond.left;
103
- if (cond.left.kind === "var" && cond.left.name === "undefined")
115
+ sentinel = cond.right.name;
116
+ }
117
+ else if (cond.left.kind === "var" && (cond.left.name === "undefined" || cond.left.name === "null")) {
104
118
  e = cond.right;
105
- if (!e || e.ty.kind !== "optional")
106
- return null;
107
- const hint = binderHintFor(e);
108
- if (hint === null)
119
+ sentinel = cond.left.name;
120
+ }
121
+ if (!e || !sentinel)
109
122
  return null;
110
- return { scrutinee: e, innerTy: e.ty.inner, negated: cond.op === "===", binder: freshName(hint), truthiness: false };
123
+ const isLoose = cond.op === "==" || cond.op === "!=";
124
+ const negated = cond.op === "===" || cond.op === "==";
125
+ if (e.ty.kind === "nullish") {
126
+ const hint = binderHintFor(e);
127
+ if (hint === null)
128
+ return null;
129
+ // Loose `== null` / `== undefined` checks BOTH sentinels, narrowing directly to T.
130
+ // Strict `=== null` rules out null (leaving T | undefined); strict `=== undefined`
131
+ // rules out undefined (leaving T | null).
132
+ const innerTy = isLoose
133
+ ? e.ty.inner
134
+ : sentinel === "null"
135
+ ? { kind: "optional", inner: e.ty.inner, absent: "undefined", fromNullish: true }
136
+ : { kind: "optional", inner: e.ty.inner, absent: "null", fromNullish: true };
137
+ return { scrutinee: e, innerTy, negated, binder: freshName(hint), truthiness: false, isNullish: true };
138
+ }
139
+ if (e.ty.kind === "optional") {
140
+ // On single-sentinel Option<T>, strict check against the *other* sentinel
141
+ // never matches and does NOT narrow (`x: T | undefined; x !== null` leaves
142
+ // x as T | undefined). Loose `==`/`!=` against either sentinel checks None.
143
+ if (!isLoose && sentinel !== optAbsent(e.ty))
144
+ return null;
145
+ const hint = binderHintFor(e);
146
+ if (hint === null)
147
+ return null;
148
+ const isNullish = e.ty.fromNullish ? true : undefined;
149
+ return { scrutinee: e, innerTy: e.ty.inner, negated, binder: freshName(hint), truthiness: false, ...(isNullish ? { isNullish } : {}) };
150
+ }
151
+ return null;
152
+ }
153
+ /** Presence fact restricted to genuine `Option<T>` storage (excluding `Nullish<T>`
154
+ * and partially narrowed `fromNullish` values, which stay off `someMatch`). */
155
+ export function optionalPresentFact(cond) {
156
+ const f = presentFact(cond);
157
+ return f && !f.isNullish ? f : null;
111
158
  }
112
159
  /** Which types have falsy values in JS (`0`, `""`, `false`); everything else
113
160
  * (array, user type, …) is always truthy. The single home of that set —
@@ -153,7 +200,7 @@ export function extractConjunct(cond, parse) {
153
200
  * It becomes the outermost match, keeping later path checks in its arm. */
154
201
  export function leadingPresent(cond) {
155
202
  return extractConjunct(cond, e => {
156
- const f = presentFact(e);
203
+ const f = optionalPresentFact(e);
157
204
  return f && !f.negated ? f : null;
158
205
  });
159
206
  }
@@ -164,22 +211,57 @@ export function flattenOr(e) {
164
211
  return [...flattenOr(e.left), ...flattenOr(e.right)];
165
212
  return [e];
166
213
  }
214
+ /** True when `e` cannot evaluate to `undefined` at runtime.
215
+ * Rules out `undefined`, optional/nullish/void/unknown types, function type
216
+ * parameters (which may be instantiated with `undefined`), and aliases to them,
217
+ * while keeping concrete declared types (records, unions, enums, classes). */
218
+ export function excludesUndefined(e, decls, typeParams) {
219
+ if (e.kind === "var" && e.name === "undefined")
220
+ return false;
221
+ return tyExcludesUndefined(e.ty, decls, typeParams);
222
+ }
223
+ function tyExcludesUndefined(ty, decls, typeParams, depth = 0) {
224
+ if (depth > 8)
225
+ return false;
226
+ switch (ty.kind) {
227
+ case "optional":
228
+ case "nullish":
229
+ case "void":
230
+ case "unknown":
231
+ return false;
232
+ case "user": {
233
+ const base = tyBaseName(ty.name);
234
+ if (typeParams?.has(base))
235
+ return false;
236
+ const decl = declOfDotted(decls, base);
237
+ if (decl?.kind === "alias" && decl.aliasOfTy) {
238
+ return tyExcludesUndefined(decl.aliasOfTy, decls, typeParams, depth + 1);
239
+ }
240
+ return true;
241
+ }
242
+ default:
243
+ return true;
244
+ }
245
+ }
167
246
  export function noneDetector(leaf, ctx) {
168
- // `x?.chain !== lit` — `undefined !== lit` is true when x is None.
247
+ // `x?.chain !== lit` — `undefined !== lit` is true when x is None, provided
248
+ // `lit` itself cannot evaluate to `undefined`.
169
249
  if (leaf.kind === "binop" && leaf.op === "!==") {
170
250
  const oc = leaf.left.kind === "optChain" ? leaf.left : leaf.right.kind === "optChain" ? leaf.right : null;
171
- if (oc && oc.kind === "optChain" && oc.obj.ty.kind === "optional") {
251
+ if (oc && oc.kind === "optChain" && oc.obj.ty.kind === "optional" && !oc.obj.ty.fromNullish) {
252
+ const lit = leaf.left === oc ? leaf.right : leaf.left;
253
+ if (!excludesUndefined(lit, ctx.decls, ctx.typeParams))
254
+ return null;
172
255
  const binder = freshPathBinder(oc.obj, ctx);
173
256
  if (binder === null)
174
257
  return null;
175
258
  const unwrapped = applyChain({ kind: "var", name: binder, ty: oc.obj.ty.inner }, oc.chain);
176
259
  restoreDiscriminantFlag(unwrapped, ctx.decls);
177
- const lit = leaf.left === oc ? leaf.right : leaf.left;
178
260
  return { scrutinee: oc.obj, innerTy: oc.obj.ty.inner, binder, residual: { kind: "binop", op: "!==", left: unwrapped, right: lit, ty: { kind: "bool" } } };
179
261
  }
180
262
  }
181
- // `!x` / `x === undefined`.
182
- const detected = presentFact(leaf);
263
+ // `!x` / `x === undefined` (genuine Option<T> only; Nullish<T> uses checked reads).
264
+ const detected = optionalPresentFact(leaf);
183
265
  if (detected && detected.negated) {
184
266
  const f = bindPresentFact(detected, ctx);
185
267
  const residual = canBeFalsy(f)