@native-sdk/cli 0.5.3 → 0.5.4

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.
Files changed (79) hide show
  1. package/build/app.zig +41 -1
  2. package/build.zig +223 -3
  3. package/native-sdk.d.ts +17 -1
  4. package/package.json +9 -9
  5. package/packages/core/package-lock.json +2 -2
  6. package/packages/core/package.json +1 -1
  7. package/packages/core/rt/rt.zig +138 -3
  8. package/packages/core/sdk/core.ts +225 -3
  9. package/packages/core/src/emitter.ts +2586 -259
  10. package/skill-data/native-ui/SKILL.md +3 -2
  11. package/skill-data/ts-core/SKILL.md +9 -1
  12. package/src/app_runner/root.zig +81 -1
  13. package/src/app_runner/ts_core_main.zig +4 -0
  14. package/src/embed/tests.zig +119 -1
  15. package/src/platform/linux/gtk_host.c +112 -3
  16. package/src/platform/linux/root.zig +71 -0
  17. package/src/platform/macos/appkit_host.h +48 -2
  18. package/src/platform/macos/appkit_host.m +533 -34
  19. package/src/platform/macos/cef_host.mm +262 -10
  20. package/src/platform/macos/root.zig +92 -4
  21. package/src/platform/null_platform.zig +298 -5
  22. package/src/platform/root.zig +33 -0
  23. package/src/platform/types.zig +138 -4
  24. package/src/platform/windows/root.zig +134 -0
  25. package/src/platform/windows/webview2_host.cpp +152 -40
  26. package/src/primitives/app_manifest/comptime_scene.zig +5 -0
  27. package/src/primitives/app_manifest/root.zig +1 -0
  28. package/src/primitives/app_manifest/types.zig +32 -0
  29. package/src/primitives/canvas/tests.zig +1 -0
  30. package/src/primitives/canvas/ui.zig +11 -7
  31. package/src/primitives/canvas/ui_markup.zig +58 -34
  32. package/src/primitives/canvas/ui_markup_binary.zig +4 -1
  33. package/src/primitives/canvas/ui_markup_compiled.zig +23 -8
  34. package/src/primitives/canvas/ui_markup_compiled_tests.zig +55 -0
  35. package/src/primitives/canvas/ui_markup_contract.zig +1 -1
  36. package/src/primitives/canvas/ui_markup_contract_tests.zig +26 -0
  37. package/src/primitives/canvas/ui_markup_huge_document_tests.zig +154 -0
  38. package/src/primitives/canvas/ui_markup_tests.zig +29 -9
  39. package/src/primitives/canvas/ui_markup_view.zig +29 -11
  40. package/src/primitives/canvas/ui_markup_view_tests.zig +150 -9
  41. package/src/primitives/canvas/ui_schema.zig +13 -0
  42. package/src/primitives/canvas/ui_schema_tests.zig +5 -4
  43. package/src/root.zig +7 -0
  44. package/src/runtime/api.zig +6 -4
  45. package/src/runtime/bridge_payload.zig +7 -0
  46. package/src/runtime/bridge_responses.zig +5 -0
  47. package/src/runtime/builtin_bridge.zig +9 -4
  48. package/src/runtime/canvas_font_tests.zig +439 -2
  49. package/src/runtime/canvas_fonts.zig +61 -6
  50. package/src/runtime/canvas_image_tests.zig +195 -0
  51. package/src/runtime/canvas_images.zig +45 -12
  52. package/src/runtime/core.zig +58 -11
  53. package/src/runtime/effects.zig +1664 -43
  54. package/src/runtime/effects_fetch_tests.zig +89 -1
  55. package/src/runtime/effects_file_tests.zig +41 -1
  56. package/src/runtime/effects_image_tests.zig +1304 -0
  57. package/src/runtime/effects_tests.zig +153 -0
  58. package/src/runtime/flow.zig +17 -0
  59. package/src/runtime/root.zig +11 -0
  60. package/src/runtime/session_blobs.zig +689 -0
  61. package/src/runtime/session_journal.zig +85 -21
  62. package/src/runtime/session_record.zig +27 -2
  63. package/src/runtime/session_replay.zig +168 -16
  64. package/src/runtime/session_tests.zig +1992 -0
  65. package/src/runtime/shell_layout.zig +7 -0
  66. package/src/runtime/testdata/fonts/NotoSansSC-Receipt.ttf +0 -0
  67. package/src/runtime/testdata/fonts/OFL.txt +93 -0
  68. package/src/runtime/tests.zig +2 -0
  69. package/src/runtime/ts_core_host.zig +439 -4
  70. package/src/runtime/ts_core_host_tests.zig +41 -0
  71. package/src/runtime/ts_ui_app.zig +7 -0
  72. package/src/runtime/ui_app.zig +111 -6
  73. package/src/runtime/ui_app_window_tests.zig +468 -0
  74. package/src/runtime/window_command_bridge_tests.zig +117 -0
  75. package/src/runtime/window_storage.zig +32 -0
  76. package/src/runtime/window_views.zig +61 -1
  77. package/src/tooling/manifest.zig +75 -0
  78. package/src/tooling/raw_manifest.zig +2 -0
  79. package/src/tooling/templates.zig +219 -1
@@ -55,6 +55,26 @@ class EmitError extends Error {
55
55
  }
56
56
  }
57
57
 
58
+ /// One enclosing edge-target construct (see Ctx.edgeKills). `label` is the
59
+ /// SOURCE label naming the construct (loopLabel mangling happens at
60
+ /// emission), null for unlabeled ones. An unlabeled `break` binds the
61
+ /// innermost loop-or-switch stage, an unlabeled `continue` the innermost
62
+ /// loop, labeled exits the innermost stage carrying their label, and a
63
+ /// lifted callback's lowered `return` the innermost callback stage.
64
+ interface EdgeKillStage {
65
+ readonly kind: "loop" | "switch" | "block" | "callback";
66
+ readonly label: string | null;
67
+ readonly kills: Set<string>;
68
+ }
69
+
70
+ /// Where a closing scope's recorded kills go — kills travel the same edges
71
+ /// control does. `merge` applies them to the surviving fall-through flow;
72
+ /// `drop` discards them (every route leaves the emitted function); an array
73
+ /// of destination sets carries them along the scope's non-local edges (the
74
+ /// enclosing try's pending catch set, break/continue target stages, the
75
+ /// lifted callback's stage), each applied where its edge lands.
76
+ type KillRouting = "merge" | "drop" | readonly Set<string>[];
77
+
58
78
  interface Ctx {
59
79
  readonly lines: string[];
60
80
  indent: number;
@@ -70,14 +90,71 @@ interface Ctx {
70
90
  /// `throw` (or a throwing call) breaks to it; null means the throw
71
91
  /// propagates (`return error.Thrown`) to the caller.
72
92
  tryLabel?: string | null;
93
+ /// R20: true while emitting inside a try body whose local catch has some
94
+ /// route back into the function. There ANY statement containing a
95
+ /// throwing call is a resuming route — it lands in the catch, and the
96
+ /// catch's fall-back carries the region's narrowing kills to a merge
97
+ /// point — so kill dropping (allRoutesLeaveFunction) treats each one as
98
+ /// a route that does not leave. A catch whose every route leaves the
99
+ /// function (including its own throws, judged against ITS enclosing
100
+ /// handler) closes that path, and the flag stays off for its body.
101
+ catchResumes?: boolean;
102
+ /// R20: the ENCLOSING try's pending exception kills — kills travel the
103
+ /// same edges control does (allRoutesLeaveFunction's route destinations).
104
+ /// A scope whose only in-function routes are throws caught by that try's
105
+ /// catch never falls through into the try body's remaining statements,
106
+ /// so its kills must not merge into intra-try flow; they wait here and
107
+ /// emitTryCore hands them to the catch as its ENTRY state (the catch
108
+ /// body's reads see them), where they ride the catch's own kill-frame
109
+ /// routing out — post-try on fall-through, the edge stage on a
110
+ /// break/continue, dropped when every catch route leaves the function
111
+ /// (see popNarrowKillFrame's route form). The throw edge is one instance
112
+ /// of the general rule; break/continue/lowered-return edges stage the
113
+ /// same way on edgeKills below.
114
+ pendingCatchKills?: Set<string> | null;
115
+ /// The enclosing edge-target constructs of the emitted function,
116
+ /// innermost last: loops, switches, labeled blocks, and lifted-callback
117
+ /// value blocks. A scope that exits ONLY along break/continue/lowered-
118
+ /// return edges stages its kills on the target construct's set
119
+ /// (popNarrowKillFrame's route form, the sibling of pendingCatchKills),
120
+ /// and the construct's emitter applies them where those edges land — the
121
+ /// post-construct state for breaks and callback returns, and for
122
+ /// continue edges the back-edge join, which the emitter also realizes as
123
+ /// the post-loop state: the loop-entry model delegates in-body
124
+ /// next-iteration reads to tsc (the checker rejects a read relying on a
125
+ /// narrow the back edge kills), so the only emission the kill must still
126
+ /// reach is the normal-completion exit. Applying a stage records into
127
+ /// the then-innermost kill frame, so staged kills keep propagating
128
+ /// outward exactly like merge-class kills.
129
+ readonly edgeKills: EdgeKillStage[];
73
130
  /// decl node -> zig identifier
74
131
  readonly names: Map<ts.Node, string>;
75
132
  readonly used: Set<string>;
76
133
  /// normalized source text of an expression -> replacement zig expr
77
134
  /// (optional-narrowing captures, union payload captures)
78
135
  readonly memberSubst: Map<string, string>;
136
+ /// The subset of memberSubst entries that RENAME without narrowing: a
137
+ /// union payload capture of an optional-typed field holds the payload
138
+ /// as-is (`.got => |parsed|` with `got: ?f64` binds `parsed: ?f64`), so
139
+ /// type queries must keep the optional. Maps key -> that replacement;
140
+ /// zTypeOfExpr only unwraps when the ACTIVE replacement differs (a
141
+ /// null-guard capture overwriting the key installs a fresh name, so the
142
+ /// identity check stays correct through save/restore cycles).
143
+ readonly stillOptionalSubst: Map<string, string>;
79
144
  /// source text of a union-typed expr -> active arm tag (kind guards)
80
145
  readonly narrowedUnion: Map<string, string>;
146
+ /// Invalidation frames, innermost last: every scope that snapshots and
147
+ /// restores the narrowing maps pushes a Set here, and the assignment path
148
+ /// records into the innermost frame each memberSubst key whose narrowing
149
+ /// it permanently deleted (the assigned value may be null again). The
150
+ /// snapshot restore at scope exit gives CONTAINMENT — narrowings added
151
+ /// inside the scope die there — but restoring alone would also resurrect
152
+ /// narrowings an assignment inside the scope killed; re-applying the
153
+ /// frame's deletions after the restore keeps those dead. Frames merge
154
+ /// outward on pop so an inner branch's kill reaches every enclosing exit
155
+ /// it can fall through to; a scope that always leaves the function drops
156
+ /// its kills instead (see popNarrowKillFrame).
157
+ readonly narrowKilled: Set<string>[];
81
158
  /// declared/inferred types of locals
82
159
  readonly localTypes: Map<ts.Node, ZType>;
83
160
  /// Locally-owned arrays with length-changing mutations (the push-builder
@@ -140,6 +217,7 @@ const MAX_SPAWN_ARGV = 16;
140
217
  const MAX_SPAWN_ARGV_BYTES = 2048;
141
218
  const MAX_SPAWN_STDIN_BYTES = 4096;
142
219
  const MAX_AUDIO_PATH_BYTES = 1024;
220
+ const MAX_IMAGE_PATH_BYTES = 1024;
143
221
 
144
222
  /// The closed `Cmd.fetch` verb set, wire value = position.
145
223
  const FETCH_METHODS = ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD"];
@@ -149,6 +227,15 @@ const FETCH_METHODS = ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD"];
149
227
  /// the app's own).
150
228
  const AUDIO_STATES = ["loaded", "position", "completed", "failed", "rejected", "spectrum"];
151
229
 
230
+ /// The image load result states an event arm's `state` union must carry —
231
+ /// the engine's outcome vocabulary, matched by member NAME (declaration
232
+ /// order is the app's own).
233
+ const IMAGE_STATES = [
234
+ "loaded", "rejected", "not_found", "io_failed", "connect_failed", "tls_failed",
235
+ "protocol_failed", "timed_out", "http_status", "cancelled", "too_large",
236
+ "unsupported", "decode_failed", "registry_full", "alloc_failed",
237
+ ];
238
+
152
239
  /// Names the emitted module's own fixtures occupy (header helpers + commit
153
240
  /// machinery): module-level claims and function locals unique around them.
154
241
  const emittedFixtureNames = [
@@ -225,6 +312,10 @@ export class Emitter {
225
312
  private readonly genericNames = new Set<string>();
226
313
  private readonly sourceName: string;
227
314
  private readonly capacities: KernelCapacities;
315
+ /// Per-switch memo for the defaultless value-switch exhaustiveness
316
+ /// consult (alwaysExits re-asks along every kill-routing scan).
317
+ private switchCoversTypeMemo = new WeakMap<ts.SwitchStatement, boolean>();
318
+
228
319
  /// Computed once at the top of emitModule (before any type emission).
229
320
  private helpers: ModelHelper[] = [];
230
321
  private unbound: { model: string[]; msg: string[] } = { model: [], msg: [] };
@@ -972,7 +1063,10 @@ export class Emitter {
972
1063
  names: new Map(),
973
1064
  used: this.moduleScopeNames(),
974
1065
  memberSubst: new Map(),
1066
+ stillOptionalSubst: new Map(),
975
1067
  narrowedUnion: new Map(),
1068
+ narrowKilled: [],
1069
+ edgeKills: [],
976
1070
  localTypes: new Map(),
977
1071
  builders: new Map(),
978
1072
  retLabel: null,
@@ -1349,7 +1443,10 @@ export class Emitter {
1349
1443
  names: new Map(),
1350
1444
  used: new Set(),
1351
1445
  memberSubst: new Map(),
1446
+ stillOptionalSubst: new Map(),
1352
1447
  narrowedUnion: new Map(),
1448
+ narrowKilled: [],
1449
+ edgeKills: [],
1353
1450
  localTypes: new Map(),
1354
1451
  builders: new Map(),
1355
1452
  retLabel: null,
@@ -1605,7 +1702,10 @@ export class Emitter {
1605
1702
  names: new Map(),
1606
1703
  used: this.moduleScopeNames(),
1607
1704
  memberSubst: new Map(),
1705
+ stillOptionalSubst: new Map(),
1608
1706
  narrowedUnion: new Map(),
1707
+ narrowKilled: [],
1708
+ edgeKills: [],
1609
1709
  localTypes: new Map(),
1610
1710
  builders: new Map(),
1611
1711
  retLabel: null,
@@ -1829,7 +1929,10 @@ export class Emitter {
1829
1929
  names: new Map(),
1830
1930
  used: this.moduleScopeNames(),
1831
1931
  memberSubst: new Map(),
1932
+ stillOptionalSubst: new Map(),
1832
1933
  narrowedUnion: new Map(),
1934
+ narrowKilled: [],
1935
+ edgeKills: [],
1833
1936
  localTypes: new Map(),
1834
1937
  builders: new Map(),
1835
1938
  retLabel: null,
@@ -2054,7 +2157,7 @@ export class Emitter {
2054
2157
  if (method === "host") {
2055
2158
  const nameArg = e.arguments[0];
2056
2159
  if (!nameArg || !ts.isStringLiteral(nameArg)) this.fail(e, "Cmd.host name (a string literal)");
2057
- if (nameArg.text.length > 255) this.fail(nameArg, "Cmd.host name over 255 bytes");
2160
+ if (utf8ByteLength(nameArg.text) > 255) this.fail(nameArg, "Cmd.host name over 255 bytes");
2058
2161
  const rest = e.arguments.slice(1);
2059
2162
  // One bytes/record argument is the v2 payload form (host_bytes on
2060
2163
  // the wire); a payload with anything alongside it has no encoding.
@@ -2083,7 +2186,7 @@ export class Emitter {
2083
2186
  if (method === "request") {
2084
2187
  const nameArg = e.arguments[0];
2085
2188
  if (!nameArg || !ts.isStringLiteral(nameArg)) this.fail(e, "Cmd.request name (a string literal)");
2086
- if (nameArg.text.length > 255) this.fail(nameArg, "Cmd.request name over 255 bytes");
2189
+ if (utf8ByteLength(nameArg.text) > 255) this.fail(nameArg, "Cmd.request name over 255 bytes");
2087
2190
  const payloadArg = e.arguments[1];
2088
2191
  if (!payloadArg) this.fail(e, "Cmd.request payload (bytes or a flat record)");
2089
2192
  if (!this.isHostPayloadArg(payloadArg, ctx)) {
@@ -2102,7 +2205,7 @@ export class Emitter {
2102
2205
  if (!keyArg || !ts.isStringLiteral(keyArg)) {
2103
2206
  this.fail(e, `\`Cmd.cancel\` takes the effect key as a string literal`, "NS1027");
2104
2207
  }
2105
- if (keyArg.text.length > 255) this.fail(keyArg, "Cmd.cancel key over 255 bytes");
2208
+ if (utf8ByteLength(keyArg.text) > 255) this.fail(keyArg, "Cmd.cancel key over 255 bytes");
2106
2209
  return `rt.cmdCancel("${escapeZigString(keyArg.text)}")`;
2107
2210
  }
2108
2211
  if (method === "readFile") {
@@ -2137,7 +2240,7 @@ export class Emitter {
2137
2240
  if (!keyArg || !ts.isStringLiteral(keyArg)) {
2138
2241
  this.fail(e, `\`Cmd.delay\` takes its key as a string literal`, "NS1027");
2139
2242
  }
2140
- if (keyArg.text.length > 255) this.fail(keyArg, "Cmd.delay key over 255 bytes");
2243
+ if (utf8ByteLength(keyArg.text) > 255) this.fail(keyArg, "Cmd.delay key over 255 bytes");
2141
2244
  const msArg = e.arguments[1];
2142
2245
  if (!msArg) this.fail(e, "Cmd.delay interval (milliseconds)");
2143
2246
  // The engine bound is 1ms..one year; a compile-time-known interval
@@ -2161,9 +2264,55 @@ export class Emitter {
2161
2264
  if (method === "audioPlay") {
2162
2265
  return this.emitAudioPlayCmd(e, ctx);
2163
2266
  }
2267
+ if (method === "imageLoad") {
2268
+ return this.emitImageLoadCmd(e, ctx);
2269
+ }
2270
+ if (method === "imageCancel") {
2271
+ const idArg = e.arguments[0];
2272
+ if (!idArg) this.fail(e, "`Cmd.imageCancel` id (the model-owned numeric ImageId)", "NS1027");
2273
+ // The same literal gate as imageLoad: an id no load could ever
2274
+ // park under has nothing to cancel — stop the build instead of
2275
+ // shipping a certain runtime no-op. Dynamic ids stay the host's
2276
+ // (an unknown id is the documented no-op).
2277
+ const idLiteral = this.numberLiteralValue(idArg);
2278
+ if (idLiteral !== null && !(Number.isSafeInteger(idLiteral) && idLiteral >= 1)) {
2279
+ this.fail(idArg, `\`Cmd.imageCancel\` id ${idLiteral} is not a positive integer ImageId below 2^53`, "NS1030");
2280
+ }
2281
+ const id = this.emitExpr(idArg, ctx, { k: "f64" }).code;
2282
+ return `rt.cmdImageCancel(${id})`;
2283
+ }
2284
+ if (method === "imageUnregister") {
2285
+ const idArg = e.arguments[0];
2286
+ if (!idArg) this.fail(e, "`Cmd.imageUnregister` id (the model-owned numeric ImageId)", "NS1027");
2287
+ // The same literal gate as imageLoad/imageCancel: an id no load
2288
+ // could ever register under has nothing to unregister — stop the
2289
+ // build instead of shipping a certain runtime no-op. Dynamic ids
2290
+ // stay the host's (an unregistered id is the documented no-op).
2291
+ const idLiteral = this.numberLiteralValue(idArg);
2292
+ if (idLiteral !== null && !(Number.isSafeInteger(idLiteral) && idLiteral >= 1)) {
2293
+ this.fail(idArg, `\`Cmd.imageUnregister\` id ${idLiteral} is not a positive integer ImageId below 2^53`, "NS1030");
2294
+ }
2295
+ const id = this.emitExpr(idArg, ctx, { k: "f64" }).code;
2296
+ return `rt.cmdImageUnregister(${id})`;
2297
+ }
2164
2298
  if (method in AUDIO_VERBS) {
2165
2299
  return this.emitAudioCtlCmd(e, method, ctx);
2166
2300
  }
2301
+ if (method === "showWindow") {
2302
+ // Window labels are declarations (app.zon / the scene), so the
2303
+ // verb takes the label as a string literal — the same discipline
2304
+ // effect keys ride (NS1027).
2305
+ const labelArg = e.arguments[0];
2306
+ if (!labelArg || !ts.isStringLiteral(labelArg)) {
2307
+ this.fail(e, `\`Cmd.showWindow\` takes the declared window label as a string literal`, "NS1027");
2308
+ }
2309
+ if (utf8ByteLength(labelArg.text) > 255) this.fail(labelArg, "Cmd.showWindow label over 255 bytes");
2310
+ return `rt.cmdWindowShow("${escapeZigString(labelArg.text)}")`;
2311
+ }
2312
+ if (method === "quitApp") {
2313
+ if (e.arguments.length !== 0) this.fail(e, "Cmd.quitApp takes no arguments");
2314
+ return "rt.cmdQuitApp()";
2315
+ }
2167
2316
  if (method === "batch") {
2168
2317
  const arr = e.arguments[0];
2169
2318
  if (!arr || !ts.isArrayLiteralExpression(arr)) this.fail(e, "Cmd.batch argument (an array literal in v1)");
@@ -2173,7 +2322,7 @@ export class Emitter {
2173
2322
  }
2174
2323
  this.fail(
2175
2324
  e,
2176
- `Cmd.${method} (the v2 command set is none, persist, now, host, request, cancel, readFile, writeFile, fetch, clipboardWrite, clipboardRead, delay, spawn, audioPlay, audioPause, audioResume, audioStop, audioSeek, audioSetVolume, batch)`,
2325
+ `Cmd.${method} (the v3 command set is none, persist, now, host, request, cancel, readFile, writeFile, fetch, clipboardWrite, clipboardRead, delay, spawn, audioPlay, audioPause, audioResume, audioStop, audioSeek, audioSetVolume, showWindow, quitApp, imageLoad, imageCancel, imageUnregister, batch)`,
2177
2326
  );
2178
2327
  }
2179
2328
  this.fail(expr, "command expression (Cmd values are built inline from the Cmd.* factories)");
@@ -2215,7 +2364,7 @@ export class Emitter {
2215
2364
  );
2216
2365
  }
2217
2366
  if (p.name.text === "key") {
2218
- if (v.text.length > 255) this.fail(v, "Cmd.request key over 255 bytes");
2367
+ if (utf8ByteLength(v.text) > 255) this.fail(v, "Cmd.request key over 255 bytes");
2219
2368
  key = v.text;
2220
2369
  } else if (p.name.text === "ok") ok = v;
2221
2370
  else if (p.name.text === "err") err = v;
@@ -2347,7 +2496,7 @@ export class Emitter {
2347
2496
  );
2348
2497
  }
2349
2498
  if (name === "key") {
2350
- if (v.text.length > 255) this.fail(v, "Cmd.spawn key over 255 bytes");
2499
+ if (utf8ByteLength(v.text) > 255) this.fail(v, "Cmd.spawn key over 255 bytes");
2351
2500
  key = v.text;
2352
2501
  } else if (name === "line") line = v;
2353
2502
  else if (name === "exit") exit = v;
@@ -2382,7 +2531,7 @@ export class Emitter {
2382
2531
  if (!keyArg || !ts.isStringLiteral(keyArg)) {
2383
2532
  this.fail(e, `\`Cmd.audioPlay\` takes its key as a string literal`, "NS1027");
2384
2533
  }
2385
- if (keyArg.text.length > 255) this.fail(keyArg, "Cmd.audioPlay key over 255 bytes");
2534
+ if (utf8ByteLength(keyArg.text) > 255) this.fail(keyArg, "Cmd.audioPlay key over 255 bytes");
2386
2535
 
2387
2536
  let source = e.arguments[1];
2388
2537
  while (source && (ts.isParenthesizedExpression(source) || ts.isAsExpression(source) || ts.isSatisfiesExpression(source))) source = source.expression;
@@ -2450,6 +2599,144 @@ export class Emitter {
2450
2599
  return `rt.cmdAudioPlay("${escapeZigString(keyArg.text)}", ${tag}, ${audio_path}, ${url}, ${cache_path}, ${expected})`;
2451
2600
  }
2452
2601
 
2602
+ /// `Cmd.imageLoad(id, source, route)`: the app's numeric ImageId (any
2603
+ /// number expression — ids are model data), an inline
2604
+ /// `{ path?, url?, cachePath?, expectedBytes? }` source (at least one of
2605
+ /// path/url), and the `{ event }` routing whose arm carries the five
2606
+ /// SDK-fixed image result fields.
2607
+ private emitImageLoadCmd(e: ts.CallExpression, ctx: Ctx): string {
2608
+ const idArg = e.arguments[0];
2609
+ if (!idArg) this.fail(e, "`Cmd.imageLoad` id (the model-owned numeric ImageId)", "NS1027");
2610
+ // A compile-time-known id the engine is certain to refuse stops the
2611
+ // build; dynamic ids stay the host's to validate through the
2612
+ // "rejected" result state. The bound is strictly BELOW 2^53
2613
+ // (Number.isSafeInteger for a positive value): 2^53 itself is the
2614
+ // first f64 that aliases a neighbor (2^53 + 1), so the host rejects
2615
+ // it too rather than guess which integer the app meant.
2616
+ const idLiteral = this.numberLiteralValue(idArg);
2617
+ if (idLiteral !== null && !(Number.isSafeInteger(idLiteral) && idLiteral >= 1)) {
2618
+ this.fail(idArg, `\`Cmd.imageLoad\` id ${idLiteral} is not a positive integer ImageId below 2^53`, "NS1030");
2619
+ }
2620
+ const id = this.emitExpr(idArg, ctx, { k: "f64" }).code;
2621
+
2622
+ let source = e.arguments[1];
2623
+ while (source && (ts.isParenthesizedExpression(source) || ts.isAsExpression(source) || ts.isSatisfiesExpression(source))) source = source.expression;
2624
+ if (!source || !ts.isObjectLiteralExpression(source)) {
2625
+ this.fail(
2626
+ e.arguments[1] ?? e,
2627
+ `\`Cmd.imageLoad\` takes an inline \`{ path?, url?, cachePath?, expectedBytes? }\` source object`,
2628
+ "NS1029",
2629
+ );
2630
+ }
2631
+ let image_path = '""';
2632
+ let url = '""';
2633
+ let cache_path = '""';
2634
+ let expected = "0";
2635
+ let has_source = false;
2636
+ for (const p of source.properties) {
2637
+ if (!ts.isPropertyAssignment(p) || !ts.isIdentifier(p.name)) {
2638
+ this.fail(p, `\`Cmd.imageLoad\` source member \`${p.getText()}\` is not a plain property`, "NS1029");
2639
+ }
2640
+ const name = p.name.text;
2641
+ if (name === "path") {
2642
+ image_path = this.effectBytesArg(e, p.initializer, "Cmd.imageLoad path", MAX_IMAGE_PATH_BYTES, ctx);
2643
+ has_source = true;
2644
+ } else if (name === "url") {
2645
+ url = this.effectBytesArg(e, p.initializer, "Cmd.imageLoad url", MAX_URL_BYTES, ctx);
2646
+ has_source = true;
2647
+ } else if (name === "cachePath") {
2648
+ cache_path = this.effectBytesArg(e, p.initializer, "Cmd.imageLoad cachePath", MAX_IMAGE_PATH_BYTES, ctx);
2649
+ } else if (name === "expectedBytes") {
2650
+ // A byte count is a whole number: file sizes have no fractional
2651
+ // bytes, and a fractional value would truncate on the host into
2652
+ // a size the app never declared — cache verification against
2653
+ // the wrong size re-downloads on every launch. The bound is the
2654
+ // id gate's (Number.isSafeInteger): past 2^53 the f64 wire
2655
+ // cannot carry the count exactly. Dynamic values stay the
2656
+ // host's, which maps unrepresentable counts to "unknown size".
2657
+ const literal = this.numberLiteralValue(p.initializer);
2658
+ if (literal !== null && !(Number.isSafeInteger(literal) && literal >= 0)) {
2659
+ this.fail(p.initializer, `\`Cmd.imageLoad\` expectedBytes ${literal} is not a whole-number byte count below 2^53`, "NS1030");
2660
+ }
2661
+ expected = this.emitExpr(p.initializer, ctx, { k: "f64" }).code;
2662
+ } else {
2663
+ this.fail(p, `\`Cmd.imageLoad\` source member \`${name}\``, "NS1029");
2664
+ }
2665
+ }
2666
+ if (!has_source) {
2667
+ this.fail(source, `\`Cmd.imageLoad\` source without a \`path\` or a \`url\` — nothing could load`, "NS1029");
2668
+ }
2669
+
2670
+ let route = e.arguments[2];
2671
+ while (route && (ts.isParenthesizedExpression(route) || ts.isAsExpression(route) || ts.isSatisfiesExpression(route))) route = route.expression;
2672
+ if (!route || !ts.isObjectLiteralExpression(route)) {
2673
+ this.fail(e.arguments[2] ?? e, `\`Cmd.imageLoad\` routing is an inline \`{ event }\` object`, "NS1027");
2674
+ }
2675
+ let event: ts.StringLiteral | null = null;
2676
+ for (const p of route.properties) {
2677
+ if (!ts.isPropertyAssignment(p) || !ts.isIdentifier(p.name)) {
2678
+ this.fail(p, `\`Cmd.imageLoad\` routing member \`${p.getText()}\` is not a plain property`, "NS1027");
2679
+ }
2680
+ let v: ts.Expression = p.initializer;
2681
+ while (ts.isParenthesizedExpression(v) || ts.isAsExpression(v) || ts.isSatisfiesExpression(v)) v = v.expression;
2682
+ if (p.name.text !== "event") {
2683
+ this.fail(p, `\`Cmd.imageLoad\` routing member \`${p.name.text}\``, "NS1027");
2684
+ }
2685
+ if (!ts.isStringLiteral(v)) {
2686
+ this.fail(p.initializer, `\`Cmd.imageLoad\` event arm is not a string literal`, "NS1027");
2687
+ }
2688
+ event = v;
2689
+ }
2690
+ if (!event) this.fail(route, `\`Cmd.imageLoad\` routing without an \`event\` arm`, "NS1027");
2691
+ const tag = this.imageEventArmTag(event, ctx);
2692
+ return `rt.cmdImageLoad(${id}, ${tag}, ${image_path}, ${url}, ${cache_path}, ${expected})`;
2693
+ }
2694
+
2695
+ /// Resolve the image result arm: exactly the five SDK-fixed fields,
2696
+ /// matched by NAME — id (a number: the requested ImageId echoed
2697
+ /// verbatim), state (a named literal-union alias carrying exactly the
2698
+ /// fifteen image states, any order), width/height/status (numbers).
2699
+ private imageEventArmTag(arg: ts.StringLiteral, ctx: Ctx): string {
2700
+ const unionName = ctx.cmdReturn!.msgUnion;
2701
+ const info = this.table.unions.get(unionName);
2702
+ if (!info) this.fail(arg, `unknown union ${unionName}`);
2703
+ const arm = info.arms.find((a) => a.tag === arg.text);
2704
+ if (!arm) {
2705
+ this.fail(arg, `routing target \`${arg.text}\` is not an arm of ${unionName}`, "NS1027");
2706
+ }
2707
+ const shape =
2708
+ "the five image result fields — id: number (the echoed ImageId), state (a named alias of exactly " +
2709
+ IMAGE_STATES.map((s) => `"${s}"`).join(" | ") +
2710
+ "), width: number, height: number, status: number";
2711
+ const fieldsByName = new Map(arm.fields.map((f) => [f.tsName, f]));
2712
+ const isNumber = (k: string): boolean => k === "number" || k === "i64" || k === "f64";
2713
+ const id = fieldsByName.get("id");
2714
+ const state = fieldsByName.get("state");
2715
+ const width = fieldsByName.get("width");
2716
+ const height = fieldsByName.get("height");
2717
+ const status = fieldsByName.get("status");
2718
+ const stateOk =
2719
+ state !== undefined &&
2720
+ state.type.k === "enum" &&
2721
+ state.type.members.length === IMAGE_STATES.length &&
2722
+ IMAGE_STATES.every((s) => state.type.k === "enum" && state.type.members.includes(s));
2723
+ const matches =
2724
+ arm.fields.length === 5 &&
2725
+ stateOk &&
2726
+ id !== undefined &&
2727
+ isNumber(id.type.k) &&
2728
+ width !== undefined &&
2729
+ isNumber(width.type.k) &&
2730
+ height !== undefined &&
2731
+ isNumber(height.type.k) &&
2732
+ status !== undefined &&
2733
+ isNumber(status.type.k);
2734
+ if (!matches) {
2735
+ this.fail(arg, `routing target \`${arg.text}\` does not carry ${shape}`, "NS1027");
2736
+ }
2737
+ return `@intFromEnum(std.meta.Tag(${unionName}).${zigId(arg.text)})`;
2738
+ }
2739
+
2453
2740
  /// Resolve the audio event arm: exactly the six SDK-fixed fields, matched
2454
2741
  /// by NAME — state (a named literal-union alias carrying exactly the six
2455
2742
  /// audio states, any order), positionMs/durationMs (numbers), playing/
@@ -2506,7 +2793,7 @@ export class Emitter {
2506
2793
  if (!keyArg || !ts.isStringLiteral(keyArg)) {
2507
2794
  this.fail(e, `\`Cmd.${method}\` takes its key as a string literal`, "NS1027");
2508
2795
  }
2509
- if (keyArg.text.length > 255) this.fail(keyArg, `Cmd.${method} key over 255 bytes`);
2796
+ if (utf8ByteLength(keyArg.text) > 255) this.fail(keyArg, `Cmd.${method} key over 255 bytes`);
2510
2797
  let value = "0";
2511
2798
  if (method === "audioSeek") {
2512
2799
  const msArg = e.arguments[1];
@@ -2575,7 +2862,10 @@ export class Emitter {
2575
2862
  }
2576
2863
 
2577
2864
  /// The byte length of a compile-time `asciiBytes("...")` literal; null
2578
- /// for everything dynamic.
2865
+ /// for everything dynamic. Counted as UTF-8 bytes: for the ASCII text
2866
+ /// the intrinsic is contracted to carry the two counts agree, and for
2867
+ /// text that violates the contract the emitted Zig literal holds the
2868
+ /// UTF-8 bytes, so this is the length the engine bound actually sees.
2579
2869
  private literalBytesLength(arg: ts.Expression): number | null {
2580
2870
  let e = arg;
2581
2871
  while (ts.isParenthesizedExpression(e) || ts.isAsExpression(e) || ts.isSatisfiesExpression(e)) e = e.expression;
@@ -2583,7 +2873,7 @@ export class Emitter {
2583
2873
  const decl = this.tast.declarationOf(e.expression);
2584
2874
  if (!decl || !this.isSdkIntrinsic(decl, "asciiBytes")) return null;
2585
2875
  const inner = e.arguments[0];
2586
- return inner && ts.isStringLiteral(inner) ? inner.text.length : null;
2876
+ return inner && ts.isStringLiteral(inner) ? utf8ByteLength(inner.text) : null;
2587
2877
  }
2588
2878
 
2589
2879
  /// The numeric value of a compile-time number literal (unary minus
@@ -2854,7 +3144,7 @@ export class Emitter {
2854
3144
  if (!keyArg || !ts.isStringLiteral(keyArg)) {
2855
3145
  this.fail(e, `\`Sub.timer\` takes its key as a string literal`, "NS1027");
2856
3146
  }
2857
- if (keyArg.text.length > 255) this.fail(keyArg, "Sub.timer key over 255 bytes");
3147
+ if (utf8ByteLength(keyArg.text) > 255) this.fail(keyArg, "Sub.timer key over 255 bytes");
2858
3148
  const everyArg = e.arguments[1];
2859
3149
  if (!everyArg) this.fail(e, "Sub.timer interval (milliseconds)");
2860
3150
  const every = this.emitExpr(everyArg, ctx, { k: "f64" }).code;
@@ -2903,6 +3193,115 @@ export class Emitter {
2903
3193
  return this.table.zigTypeRef(t);
2904
3194
  }
2905
3195
 
3196
+ /// Per-declaration ids for narrowing keys (see narrowKey). A WeakMap
3197
+ /// identity id rather than the declaration's source position: positions
3198
+ /// can collide across files, and imported consts narrow too.
3199
+ private readonly narrowKeyIds = new WeakMap<ts.Declaration, number>();
3200
+ private narrowKeyNextId = 1;
3201
+
3202
+ /// Explicit node-scoped keys: a lowering that re-emits one specific
3203
+ /// expression NODE under a capture (the optional-call receiver) can
3204
+ /// register a key for it even when the expression has no canonical
3205
+ /// narrowing key. The key is unique to the node, so it can never match
3206
+ /// a different occurrence — it carries a single node's rewrite, not a
3207
+ /// narrowing fact.
3208
+ private readonly nodeNarrowKeys = new WeakMap<ts.Node, string>();
3209
+
3210
+ /// The key an expression narrows/substitutes under: normalized source
3211
+ /// text with the base identifier DECLARATION-qualified (`q#3`, member
3212
+ /// chains `q#3.v`). Emission FLATTENS plain lexical blocks and callback
3213
+ /// bodies share the enclosing maps, so raw text would let two
3214
+ /// same-named declarations collide — a block-local `const q` shadow
3215
+ /// leaves its entries live for the OUTER q after the block, and an
3216
+ /// outer capture rewrites a callback parameter's reads. Symbol identity
3217
+ /// makes the collision impossible; the maps' values and mechanics are
3218
+ /// unchanged. Wrapper spellings collide by design: parentheses,
3219
+ /// non-null assertions, `as`, and `satisfies` all erase at emission
3220
+ /// (`(q)`, `q!`, and `q as Quote` are the tested `q`), so every
3221
+ /// consumer comparing or looking up keys sees through them — an arm
3222
+ /// spelled `q!` matches its guard's `q`, and a narrow installed for `q`
3223
+ /// rewrites the `q!` read. A base the checker cannot resolve keys by
3224
+ /// plain text — same behavior as before, and such bases are never
3225
+ /// locals.
3226
+ ///
3227
+ /// Element accesses qualify recursively, like property chains — the
3228
+ /// grammar is `base[index]` where the base is this same key and the
3229
+ /// index is a canonical argument form: a literal index canonicalizes by
3230
+ /// VALUE (`xs#3[0]`, so `xs[0]`, `xs[0x0]`, and `xs["0"]` are one key,
3231
+ /// exactly the one element JS reads), and an identifier index qualifies
3232
+ /// by the index's own declaration (`xs#3[i#7]` — a shadowed `i` is a
3233
+ /// different element). Anything non-canonical — a computed index, a
3234
+ /// call — has NO narrowing key: two spellings of `xs[f()]` need not
3235
+ /// read the same element, so nothing may narrow, substitute, or match
3236
+ /// through one. Returning null here is the decline answer every
3237
+ /// consumer honors: no substitution installs, capture gates see no
3238
+ /// read, and the expression's reads stay live optionals. Raw source
3239
+ /// text is never a key — emission flattens lexical blocks, so text
3240
+ /// would let a shadowed declaration's narrow leak onto the outer name.
3241
+ private narrowKey(expr: ts.Node): string | null {
3242
+ const override = this.nodeNarrowKeys.get(expr);
3243
+ if (override !== undefined) return override;
3244
+ let e: ts.Node = expr;
3245
+ while (
3246
+ ts.isParenthesizedExpression(e) ||
3247
+ ts.isNonNullExpression(e) ||
3248
+ ts.isAsExpression(e) ||
3249
+ ts.isSatisfiesExpression(e)
3250
+ ) {
3251
+ e = e.expression;
3252
+ }
3253
+ if (ts.isPropertyAccessExpression(e)) {
3254
+ const base = this.narrowKey(e.expression);
3255
+ return base === null ? null : `${base}${e.questionDotToken ? "?." : "."}${e.name.text}`;
3256
+ }
3257
+ if (ts.isElementAccessExpression(e)) {
3258
+ const base = this.narrowKey(e.expression);
3259
+ if (base === null) return null;
3260
+ const index = this.canonicalIndexKey(e.argumentExpression);
3261
+ if (index === null) return null;
3262
+ return `${base}${e.questionDotToken ? "?." : ""}[${index}]`;
3263
+ }
3264
+ if (ts.isIdentifier(e)) {
3265
+ const decl = this.tast.declarationOf(e);
3266
+ if (decl) {
3267
+ let id = this.narrowKeyIds.get(decl);
3268
+ if (id === undefined) {
3269
+ id = this.narrowKeyNextId++;
3270
+ this.narrowKeyIds.set(decl, id);
3271
+ }
3272
+ return `${e.text}#${id}`;
3273
+ }
3274
+ return e.text;
3275
+ }
3276
+ // `this` is one object per member body (arrows keep it), never
3277
+ // shadowable — the keyword is its own key.
3278
+ if (e.kind === ts.SyntaxKind.ThisKeyword) return "this";
3279
+ return null;
3280
+ }
3281
+
3282
+ /// The canonical form of an element-access index, or null when the
3283
+ /// index is not a stable reference to one element (see narrowKey).
3284
+ /// Literals canonicalize by the VALUE JS coerces to a property key —
3285
+ /// a numeric string index is the numeric index (`xs["0"]` is `xs[0]`).
3286
+ private canonicalIndexKey(arg: ts.Expression): string | null {
3287
+ let a: ts.Expression = arg;
3288
+ while (
3289
+ ts.isParenthesizedExpression(a) ||
3290
+ ts.isNonNullExpression(a) ||
3291
+ ts.isAsExpression(a) ||
3292
+ ts.isSatisfiesExpression(a)
3293
+ ) {
3294
+ a = a.expression;
3295
+ }
3296
+ if (ts.isNumericLiteral(a)) return String(Number(a.text));
3297
+ if (ts.isStringLiteral(a) || ts.isNoSubstitutionTemplateLiteral(a)) {
3298
+ const n = Number(a.text);
3299
+ return String(n) === a.text ? String(n) : JSON.stringify(a.text);
3300
+ }
3301
+ if (ts.isIdentifier(a)) return this.narrowKey(a);
3302
+ return null;
3303
+ }
3304
+
2906
3305
  private identifierUsed(body: ts.Node, decl: ts.Node): boolean {
2907
3306
  let used = false;
2908
3307
  const visit = (n: ts.Node): void => {
@@ -2964,7 +3363,326 @@ export class Emitter {
2964
3363
  return this.uniqueName(ctx, hint);
2965
3364
  }
2966
3365
 
2967
- private emitBlockStatements(stmts: readonly ts.Statement[], ctx: Ctx): void {
3366
+ /// Open an invalidation frame: every scope that snapshots/restores the
3367
+ /// narrowing maps brackets its emission with this pair, so assignment
3368
+ /// kills recorded during the scope survive the restore (see Ctx.narrowKilled).
3369
+ private pushNarrowKillFrame(ctx: Ctx): void {
3370
+ ctx.narrowKilled.push(new Set());
3371
+ }
3372
+
3373
+ /// Close the innermost invalidation frame: re-apply its recorded kills to
3374
+ /// the just-restored narrowing maps and merge them one frame outward (an
3375
+ /// inner branch's kill must reach every enclosing exit it can fall
3376
+ /// through to). A kill on ANY fall-through path inside the scope deletes
3377
+ /// the narrow at the merge point, so a path that kept the value non-null
3378
+ /// pays a re-check — never wrong code. Only memberSubst is touched,
3379
+ /// mirroring the assignment-invalidation path (a stillOptionalSubst entry
3380
+ /// is inert once its memberSubst entry is gone, and narrowedUnion is not
3381
+ /// what `.?` substitutions live in).
3382
+ ///
3383
+ /// `drop` discards the frame's kills instead: the caller has proven the
3384
+ /// scope always leaves the emitted function, so no path carrying those
3385
+ /// kills reaches the merge point — merging them would delete narrowings
3386
+ /// tsc keeps on the surviving flow, and a read there relies on the
3387
+ /// substitution's unwrap spelling (losing it emits a field access on an
3388
+ /// optional, not a re-check).
3389
+ ///
3390
+ /// A destination array routes the kills along the scope's non-local
3391
+ /// edges instead: the scope's only in-function routes are caught throws
3392
+ /// and/or escaping break/continue/lowered-return edges, so no path
3393
+ /// carrying the kills reaches THIS merge point either — but each edge
3394
+ /// resumes somewhere in the function, and the kills must be live there.
3395
+ /// Kills travel the same edges control does: they wait in the
3396
+ /// destination sets (the enclosing try's pendingCatchKills, the target
3397
+ /// constructs' edgeKills stages) and the owning emitters apply them
3398
+ /// where the edges land — never mid-flight, where tsc keeps the
3399
+ /// surviving paths' narrows.
3400
+ private popNarrowKillFrame(ctx: Ctx, routing: KillRouting = "merge"): Set<string> {
3401
+ const killed = ctx.narrowKilled.pop() ?? new Set<string>();
3402
+ if (routing === "drop") return killed;
3403
+ if (routing !== "merge") {
3404
+ for (const dest of routing) for (const key of killed) dest.add(key);
3405
+ return killed;
3406
+ }
3407
+ for (const key of killed) ctx.memberSubst.delete(key);
3408
+ const parent = ctx.narrowKilled[ctx.narrowKilled.length - 1];
3409
+ if (parent) for (const key of killed) parent.add(key);
3410
+ return killed;
3411
+ }
3412
+
3413
+ /// Bracket `emit` in one narrowing flow scope: on exit, restore the three
3414
+ /// narrowing maps to their entry snapshot (containment), then re-apply and
3415
+ /// merge — or drop, or route to the enclosing try's pending set — the
3416
+ /// kills recorded inside (see popNarrowKillFrame).
3417
+ ///
3418
+ /// `joinInto` defers merge-class kills for a JOIN instead of applying
3419
+ /// them here: a multi-alternative construct (if/else arms, an else-if
3420
+ /// chain, switch clauses) must emit every alternative from the shared
3421
+ /// ENTRY state — tsc types the arms as alternatives, not a sequence, so
3422
+ /// one arm's kill applied mid-construct would strip a sibling of a
3423
+ /// narrowing tsc keeps there. The caller collects each arm's kills and
3424
+ /// applies the union once via applyJoinedNarrowKills, after the last
3425
+ /// alternative. Only merge-class kills defer: an always-leaving arm
3426
+ /// still drops its kills, and an arm whose only in-function routes are
3427
+ /// non-local edges still routes them to those edges' destination sets —
3428
+ /// those edges never reach a sibling.
3429
+ private withNarrowScope<T>(
3430
+ ctx: Ctx,
3431
+ mode: KillRouting,
3432
+ emit: () => T,
3433
+ joinInto?: Set<string>,
3434
+ ): T {
3435
+ const savedSubst = new Map(ctx.memberSubst);
3436
+ const savedStillOptional = new Map(ctx.stillOptionalSubst);
3437
+ const savedNarrowed = new Map(ctx.narrowedUnion);
3438
+ this.pushNarrowKillFrame(ctx);
3439
+ try {
3440
+ return emit();
3441
+ } finally {
3442
+ ctx.memberSubst.clear();
3443
+ for (const [k, v] of savedSubst) ctx.memberSubst.set(k, v);
3444
+ ctx.stillOptionalSubst.clear();
3445
+ for (const [k, v] of savedStillOptional) ctx.stillOptionalSubst.set(k, v);
3446
+ ctx.narrowedUnion.clear();
3447
+ for (const [k, v] of savedNarrowed) ctx.narrowedUnion.set(k, v);
3448
+ if (mode === "merge" && joinInto) {
3449
+ for (const key of this.popNarrowKillFrame(ctx, "drop")) joinInto.add(key);
3450
+ } else {
3451
+ this.popNarrowKillFrame(ctx, mode);
3452
+ }
3453
+ }
3454
+ }
3455
+
3456
+ /// The JOIN of a multi-alternative construct: apply the union of the
3457
+ /// alternatives' merge-class kills to the surviving flow, once, after
3458
+ /// every alternative has emitted from the shared entry state (see
3459
+ /// withNarrowScope's `joinInto`). Same application as a plain merge —
3460
+ /// delete the narrow, propagate the kill one frame outward so enclosing
3461
+ /// exits keep it dead past their restores.
3462
+ private applyJoinedNarrowKills(ctx: Ctx, join: ReadonlySet<string>): void {
3463
+ for (const key of join) {
3464
+ ctx.memberSubst.delete(key);
3465
+ ctx.narrowKilled[ctx.narrowKilled.length - 1]?.add(key);
3466
+ }
3467
+ }
3468
+
3469
+ /// Bracket a construct's emission with an edge-kill stage (Ctx.edgeKills):
3470
+ /// scopes inside that exit only along edges bound to this construct stage
3471
+ /// their kills here, and the returned set is what the caller applies at
3472
+ /// the point those edges land — applyJoinedNarrowKills after the closing
3473
+ /// brace for loops, labeled blocks, and callback value blocks; folded
3474
+ /// through the clause join for switches (the two mechanisms share one
3475
+ /// application point, so a kill is neither applied twice mid-construct
3476
+ /// nor dropped between them). The application records into the
3477
+ /// then-innermost kill frame, so a staged kill keeps propagating outward
3478
+ /// — through enclosing joins and post-narrow subtractions — exactly like
3479
+ /// a merge-class kill applied at the same spot.
3480
+ private stagedEdgeKills(
3481
+ ctx: Ctx,
3482
+ kind: EdgeKillStage["kind"],
3483
+ label: string | null,
3484
+ emit: () => void,
3485
+ ): Set<string> {
3486
+ const stage: EdgeKillStage = { kind, label, kills: new Set() };
3487
+ ctx.edgeKills.push(stage);
3488
+ try {
3489
+ emit();
3490
+ } finally {
3491
+ ctx.edgeKills.pop();
3492
+ }
3493
+ return stage.kills;
3494
+ }
3495
+
3496
+ private emitBlockStatements(
3497
+ stmts: readonly ts.Statement[],
3498
+ ctx: Ctx,
3499
+ joinInto?: Set<string>,
3500
+ entryKills?: ReadonlySet<string>,
3501
+ trailing?: () => void,
3502
+ ): void {
3503
+ // Narrowing is flow-scoped the way tsc scopes it: an early-exit guard
3504
+ // narrows the statements after it in ITS list, and whatever those
3505
+ // statements nest — never code beyond the list. The narrowing maps ride
3506
+ // the shared ctx, so the scope's entry/exit snapshot is what bounds
3507
+ // them: a `break`/`continue`/`return` guard inside a loop body or a
3508
+ // branch cannot leak its captures into code after the construct (where
3509
+ // the capture is out of scope in Zig and the narrowing wrong in TS).
3510
+ //
3511
+ // Invalidation survives the restore — an assignment inside the block
3512
+ // that killed a narrowing (assigned a possibly-null value) must stay
3513
+ // dead past the merge — UNLESS every route out of the list leaves the
3514
+ // emitted function (allRoutesLeaveFunction): then no path carrying the
3515
+ // kills reaches the merge, tsc keeps the narrow on the surviving flow,
3516
+ // and reads there depend on it.
3517
+ const env = {
3518
+ returnLeaves: ctx.retLabel === null,
3519
+ throwResumes: ctx.catchResumes === true,
3520
+ };
3521
+ const leavesFn = this.allRoutesLeaveFunction(stmts, env);
3522
+ // Edge-kills channel: when the list's only in-function routes are
3523
+ // non-local edges — throws the enclosing catch hands back, escaping
3524
+ // break/continue edges, lowered callback returns — no path carrying
3525
+ // the kills falls through into the statements after this list, so
3526
+ // merging them here would poison flow tsc keeps narrowed (the killing
3527
+ // paths cannot reach it). Kills travel the same edges control does:
3528
+ // each class stages at its destination — the try's pending set for
3529
+ // caught throws, the target construct's stage for break/continue, the
3530
+ // callback stage for lowered returns — and the owning emitter applies
3531
+ // it where the edge lands. Re-asking the route question with every
3532
+ // edge class treated as leaving isolates exactly this case: any true
3533
+ // fall-through still forces the plain merge (which is a conservative
3534
+ // superset — its kills persist into all downstream states, the edge
3535
+ // destinations included).
3536
+ // `entryKills` are kills that arrived WITH control (a catch entered on
3537
+ // throw edges that carried them): they widen the list's entry state —
3538
+ // its reads see them — and then ride this frame's routing out, exactly
3539
+ // like a kill the first statement made. Routing is what makes them
3540
+ // land where flow says: a fall-through carries them to the code after
3541
+ // the construct, an escaping break/continue stages them at that edge's
3542
+ // destination, and a list whose every route leaves the function drops
3543
+ // them (no surviving path carries them anywhere).
3544
+ // `trailing` is emission that tsc types under the list's END state — a
3545
+ // do-while's trailing exit test evaluates after the body, so a terminal
3546
+ // guard in the body narrows it. It runs inside this same scope: a scope
3547
+ // closed between the list and the test would restore the maps before
3548
+ // the read they guard (the callback trailing-return fix, applied to the
3549
+ // loop lowering).
3550
+ this.withNarrowScope(
3551
+ ctx,
3552
+ leavesFn ? "drop" : this.edgeKillRouting(stmts, env, ctx),
3553
+ () => {
3554
+ if (entryKills) {
3555
+ for (const key of entryKills) {
3556
+ ctx.memberSubst.delete(key);
3557
+ ctx.narrowKilled[ctx.narrowKilled.length - 1]?.add(key);
3558
+ }
3559
+ }
3560
+ this.emitStatementList(stmts, ctx);
3561
+ trailing?.();
3562
+ },
3563
+ joinInto,
3564
+ );
3565
+ }
3566
+
3567
+ /// The routing for a list that does NOT always leave the function: the
3568
+ /// non-local-edges-only route form when it applies, else "merge". A
3569
+ /// destination that fails to resolve (a caught throw without a pending
3570
+ /// set, an edge whose target construct has no stage) falls back to the
3571
+ /// plain merge — over-merging costs a re-check, never wrong code.
3572
+ private edgeKillRouting(
3573
+ stmts: readonly ts.Statement[],
3574
+ env: { returnLeaves: boolean; throwResumes: boolean },
3575
+ ctx: Ctx,
3576
+ ): KillRouting {
3577
+ if (!this.allRoutesLeaveFunction(stmts, { ...env, edgesLeave: true, throwResumes: false })) {
3578
+ return "merge";
3579
+ }
3580
+ const targets: Set<string>[] = [];
3581
+ if (env.throwResumes && !this.allRoutesLeaveFunction(stmts, { ...env, edgesLeave: true })) {
3582
+ // With edges leaving but caught throws resuming, any remaining
3583
+ // resuming route is a caught throw: this list exits along the
3584
+ // throw edge into the enclosing catch.
3585
+ if (ctx.pendingCatchKills == null) return "merge";
3586
+ targets.push(ctx.pendingCatchKills);
3587
+ }
3588
+ const edges = this.escapingEdgesOf(stmts, env.returnLeaves);
3589
+ const innermost = (pred: (s: EdgeKillStage) => boolean): EdgeKillStage | null => {
3590
+ for (let i = ctx.edgeKills.length - 1; i >= 0; i--) {
3591
+ if (pred(ctx.edgeKills[i])) return ctx.edgeKills[i];
3592
+ }
3593
+ return null;
3594
+ };
3595
+ for (const label of edges.breaks) {
3596
+ const stage = innermost((s) =>
3597
+ label === null ? s.kind === "loop" || s.kind === "switch" : s.label === label,
3598
+ );
3599
+ if (stage === null) return "merge";
3600
+ targets.push(stage.kills);
3601
+ }
3602
+ for (const label of edges.continues) {
3603
+ const stage = innermost((s) => s.kind === "loop" && (label === null || s.label === label));
3604
+ if (stage === null) return "merge";
3605
+ targets.push(stage.kills);
3606
+ }
3607
+ if (edges.callbackReturn) {
3608
+ const stage = innermost((s) => s.kind === "callback");
3609
+ if (stage === null) return "merge";
3610
+ targets.push(stage.kills);
3611
+ }
3612
+ // No resolvable destination at all would leave resuming routes with
3613
+ // nowhere to carry the kills — that only happens when the two route
3614
+ // analyses disagree, so keep the conservative merge.
3615
+ return targets.length > 0 ? targets : "merge";
3616
+ }
3617
+
3618
+ /// The escaping non-local edges out of a statement list: the labels (null
3619
+ /// = unlabeled) of break/continue statements whose target sits at or
3620
+ /// outside the list, and whether any lowered `return` exits it (lifted
3621
+ /// callbacks: returnLeaves is false). Binding mirrors
3622
+ /// allRoutesLeaveFunction's target tracking — a loop binds unlabeled
3623
+ /// break and continue for its subtree, a switch binds unlabeled break, a
3624
+ /// labeled statement binds its label — and callback bodies are theirs
3625
+ /// alone (tsc rejects a break/continue crossing a function boundary;
3626
+ /// their returns are analyzed at their own emission).
3627
+ private escapingEdgesOf(
3628
+ stmts: readonly ts.Statement[],
3629
+ returnLeaves: boolean,
3630
+ ): { breaks: Set<string | null>; continues: Set<string | null>; callbackReturn: boolean } {
3631
+ const breaks = new Set<string | null>();
3632
+ const continues = new Set<string | null>();
3633
+ let callbackReturn = false;
3634
+ interface Bound {
3635
+ readonly labels: ReadonlySet<string>;
3636
+ readonly breakBound: boolean;
3637
+ readonly continueBound: boolean;
3638
+ }
3639
+ const visit = (n: ts.Node, st: Bound): void => {
3640
+ if (ts.isBreakStatement(n)) {
3641
+ if (n.label ? !st.labels.has(n.label.text) : !st.breakBound) breaks.add(n.label?.text ?? null);
3642
+ return;
3643
+ }
3644
+ if (ts.isContinueStatement(n)) {
3645
+ if (n.label ? !st.labels.has(n.label.text) : !st.continueBound) continues.add(n.label?.text ?? null);
3646
+ return;
3647
+ }
3648
+ if (ts.isReturnStatement(n)) {
3649
+ if (!returnLeaves) callbackReturn = true;
3650
+ return;
3651
+ }
3652
+ if (ts.isFunctionDeclaration(n) || ts.isArrowFunction(n) || ts.isFunctionExpression(n)) return;
3653
+ if (ts.isLabeledStatement(n)) {
3654
+ visit(n.statement, { ...st, labels: new Set(st.labels).add(n.label.text) });
3655
+ return;
3656
+ }
3657
+ if (
3658
+ ts.isWhileStatement(n) ||
3659
+ ts.isDoStatement(n) ||
3660
+ ts.isForStatement(n) ||
3661
+ ts.isForOfStatement(n) ||
3662
+ ts.isForInStatement(n)
3663
+ ) {
3664
+ ts.forEachChild(n, (c) => {
3665
+ if (!this.tscExcludedArm(n, c)) visit(c, { ...st, breakBound: true, continueBound: true });
3666
+ });
3667
+ return;
3668
+ }
3669
+ if (ts.isSwitchStatement(n)) {
3670
+ ts.forEachChild(n, (c) => visit(c, { ...st, breakBound: true }));
3671
+ return;
3672
+ }
3673
+ // tsc-excluded arms carry no escaping edges: an edge the CFA cannot
3674
+ // take must not stage kills at its would-be destination
3675
+ // (tscExcludedArm — mirrors allRoutesLeaveFunction's route walk).
3676
+ ts.forEachChild(n, (c) => {
3677
+ if (!this.tscExcludedArm(n, c)) visit(c, st);
3678
+ });
3679
+ };
3680
+ const start: Bound = { labels: new Set(), breakBound: false, continueBound: false };
3681
+ for (const s of stmts) visit(s, start);
3682
+ return { breaks, continues, callbackReturn };
3683
+ }
3684
+
3685
+ private emitStatementList(stmts: readonly ts.Statement[], ctx: Ctx): void {
2968
3686
  for (let i = 0; i < stmts.length; i++) {
2969
3687
  const stmt = stmts[i];
2970
3688
  for (const c of this.leadingComments(stmt)) this.push(ctx, c);
@@ -2982,8 +3700,16 @@ export class Emitter {
2982
3700
  !next.elseStatement &&
2983
3701
  test !== null &&
2984
3702
  ts.isIdentifier(test.target) &&
2985
- test.target.text === decl.name.text &&
2986
- this.alwaysExits(next.thenStatement)
3703
+ // Declaration identity, not name text: the guard must test THIS
3704
+ // declaration for the fusion's const to stand in for it (a
3705
+ // same-named outer local tested here narrows the wrong slot).
3706
+ this.tast.declarationOf(test.target) === decl &&
3707
+ this.alwaysExits(next.thenStatement) &&
3708
+ // A reassigned `let` cannot fuse: the fusion emits `const` typed by
3709
+ // the non-optional payload, so a later `p = ...` (or a legal
3710
+ // `p = null`) has no binding to land in. The plain path already
3711
+ // types it `var p: ?T` and guards with a real `if`.
3712
+ !this.isReassigned(decl, ctx)
2987
3713
  ) {
2988
3714
  const initType = this.zTypeOfExpr(decl.initializer, ctx);
2989
3715
  if (initType.k === "optional") {
@@ -3005,10 +3731,19 @@ export class Emitter {
3005
3731
  cond: ts.Expression,
3006
3732
  op: ts.SyntaxKind = ts.SyntaxKind.EqualsEqualsEqualsToken,
3007
3733
  ): { target: ts.Expression; flavor: "null" | "undefined" } | null {
3008
- if (!ts.isBinaryExpression(cond) || cond.operatorToken.kind !== op) return null;
3734
+ // Wrapper spellings must not change what the test matches: the
3735
+ // condition, either operand, and the returned target all strip
3736
+ // parentheses, non-null assertions, `as`, and `satisfies` — emission
3737
+ // erases every one of them, and tsc's own narrowing sees through them
3738
+ // too (`(q) === null` and `q! !== null` both test `q`), so downstream
3739
+ // shape checks and key derivations see the identifier itself.
3740
+ const c = unwrapExpr(cond);
3741
+ if (!ts.isBinaryExpression(c) || c.operatorToken.kind !== op) return null;
3742
+ const left = unwrapExpr(c.left);
3743
+ const right = unwrapExpr(c.right);
3009
3744
  const sides: Array<[ts.Expression, ts.Expression]> = [
3010
- [cond.left, cond.right],
3011
- [cond.right, cond.left],
3745
+ [left, right],
3746
+ [right, left],
3012
3747
  ];
3013
3748
  for (const [target, emptySide] of sides) {
3014
3749
  const flavor = this.emptyFlavorOf(emptySide);
@@ -3029,6 +3764,17 @@ export class Emitter {
3029
3764
  return null;
3030
3765
  }
3031
3766
 
3767
+ /// A literal JS empty in VALUE position, through the value-preserving
3768
+ /// wrappers emission erases (parens, `as`, `satisfies`, non-null
3769
+ /// assertions): the `null` keyword or the global `undefined` identifier.
3770
+ /// Every ternary-arm and nullish EMPTINESS decision must use this, never
3771
+ /// a ZType check — `undefined`'s internal type is void, so a type check
3772
+ /// reads an `undefined` arm as a non-empty value and drops the
3773
+ /// optionality it carries, skipping the later guard's unwrap.
3774
+ private isEmptyLiteral(e: ts.Expression): boolean {
3775
+ return this.emptyFlavorOf(unwrapExpr(e)) !== null;
3776
+ }
3777
+
3032
3778
  /// R7c: JS keeps null and undefined distinct; the native optional folds
3033
3779
  /// both into one empty. An empty test therefore only maps when the
3034
3780
  /// target's own type carries exactly the tested empty — testing the wrong
@@ -3051,8 +3797,20 @@ export class Emitter {
3051
3797
  }
3052
3798
  }
3053
3799
 
3800
+ /// Whether a statement NEVER falls through to the statement after it.
3801
+ /// tsc's control-flow analysis narrows after any such statement — return,
3802
+ /// throw, break, and continue all qualify (a break/continue jumps to an
3803
+ /// enclosing construct's boundary, never to the next statement in
3804
+ /// sequence), so an early-exit guard narrows the remainder of its block
3805
+ /// no matter which exit the guard takes. A constant-true loop that no
3806
+ /// break binds qualifies too: it never completes normally, so tsc treats
3807
+ /// the statement after it as unreachable (and Zig types such a loop
3808
+ /// noreturn — the two terminality judgments must stay aligned).
3809
+ /// Kill-frame drops need the stronger whole-function question; that is
3810
+ /// allRoutesLeaveFunction.
3054
3811
  private alwaysExits(stmt: ts.Statement): boolean {
3055
3812
  if (ts.isReturnStatement(stmt)) return true;
3813
+ if (ts.isBreakStatement(stmt) || ts.isContinueStatement(stmt)) return true;
3056
3814
  // R20: a throw never falls through (it unwinds to a catch or out of
3057
3815
  // the function), and a try/catch exits when both arms do — any throw
3058
3816
  // mid-try lands in the catch, which exits. NS1058 keeps `finally`
@@ -3060,7 +3818,8 @@ export class Emitter {
3060
3818
  if (ts.isThrowStatement(stmt)) return true;
3061
3819
  if (ts.isTryStatement(stmt)) {
3062
3820
  const tryExits = this.alwaysExits(stmt.tryBlock);
3063
- const catchExits = stmt.catchClause === undefined || this.alwaysExits(stmt.catchClause.block);
3821
+ const catchExits =
3822
+ stmt.catchClause === undefined || this.alwaysExits(stmt.catchClause.block);
3064
3823
  return tryExits && catchExits;
3065
3824
  }
3066
3825
  if (ts.isBlock(stmt)) {
@@ -3074,43 +3833,486 @@ export class Emitter {
3074
3833
  this.alwaysExits(stmt.elseStatement)
3075
3834
  );
3076
3835
  }
3836
+ // A constant-true loop with no break bound to it never completes
3837
+ // normally, so the statement after it is unreachable — tsc's CFA types
3838
+ // post-loop code off the paths that never get there. The recognition
3839
+ // mirrors tsc's scope for our subset: the literal `true` keyword (and
3840
+ // the omitted / literal-true `for` condition) only, never arbitrary
3841
+ // constant-foldable expressions. Returns and throws inside the loop
3842
+ // leave the function without completing the loop, so they don't make
3843
+ // its end reachable (allRoutesLeaveFunction classifies them as routes
3844
+ // of their own); `continue` stays inside. Only a break bound to the
3845
+ // loop resumes right after it.
3846
+ if (ts.isWhileStatement(stmt) || ts.isDoStatement(stmt)) {
3847
+ return stmt.expression.kind === ts.SyntaxKind.TrueKeyword && !this.bindsBreak(stmt);
3848
+ }
3849
+ if (ts.isForStatement(stmt)) {
3850
+ return (
3851
+ (stmt.condition === undefined || stmt.condition.kind === ts.SyntaxKind.TrueKeyword) &&
3852
+ !this.bindsBreak(stmt)
3853
+ );
3854
+ }
3077
3855
  if (ts.isSwitchStatement(stmt)) {
3078
- // A value switch (R13d) without a default may skip every clause, so
3079
- // only kind switches (exhaustive by NS1015) and defaulted switches
3080
- // count as exiting. Exhaustiveness itself is enforced at emission;
3081
- // here the question is only whether every written clause exits.
3856
+ // A break bound to THIS switch resumes right after it, so the switch
3857
+ // completes normally even when every clause body ends in an exit
3858
+ // statement (the ubiquitous clause-terminating `break;` is exactly
3859
+ // such a break).
3860
+ if (this.bindsBreak(stmt)) return false;
3861
+ // A value switch (R13d) without a default may skip every clause —
3862
+ // unless its case labels cover the scrutinee's literal-union type,
3863
+ // in which case tsc's CFA (which is what this predicate mirrors)
3864
+ // treats the switch as always entering a clause. Kind switches are
3865
+ // exhaustive by NS1015; defaulted switches always enter a clause;
3866
+ // everything else consults the type (conservative false when the
3867
+ // scrutinee is not an enumerable literal union).
3082
3868
  const kindSwitch =
3083
3869
  ts.isPropertyAccessExpression(stmt.expression) && stmt.expression.name.text === "kind";
3084
3870
  const hasDefault = stmt.caseBlock.clauses.some((c) => ts.isDefaultClause(c));
3085
- if (!kindSwitch && !hasDefault) return false;
3086
- return stmt.caseBlock.clauses.every((c) => {
3871
+ if (!kindSwitch && !hasDefault && !this.valueSwitchCoversScrutineeType(stmt)) return false;
3872
+ // Stacked case labels (`case "a": case "b": body`) share one body:
3873
+ // JS falls through an empty clause onto the next clause's statements
3874
+ // (the switch emitters coalesce the labels into one arm the same
3875
+ // way), so an empty clause's terminality is its group's tail's — the
3876
+ // next statement-bearing clause at or after it. A trailing run of
3877
+ // empty clauses has no body at all: control falls out of the switch,
3878
+ // so the switch completes normally.
3879
+ const clauses = stmt.caseBlock.clauses;
3880
+ return clauses.every((c, i) => {
3087
3881
  let stmts: readonly ts.Statement[] = c.statements;
3882
+ for (let j = i + 1; stmts.length === 0 && j < clauses.length; j++) {
3883
+ stmts = clauses[j].statements;
3884
+ }
3088
3885
  if (stmts.length === 1 && ts.isBlock(stmts[0])) stmts = (stmts[0] as ts.Block).statements;
3089
3886
  const last = stmts[stmts.length - 1];
3090
3887
  return last !== undefined && this.alwaysExits(last);
3091
3888
  });
3092
3889
  }
3890
+ if (ts.isLabeledStatement(stmt)) {
3891
+ // A label adds exactly one edge: `break label` resumes right AFTER
3892
+ // the labeled statement, making its end reachable. So the statement
3893
+ // is terminal iff the wrapped statement is terminal AND nothing
3894
+ // inside breaks to the label. The check is additive: a wrapped
3895
+ // loop's unlabeled breaks are already the loop's own concern
3896
+ // (bindsBreak, which also sees wrapping labels), and a labeled
3897
+ // BLOCK's inner terminality comes from the block rule above.
3898
+ return (
3899
+ this.alwaysExits(stmt.statement) &&
3900
+ !this.breaksToLabel(stmt.statement, stmt.label.text)
3901
+ );
3902
+ }
3903
+ return false;
3904
+ }
3905
+
3906
+ /// Whether a defaultless VALUE switch's case labels cover every member of
3907
+ /// the scrutinee's literal-union type. Enumerable scrutinees are
3908
+ /// string/number/boolean literal unions ONLY: any wider type, any
3909
+ /// non-literal member, or any case label that is not a literal after
3910
+ /// wrapper-stripping answers false — the conservative side (a false merely
3911
+ /// merges a kill tsc kept and completes the lowered fallthrough; a wrong
3912
+ /// true emits an `else => unreachable` real execution can REACH). The type
3913
+ /// consulted is scrutineeCoverageType's SOUND type, never the checker's
3914
+ /// raw flow type: tsc keeps a local's narrowing across callback bodies
3915
+ /// that assign it, so its flow-exhaustiveness can be false at runtime.
3916
+ /// alwaysExits stays syntax-only on every other construct, and every
3917
+ /// caller is an emission path where `this.tast` is live, so the capability
3918
+ /// is unconditional. THE AGREEMENT INVARIANT: the terminality claim and
3919
+ /// the emitted shape must never disagree — no switch construct may be
3920
+ /// claimed terminal while its lowering emits a completable fallthrough.
3921
+ /// Each lowering either closes or declines:
3922
+ /// - emitSwitch (kind): a Zig enum switch is exhaustive by construction
3923
+ /// (NS1015 gates uncovered arms), and a terminal claim requires every
3924
+ /// arm group to exit, so the shape closes by construction;
3925
+ /// - emitValueSwitch: a covered-by-type defaultless switch whose arms
3926
+ /// all exit closes its never-reached fallthrough with
3927
+ /// `else => unreachable` (numeric) or emits no else at all (string
3928
+ /// enums, already Zig-exhaustive), and asserts the agreement;
3929
+ /// - emitPlainSwitch: the lowered if/else chain closes a
3930
+ /// claimed-terminal defaultless switch with an `unreachable` else
3931
+ /// (its `claimsTerminal`), and asserts the agreement.
3932
+ /// All consumers read this one memoized judgment and demote together.
3933
+ private valueSwitchCoversScrutineeType(stmt: ts.SwitchStatement): boolean {
3934
+ const memo = this.switchCoversTypeMemo.get(stmt);
3935
+ if (memo !== undefined) return memo;
3936
+ const answer = this.computeValueSwitchCoversScrutineeType(stmt);
3937
+ this.switchCoversTypeMemo.set(stmt, answer);
3938
+ return answer;
3939
+ }
3940
+
3941
+ /// The type a defaultless switch's exhaustiveness may be judged against —
3942
+ /// null when no sound basis exists (the caller then answers false). tsc's
3943
+ /// flow type at the scrutinee is NOT such a basis on its own: tsc never
3944
+ /// widens a local's narrowing for assignments inside callbacks (it types
3945
+ /// `let k: "a" | "b" = "a"; xs.map(() => { k = "b"; }); switch (k)` with
3946
+ /// k still "a"), so a flow-exhaustive switch can be skipped by real
3947
+ /// execution. Sound bases, in order:
3948
+ /// - an identifier local/param never assigned inside any nested
3949
+ /// function of the switch's own enclosing function keeps the flow
3950
+ /// type: locals cannot alias, so a scan over nested-function scopes
3951
+ /// for assignments is exact, and without a capture-site assignment
3952
+ /// the straight-line CFA is;
3953
+ /// - any other narrowable reference (identifier, property read) is
3954
+ /// judged by its DECLARED type — a symbol can hold any member of its
3955
+ /// declared union at runtime whatever the flow claims;
3956
+ /// - a non-reference scrutinee (call result, arithmetic, literal) has
3957
+ /// no flow claims to distrust: its own resolved type stands.
3958
+ private scrutineeCoverageType(expr: ts.Expression): ts.Type | null {
3959
+ const e = unwrapExpr(expr);
3960
+ if (ts.isIdentifier(e)) {
3961
+ if (this.scrutineeFlowTrustable(e)) return this.tast.typeOf(e);
3962
+ return this.declaredTypeOfReference(e);
3963
+ }
3964
+ if (ts.isPropertyAccessExpression(e)) return this.declaredTypeOfReference(e.name);
3965
+ if (ts.isElementAccessExpression(e)) return null;
3966
+ return this.tast.typeOf(e);
3967
+ }
3968
+
3969
+ /// The declared (declaration-site) type of a reference: the annotation
3970
+ /// when the declaration carries one, else the checker's type AT the
3971
+ /// declaration name — the symbol's initial type, which no flow narrowing
3972
+ /// has touched. Null when the declaration shape is not one whose declared
3973
+ /// type is recoverable; callers treat null as "cannot judge".
3974
+ private declaredTypeOfReference(name: ts.Node): ts.Type | null {
3975
+ const decl = this.tast.declarationOf(name);
3976
+ if (!decl) return null;
3977
+ if (
3978
+ (ts.isVariableDeclaration(decl) ||
3979
+ ts.isParameter(decl) ||
3980
+ ts.isPropertySignature(decl) ||
3981
+ ts.isPropertyDeclaration(decl)) &&
3982
+ decl.type
3983
+ ) {
3984
+ return this.tast.typeFromTypeNode(decl.type);
3985
+ }
3986
+ if (ts.isVariableDeclaration(decl) && ts.isIdentifier(decl.name)) {
3987
+ return this.tast.typeOf(decl.name);
3988
+ }
3989
+ return null;
3990
+ }
3991
+
3992
+ /// Whether the flow type of this identifier may be trusted for an
3993
+ /// exhaustiveness claim: it names a local/param declared in the SAME
3994
+ /// enclosing function, and no nested function/callback in that function's
3995
+ /// body assigns it BEFORE the read can execute. Locals cannot alias in
3996
+ /// TypeScript, so the only escape hatch from the straight-line CFA is a
3997
+ /// capture-site assignment — the exact hole tsc's optimistic callback
3998
+ /// model leaves open. Declines when the declaration lives in an outer
3999
+ /// scope (the local IS a capture there) or when any nested function that
4000
+ /// can have RUN before the read (nestedFnRunsBeforeUse: position for
4001
+ /// arrows/function expressions, always for hoisted declarations and
4002
+ /// class members, back edges for shared loops) assigns or ++/--s it.
4003
+ private scrutineeFlowTrustable(id: ts.Identifier): boolean {
4004
+ const decl = this.tast.declarationOf(id);
4005
+ if (!decl || (!ts.isVariableDeclaration(decl) && !ts.isParameter(decl))) return false;
4006
+ const isFnScope = (n: ts.Node): boolean =>
4007
+ ts.isArrowFunction(n) ||
4008
+ ts.isFunctionExpression(n) ||
4009
+ ts.isFunctionDeclaration(n) ||
4010
+ ts.isMethodDeclaration(n) ||
4011
+ ts.isConstructorDeclaration(n) ||
4012
+ ts.isGetAccessorDeclaration(n) ||
4013
+ ts.isSetAccessorDeclaration(n);
4014
+ const enclosing = (n: ts.Node): ts.Node => {
4015
+ let cur: ts.Node | undefined = n.parent;
4016
+ while (cur && !isFnScope(cur)) cur = cur.parent;
4017
+ return cur ?? n.getSourceFile();
4018
+ };
4019
+ const scope = enclosing(id);
4020
+ if (scope !== enclosing(decl)) return false;
4021
+ let assignedInNested = false;
4022
+ // `root` is the OUTERMOST nested function of the current subtree: the
4023
+ // reach-before-use judgment belongs to it (an arrow inside a hoisted
4024
+ // declaration runs whenever the declaration does, so the inner arrow's
4025
+ // own position proves nothing).
4026
+ const visit = (n: ts.Node, root: ts.Node | null): void => {
4027
+ if (assignedInNested) return;
4028
+ const enter = root ?? (n !== scope && isFnScope(n) ? n : null);
4029
+ if (enter) {
4030
+ if (
4031
+ ts.isBinaryExpression(n) &&
4032
+ n.operatorToken.kind >= ts.SyntaxKind.FirstAssignment &&
4033
+ n.operatorToken.kind <= ts.SyntaxKind.LastAssignment
4034
+ ) {
4035
+ const target = unwrapExpr(n.left);
4036
+ if (
4037
+ ts.isIdentifier(target) &&
4038
+ this.tast.declarationOf(target) === decl &&
4039
+ this.nestedFnRunsBeforeUse(enter, id)
4040
+ ) {
4041
+ assignedInNested = true;
4042
+ return;
4043
+ }
4044
+ }
4045
+ if (
4046
+ (ts.isPrefixUnaryExpression(n) || ts.isPostfixUnaryExpression(n)) &&
4047
+ (n.operator === ts.SyntaxKind.PlusPlusToken || n.operator === ts.SyntaxKind.MinusMinusToken)
4048
+ ) {
4049
+ const target = unwrapExpr(n.operand as ts.Expression);
4050
+ if (
4051
+ ts.isIdentifier(target) &&
4052
+ this.tast.declarationOf(target) === decl &&
4053
+ this.nestedFnRunsBeforeUse(enter, id)
4054
+ ) {
4055
+ assignedInNested = true;
4056
+ return;
4057
+ }
4058
+ }
4059
+ }
4060
+ ts.forEachChild(n, (c) => visit(c, enter));
4061
+ };
4062
+ visit(scope, null);
4063
+ return !assignedInNested;
4064
+ }
4065
+
4066
+ /// Whether an assignment inside nested function `fn` can have EXECUTED
4067
+ /// before the flow-trusted read at `use`. Labels the position rule with
4068
+ /// JS evaluation semantics:
4069
+ /// - function DECLARATIONS hoist — they exist from scope start, so an
4070
+ /// earlier call can run them wherever they sit — and class-member
4071
+ /// bodies (methods, accessors, constructors) exist from their
4072
+ /// container's creation: all count regardless of position;
4073
+ /// - arrow functions and function EXPRESSIONS do not exist as values
4074
+ /// before their definition evaluates, so one whose definition sits
4075
+ /// textually after the read cannot have run before it — UNLESS a
4076
+ /// loop encloses both, whose back edge re-enters the read after the
4077
+ /// definition evaluated on an earlier iteration. An arrow defined
4078
+ /// before the read counts even when only a variable holds it
4079
+ /// (conservative-correct: whether anything calls it is not asked).
4080
+ private nestedFnRunsBeforeUse(fn: ts.Node, use: ts.Identifier): boolean {
4081
+ if (!ts.isArrowFunction(fn) && !ts.isFunctionExpression(fn)) return true;
4082
+ if (fn.getStart() < use.getStart()) return true;
4083
+ for (let cur: ts.Node | undefined = fn.parent; cur && !ts.isSourceFile(cur); cur = cur.parent) {
4084
+ if (ts.isFunctionLike(cur)) break;
4085
+ if (
4086
+ ts.isIterationStatement(cur, false) &&
4087
+ cur.getStart() <= use.getStart() &&
4088
+ use.getEnd() <= cur.getEnd()
4089
+ ) {
4090
+ return true;
4091
+ }
4092
+ }
3093
4093
  return false;
3094
4094
  }
3095
4095
 
4096
+ private computeValueSwitchCoversScrutineeType(stmt: ts.SwitchStatement): boolean {
4097
+ const type = this.scrutineeCoverageType(stmt.expression);
4098
+ if (type === null) return false;
4099
+ const members = type.isUnion() ? type.types : [type];
4100
+ const wanted = new Set<string>();
4101
+ for (const member of members) {
4102
+ if (member.isStringLiteral()) wanted.add(`s:${member.value}`);
4103
+ else if (member.isNumberLiteral()) wanted.add(`n:${member.value}`);
4104
+ else if (member.flags & ts.TypeFlags.BooleanLiteral) {
4105
+ wanted.add(`b:${this.tast.typeToString(member)}`);
4106
+ } else return false;
4107
+ }
4108
+ for (const clause of stmt.caseBlock.clauses) {
4109
+ if (ts.isDefaultClause(clause)) continue;
4110
+ const label = unwrapExpr(clause.expression);
4111
+ if (ts.isStringLiteral(label)) wanted.delete(`s:${label.text}`);
4112
+ else if (label.kind === ts.SyntaxKind.TrueKeyword) wanted.delete("b:true");
4113
+ else if (label.kind === ts.SyntaxKind.FalseKeyword) wanted.delete("b:false");
4114
+ else {
4115
+ const v = this.tast.constEvalNumber(label);
4116
+ if (v === null) return false;
4117
+ wanted.delete(`n:${v}`);
4118
+ }
4119
+ }
4120
+ return wanted.size === 0;
4121
+ }
4122
+
4123
+ /// Kill-frame drop eligibility: whether EVERY route out of this statement
4124
+ /// list leaves the emitted function. Only then may the list's narrowing
4125
+ /// kills drop (emitBlockStatements) or a catch arm close the exception
4126
+ /// paths over its try body (emitTryCore) — the final statement alone
4127
+ /// cannot answer this, because earlier statements open routes of their
4128
+ /// own. The routes, and when each one resumes in-function instead of
4129
+ /// leaving:
4130
+ /// - fallthrough off the end of the list — always resumes;
4131
+ /// - `return` — resumes where returns lower to labeled breaks (lifted
4132
+ /// callbacks: env.returnLeaves is false);
4133
+ /// - `break`/`continue` at any nesting depth whose target sits at or
4134
+ /// outside the list — always resumes (after the target construct,
4135
+ /// inside the function). One bound to a loop/switch/label WHOLLY
4136
+ /// inside the list stays inside it and is not a route out, so the
4137
+ /// walk tracks locally-bound targets, never spellings;
4138
+ /// - `throw`, or any statement containing a throwing call, whose
4139
+ /// handler can fall back into the function — the handler is the
4140
+ /// nearest catch inside the list, and the route's destination is
4141
+ /// that catch PLUS its continuation: a catch that falls through
4142
+ /// resumes at the statements following its try (transitively out
4143
+ /// through enclosing blocks), so the route leaves iff every route
4144
+ /// out of the catch leaves AND that continuation leaves. Outside
4145
+ /// any local try, whatever env.throwResumes says about the
4146
+ /// surroundings.
4147
+ /// When a route resists classification the answer is false (merge): an
4148
+ /// over-merge costs a narrow tsc would have kept, an under-merge
4149
+ /// resurrects a dead one and emits an unwrap Zig rejects. The
4150
+ /// continuation after a try is known positionally inside statement
4151
+ /// lists (the top list and nested blocks); inside loop bodies, switch
4152
+ /// clauses, and inline callbacks a catch's fallthrough re-enters the
4153
+ /// construct, so the continuation is treated as resuming there.
4154
+ /// `env.edgesLeave` re-asks the question with escaping break/continue
4155
+ /// edges and lowered returns treated as LEAVING: emitBlockStatements uses
4156
+ /// the difference to isolate lists whose only in-function routes are
4157
+ /// non-local edges (their kills stage at the edges' destinations rather
4158
+ /// than merging — see edgeKillRouting). A leaving return's expression
4159
+ /// still walks: throwing calls inside it ride the throw edges, not the
4160
+ /// return edge.
4161
+ private allRoutesLeaveFunction(
4162
+ stmts: readonly ts.Statement[],
4163
+ env: { returnLeaves: boolean; throwResumes: boolean; edgesLeave?: boolean },
4164
+ ): boolean {
4165
+ // `labels` / `breaks` / `continues` carry the targets bound inside the
4166
+ // list so far on this path; `throwResumes` is the handler visibility at
4167
+ // this point (re-derived at every try/catch met on the way down);
4168
+ // `inCallback` marks inline (unlifted) callback bodies, whose returns
4169
+ // are their own but whose throwing calls act at this site.
4170
+ interface State {
4171
+ readonly labels: ReadonlySet<string>;
4172
+ readonly breaks: number;
4173
+ readonly continues: number;
4174
+ readonly throwResumes: boolean;
4175
+ readonly inCallback: boolean;
4176
+ }
4177
+ // `tailLeaves`: whether control falling through past the node (to the
4178
+ // rest of its enclosing list, transitively outward) leaves the
4179
+ // function on every route — the positional continuation a
4180
+ // fallthrough catch hands a caught throw.
4181
+ const resumes = (n: ts.Node, st: State, tailLeaves: boolean): boolean => {
4182
+ const walk = (c: ts.Node): boolean => resumes(c, st, tailLeaves);
4183
+ if (ts.isBreakStatement(n)) {
4184
+ if (env.edgesLeave) return false;
4185
+ return !st.inCallback && (n.label ? !st.labels.has(n.label.text) : st.breaks === 0);
4186
+ }
4187
+ if (ts.isContinueStatement(n)) {
4188
+ if (env.edgesLeave) return false;
4189
+ return !st.inCallback && (n.label ? !st.labels.has(n.label.text) : st.continues === 0);
4190
+ }
4191
+ if (ts.isReturnStatement(n)) {
4192
+ if (!st.inCallback && !env.returnLeaves && !env.edgesLeave) return true;
4193
+ return n.expression !== undefined && walk(n.expression);
4194
+ }
4195
+ if (ts.isThrowStatement(n)) {
4196
+ return st.throwResumes || walk(n.expression);
4197
+ }
4198
+ if ((ts.isCallExpression(n) || ts.isNewExpression(n)) && st.throwResumes) {
4199
+ const target = this.calleeOwnerOf(n);
4200
+ if (target && this.leakingFns.has(target)) return true;
4201
+ }
4202
+ if (ts.isBlock(n)) {
4203
+ // A block's own fallthrough continues wherever the block's does,
4204
+ // so its statements scan positionally against the same tail.
4205
+ return scanList(n.statements, st, tailLeaves).resumes;
4206
+ }
4207
+ if (ts.isTryStatement(n) && n.catchClause !== undefined) {
4208
+ // Throws in the body land in this catch, whose destination is the
4209
+ // catch block plus its continuation: a fallthrough catch resumes
4210
+ // at the statements after this try, so the caught throw leaves
4211
+ // iff the catch-then-rest continuation leaves. The catch itself
4212
+ // runs against the handler visible OUTSIDE this try (its own
4213
+ // throws escape to enclosing handlers, never back into it).
4214
+ const catchScan = scanList(n.catchClause.block.statements, st, tailLeaves);
4215
+ const bodyThrowResumes = !catchScan.leaves;
4216
+ return (
4217
+ resumes(n.tryBlock, { ...st, throwResumes: bodyThrowResumes }, tailLeaves) ||
4218
+ catchScan.resumes ||
4219
+ (n.finallyBlock !== undefined && walk(n.finallyBlock))
4220
+ );
4221
+ }
4222
+ if (ts.isLabeledStatement(n)) {
4223
+ const bound = new Set(st.labels);
4224
+ bound.add(n.label.text);
4225
+ return resumes(n.statement, { ...st, labels: bound }, tailLeaves);
4226
+ }
4227
+ if (
4228
+ ts.isWhileStatement(n) ||
4229
+ ts.isDoStatement(n) ||
4230
+ ts.isForStatement(n) ||
4231
+ ts.isForOfStatement(n) ||
4232
+ ts.isForInStatement(n)
4233
+ ) {
4234
+ // The loop binds unlabeled break/continue for its whole subtree
4235
+ // (heads hold no break/continue — tsc rejects them there). A
4236
+ // fallthrough inside the body resumes at the back edge, in the
4237
+ // function, so the body scans against a resuming tail. A
4238
+ // tsc-excluded body (while (false), for (; false;)) contributes
4239
+ // no routes at all — an edge tsc's CFA cannot take is not a route
4240
+ // (tscExcludedArm; the joins already give such arms no kills).
4241
+ return (
4242
+ ts.forEachChild(n, (c) =>
4243
+ (!this.tscExcludedArm(n, c) &&
4244
+ resumes(c, { ...st, breaks: st.breaks + 1, continues: st.continues + 1 }, false)) ||
4245
+ undefined,
4246
+ ) === true
4247
+ );
4248
+ }
4249
+ if (ts.isSwitchStatement(n)) {
4250
+ // Clause fallthrough resumes at the next clause / after the
4251
+ // switch — in the function — so clauses scan against a resuming
4252
+ // tail too.
4253
+ return (
4254
+ walk(n.expression) ||
4255
+ resumes(n.caseBlock, { ...st, breaks: st.breaks + 1 }, false)
4256
+ );
4257
+ }
4258
+ // Declarations don't run here; lifted callbacks are analyzed at
4259
+ // their own emission (their bodies get a retLabel of their own).
4260
+ if (ts.isFunctionDeclaration(n)) return false;
4261
+ if (ts.isArrowFunction(n) || ts.isFunctionExpression(n)) {
4262
+ if ([...this.hoistedFns.values()].includes(n)) return false;
4263
+ return resumes(n.body, { ...st, inCallback: true }, false);
4264
+ }
4265
+ // tsc-excluded arms (`if (false)` then, `if (true)` else) hold no
4266
+ // routes tsc's CFA can take: a dead `break` must not read as a
4267
+ // loop-escaping edge (tscExcludedArm).
4268
+ return ts.forEachChild(n, (c) => (!this.tscExcludedArm(n, c) && walk(c)) || undefined) === true;
4269
+ };
4270
+ // One right-to-left pass over a statement list: `resumes` is whether
4271
+ // any route out of any statement resumes in-function (each statement
4272
+ // classified against the continuation after ITS position); `leaves`
4273
+ // is whether control entering the list leaves the function on every
4274
+ // route — no route resumes, and fallthrough (which stops at the first
4275
+ // always-exiting statement) bottoms out in an exit or a leaving tail.
4276
+ // The fallthrough chain deliberately ignores in-list resuming routes:
4277
+ // any such route already forces `resumes`, and every consumer of
4278
+ // `leaves` (the verdict below, a caught throw's continuation) sits
4279
+ // under a scan whose `resumes` it feeds.
4280
+ const scanList = (
4281
+ list: readonly ts.Statement[],
4282
+ st: State,
4283
+ tailLeaves: boolean,
4284
+ ): { leaves: boolean; resumes: boolean } => {
4285
+ let cont = tailLeaves;
4286
+ let any = false;
4287
+ for (let i = list.length - 1; i >= 0; i--) {
4288
+ if (resumes(list[i], st, cont)) any = true;
4289
+ cont = this.alwaysExits(list[i]) || cont;
4290
+ }
4291
+ return { leaves: !any && cont, resumes: any };
4292
+ };
4293
+ const start: State = {
4294
+ labels: new Set(),
4295
+ breaks: 0,
4296
+ continues: 0,
4297
+ throwResumes: env.throwResumes,
4298
+ inCallback: false,
4299
+ };
4300
+ // Fallthrough off the end of the whole list always resumes.
4301
+ return scanList(stmts, start, false).leaves;
4302
+ }
4303
+
3096
4304
  private emitOrelseFusion(decl: ts.VariableDeclaration, exit: ts.Statement, inner: ZType, ctx: Ctx): void {
3097
4305
  const name = this.claim(ctx, decl, zigLocalName((decl.name as ts.Identifier).text));
3098
4306
  ctx.localTypes.set(decl, inner);
3099
4307
  const init = orelseOperand(this.emitExpr(decl.initializer!, ctx).code);
3100
4308
  const exitStmts = ts.isBlock(exit) ? exit.statements : [exit];
3101
- if (exitStmts.length === 1 && ts.isReturnStatement(exitStmts[0])) {
3102
- const r = exitStmts[0];
3103
- if (!r.expression) {
3104
- this.push(ctx, `const ${name} = ${init} orelse ${this.returnText(ctx, null, r)}`);
3105
- return;
3106
- }
3107
- // Simple return value -> inline orelse; value needing statements -> block.
3108
- const sub = this.childCtx(ctx);
3109
- const v = this.emitReturn(r.expression, sub);
3110
- if (sub.lines.length === 0) {
3111
- this.push(ctx, `const ${name} = ${init} orelse ${this.returnText(ctx, v, r)}`);
3112
- return;
3113
- }
4309
+ // A one-statement exit inlines (`orelse return v` / `orelse break` /
4310
+ // `orelse continue`); anything needing statements takes the block form
4311
+ // below — the block never falls through, so Zig types it noreturn.
4312
+ const inline = this.singleExitText(exit, ctx);
4313
+ if (inline !== null) {
4314
+ this.push(ctx, `const ${name} = ${init} orelse ${inline}`);
4315
+ return;
3114
4316
  }
3115
4317
  this.push(ctx, `const ${name} = ${init} orelse {`);
3116
4318
  const sub = this.nestedCtx(ctx);
@@ -3119,6 +4321,23 @@ export class Emitter {
3119
4321
  this.push(ctx, `};`);
3120
4322
  }
3121
4323
 
4324
+ /// Clone a ctx for a probe or a same-indent sub-emission. ISOLATION LAW:
4325
+ /// the clone shares every mutable flow structure with its parent BY
4326
+ /// REFERENCE — memberSubst, stillOptionalSubst, narrowedUnion, the
4327
+ /// narrowKilled frame stack, the edgeKills stages, and pendingCatchKills
4328
+ /// — it isolates only the output lines. A PROBE (an emission whose lines
4329
+ /// may be discarded to pick a lowering shape) must therefore bracket
4330
+ /// itself with withNarrowScope: a probe that processes an assignment to
4331
+ /// an outer narrowed local (an inline map callback inside a ternary arm)
4332
+ /// would otherwise delete the narrowing for everything emitted after it
4333
+ /// — the SIBLING arm then reads the optional raw, invalid Zig. Sibling
4334
+ /// arms of one expression construct follow the statement-level law: each
4335
+ /// arm probes AND emits from the construct's entry state, and the arms'
4336
+ /// real kills join once after the last arm (applyJoinedNarrowKills).
4337
+ /// Kills a discarded probe stages on the shared edge sets (edgeKills,
4338
+ /// pendingCatchKills) are re-staged identically when the arm re-emits,
4339
+ /// so the sharing stays observationally clean — the narrowing maps and
4340
+ /// kill frames are the state a probe MUST NOT touch.
3122
4341
  private childCtx(ctx: Ctx): Ctx {
3123
4342
  return { ...ctx, lines: [], indent: ctx.indent };
3124
4343
  }
@@ -3145,20 +4364,37 @@ export class Emitter {
3145
4364
  this.emitIf(stmt, ctx);
3146
4365
  return;
3147
4366
  }
4367
+ // Loops (and below, labeled statements and switches) bracket their
4368
+ // emission with an edge-kill stage: kills that ride a break edge bound
4369
+ // here apply to the POST-construct state — the destination the break
4370
+ // resumes at — and kills on a continue edge ride the back edge into
4371
+ // the loop-entry join. The emitter realizes both as the post-loop
4372
+ // application below: the loop-entry model delegates in-body
4373
+ // next-iteration reads to tsc (a read relying on a narrow the back
4374
+ // edge kills is a tsc error the checker already rejected), so the
4375
+ // only remaining state a back-edge kill must reach is the loop's
4376
+ // normal-completion exit — the same post-loop point.
3148
4377
  if (ts.isWhileStatement(stmt)) {
3149
- this.emitWhile(stmt, ctx, null);
4378
+ const staged = this.stagedEdgeKills(ctx, "loop", null, () => this.emitWhile(stmt, ctx, null));
4379
+ // A `while (false)` body is tsc-unreachable (tscExcludedArm): kills
4380
+ // its break edges staged here never execute, so they don't apply.
4381
+ this.applyJoinedNarrowKills(ctx, this.tscExcludedArm(stmt, stmt.statement) ? new Set() : staged);
3150
4382
  return;
3151
4383
  }
3152
4384
  if (ts.isDoStatement(stmt)) {
3153
- this.emitDoWhile(stmt, ctx, null);
4385
+ this.applyJoinedNarrowKills(ctx, this.stagedEdgeKills(ctx, "loop", null, () => this.emitDoWhile(stmt, ctx, null)));
3154
4386
  return;
3155
4387
  }
3156
4388
  if (ts.isForStatement(stmt)) {
3157
- this.emitClassicFor(stmt, ctx, null);
4389
+ const staged = this.stagedEdgeKills(ctx, "loop", null, () => this.emitClassicFor(stmt, ctx, null));
4390
+ // A `for (; false;)` body is tsc-unreachable exactly like a
4391
+ // `while (false)` body (tscExcludedArm): kills its break edges
4392
+ // staged here never execute, so they don't apply.
4393
+ this.applyJoinedNarrowKills(ctx, this.tscExcludedArm(stmt, stmt.statement) ? new Set() : staged);
3158
4394
  return;
3159
4395
  }
3160
4396
  if (ts.isForOfStatement(stmt)) {
3161
- this.emitForOf(stmt, ctx, null);
4397
+ this.applyJoinedNarrowKills(ctx, this.stagedEdgeKills(ctx, "loop", null, () => this.emitForOf(stmt, ctx, null)));
3162
4398
  return;
3163
4399
  }
3164
4400
  if (ts.isLabeledStatement(stmt)) {
@@ -3171,28 +4407,49 @@ export class Emitter {
3171
4407
  const label = this.labelReferenced(stmt.statement, stmt.label.text)
3172
4408
  ? loopLabel(stmt.label.text)
3173
4409
  : null;
4410
+ // The stage binds by the SOURCE label: a labeled break/continue's
4411
+ // kills must land at this construct's post-state even from deep
4412
+ // inside nested loops (edgeKillRouting resolves labels innermost-
4413
+ // out, so an inner-targeted unlabeled break never binds here).
4414
+ const jsLabel = stmt.label.text;
3174
4415
  const inner = stmt.statement;
3175
4416
  if (ts.isWhileStatement(inner)) {
3176
- this.emitWhile(inner, ctx, label);
4417
+ const staged = this.stagedEdgeKills(ctx, "loop", jsLabel, () => this.emitWhile(inner, ctx, label));
4418
+ // Same tsc-unreachable exclusion as the unlabeled while dispatch.
4419
+ this.applyJoinedNarrowKills(ctx, this.tscExcludedArm(inner, inner.statement) ? new Set() : staged);
3177
4420
  } else if (ts.isDoStatement(inner)) {
3178
- this.emitDoWhile(inner, ctx, label);
4421
+ this.applyJoinedNarrowKills(ctx, this.stagedEdgeKills(ctx, "loop", jsLabel, () => this.emitDoWhile(inner, ctx, label)));
3179
4422
  } else if (ts.isForStatement(inner)) {
3180
- this.emitClassicFor(inner, ctx, label);
4423
+ const staged = this.stagedEdgeKills(ctx, "loop", jsLabel, () => this.emitClassicFor(inner, ctx, label));
4424
+ // Same tsc-unreachable exclusion as the unlabeled for dispatch.
4425
+ this.applyJoinedNarrowKills(ctx, this.tscExcludedArm(inner, inner.statement) ? new Set() : staged);
3181
4426
  } else if (ts.isForOfStatement(inner)) {
3182
- this.emitForOf(inner, ctx, label);
4427
+ this.applyJoinedNarrowKills(ctx, this.stagedEdgeKills(ctx, "loop", jsLabel, () => this.emitForOf(inner, ctx, label)));
3183
4428
  } else if (label === null) {
3184
4429
  this.emitStatement(inner, ctx);
3185
4430
  } else {
3186
- this.push(ctx, `${label}: {`);
3187
- const sub = this.nestedCtx(ctx);
3188
- this.emitBlockStatements(ts.isBlock(inner) ? inner.statements : [inner], sub);
3189
- ctx.lines.push(...sub.lines);
3190
- this.push(ctx, `}`);
4431
+ const kills = this.stagedEdgeKills(ctx, "block", jsLabel, () => {
4432
+ this.push(ctx, `${label}: {`);
4433
+ const sub = this.nestedCtx(ctx);
4434
+ this.emitBlockStatements(ts.isBlock(inner) ? inner.statements : [inner], sub);
4435
+ ctx.lines.push(...sub.lines);
4436
+ this.push(ctx, `}`);
4437
+ });
4438
+ this.applyJoinedNarrowKills(ctx, kills);
3191
4439
  }
3192
4440
  return;
3193
4441
  }
3194
4442
  if (ts.isSwitchStatement(stmt)) {
3195
- this.emitSwitch(stmt, ctx);
4443
+ // Clause-terminating breaks are stripped before their clause's route
4444
+ // analysis, so their kills ride the sibling JOIN (the switch
4445
+ // emitters' joinInto) to the same post-switch point this stage
4446
+ // applies at — one application, nothing dropped between the two
4447
+ // mechanisms. The stage itself keeps unlabeled-break RESOLUTION
4448
+ // faithful (a break under a switch binds the switch, never a loop
4449
+ // outside it; the mid-clause spellings that would stage here stop
4450
+ // the build at their own emission). Labeled exits out of a labeled
4451
+ // switch bind the wrapping labeled BLOCK's stage instead.
4452
+ this.applyJoinedNarrowKills(ctx, this.stagedEdgeKills(ctx, "switch", null, () => this.emitSwitch(stmt, ctx)));
3196
4453
  return;
3197
4454
  }
3198
4455
  if (ts.isExpressionStatement(stmt)) {
@@ -3200,14 +4457,36 @@ export class Emitter {
3200
4457
  return;
3201
4458
  }
3202
4459
  if (ts.isBlock(stmt)) {
3203
- this.push(ctx, `{`);
3204
- const sub = this.nestedCtx(ctx);
3205
- this.emitBlockStatements(stmt.statements, sub);
3206
- ctx.lines.push(...sub.lines);
3207
- this.push(ctx, `}`);
4460
+ // A plain lexical block is NOT a merge boundary: tsc's narrowing is
4461
+ // flow-based, so a narrow (or kill) established inside a fall-through
4462
+ // block survives into the statements after it. Emission FLATTENS the
4463
+ // block's statements into the enclosing list instead of bracketing
4464
+ // them (no withNarrowScope, no Zig braces): name uniquing is already
4465
+ // function-wide (ctx.used and the decl-keyed ctx.names ride every
4466
+ // nested ctx by reference), so Zig block scope is never load-bearing
4467
+ // for shadowing — and flattening is what keeps a narrowing capture
4468
+ // lowered inside the block (an orelse fusion's const, a `.?` subst's
4469
+ // target) in the same Zig scope as the post-block reads that rely on
4470
+ // it. Merge contexts (if/else arms, loop bodies, switch clauses,
4471
+ // callback and try/catch bodies, labeled blocks) never reach this
4472
+ // case — their emitters unwrap the block and bracket its statement
4473
+ // LIST — so control only ever falls straight through here. Nested
4474
+ // plain blocks flatten recursively.
4475
+ this.emitStatementList(stmt.statements, ctx);
3208
4476
  return;
3209
4477
  }
3210
4478
  if (ts.isBreakStatement(stmt)) {
4479
+ // An unlabeled JS break binds the nearest loop OR switch; Zig's
4480
+ // `break` binds loops only. A break that reaches statement emission
4481
+ // bound to a switch (the clause-terminating `break;` never gets
4482
+ // here — the switch emitters strip it) would jump past the wrong
4483
+ // construct, so it stops the build instead of miscompiling.
4484
+ if (!stmt.label && this.breakBindsEnclosingSwitch(stmt)) {
4485
+ this.fail(
4486
+ stmt,
4487
+ "a `break` that exits a `switch` from inside a clause body (only a clause-ending `break` has a mapping; restructure with an early `return`, or label the switch and `break <label>`)",
4488
+ );
4489
+ }
3211
4490
  this.push(ctx, stmt.label ? `break :${loopLabel(stmt.label.text)};` : `break;`);
3212
4491
  return;
3213
4492
  }
@@ -3289,26 +4568,186 @@ export class Emitter {
3289
4568
  private emitTry(stmt: ts.TryStatement, ctx: Ctx): void {
3290
4569
  const fin = stmt.finallyBlock && stmt.finallyBlock.statements.length > 0 ? stmt.finallyBlock : undefined;
3291
4570
  if (fin) {
4571
+ // The defer's TEXT precedes the try body's, but its FLOW follows it:
4572
+ // the finally runs at the construct's exits, after the body and catch.
4573
+ // So the finally emits in a bracketed scope — its entry state is the
4574
+ // pre-try narrows minus the keys tsc widens for a finally (see
4575
+ // finallyEntryKills: any possibly-null assignment in the try or catch
4576
+ // kills, path-insensitively), and its own kills stage in `finStage`
4577
+ // rather than merging, so the body emitted after this text still
4578
+ // holds every narrow tsc keeps at its program points (the finally
4579
+ // has not run there). The staged kills apply once at the construct's
4580
+ // exit below — the state every fall-through continuation resumes
4581
+ // from — and propagate outward through the enclosing frames exactly
4582
+ // like a merge-class kill applied at that spot.
3292
4583
  this.push(ctx, `{`);
3293
4584
  const wrap = this.nestedCtx(ctx);
3294
4585
  this.push(wrap, `// finally: a scoped defer runs it on every exit of this block.`);
3295
4586
  this.push(wrap, `defer {`);
3296
4587
  const finCtx = this.nestedCtx(wrap);
3297
- this.emitBlockStatements(fin.statements, finCtx);
4588
+ const finStage = new Set<string>();
4589
+ this.withNarrowScope(
4590
+ finCtx,
4591
+ "merge",
4592
+ () => {
4593
+ for (const key of this.finallyEntryKills(stmt, finCtx)) finCtx.memberSubst.delete(key);
4594
+ this.emitBlockStatements(fin.statements, finCtx);
4595
+ },
4596
+ finStage,
4597
+ );
3298
4598
  wrap.lines.push(...finCtx.lines);
3299
4599
  this.push(wrap, `}`);
3300
4600
  this.emitTryCore(stmt, wrap);
3301
4601
  ctx.lines.push(...wrap.lines);
3302
4602
  this.push(ctx, `}`);
4603
+ this.applyJoinedNarrowKills(ctx, finStage);
3303
4604
  return;
3304
4605
  }
3305
4606
  this.emitTryCore(stmt, ctx);
3306
4607
  }
3307
4608
 
4609
+ /// Whether tsc's CFA treats `arm` as statically unreachable inside
4610
+ /// `construct` — the then-arm of `if (false)`, the else-arm of
4611
+ /// `if (true)`, a `while (false)` body, a `for (; false;)` body (and its
4612
+ /// incrementor, which runs only after a body iteration). Such an arm
4613
+ /// contributes NOTHING to the flow bookkeeping: no kills at the branch
4614
+ /// join, no widening of a finally's entry narrows, no ROUTES either —
4615
+ /// a `break`/`continue`/`return`/`throw` under an excluded arm is not an
4616
+ /// edge tsc's CFA can take, so the route walks (allRoutesLeaveFunction,
4617
+ /// escapingEdgesOf) and the terminality binders (bindsBreak,
4618
+ /// breaksToLabel) give it nothing. Zig's comptime-false folding makes the
4619
+ /// same call on the emitted text, so the two terminality judgments stay
4620
+ /// aligned. The arm still EMITS — Zig compiles `if (false)` fine — only
4621
+ /// the flow accounting skips it.
4622
+ ///
4623
+ /// The split among the statement walkers is by QUESTION, not by walker:
4624
+ /// - FLOW-SEMANTICS walks (what can execute) exclude, per the above.
4625
+ /// - EMISSION-SHAPE walks keep counting excluded arms, because the
4626
+ /// arm's TEXT still emits: labelReferenced (a dead `break outer`
4627
+ /// still spells `break :outer` — Zig's unused-label check is
4628
+ /// syntactic, so the label must stay and stays used) and
4629
+ /// bindsContinue (the do-while first-pass-flag form must host any
4630
+ /// `continue` the body emits, dead or not — the plain trailing-test
4631
+ /// lowering has no valid spelling for that text).
4632
+ ///
4633
+ /// Only the bare `true`/`false` keywords qualify, pinned against the
4634
+ /// checker provider: a `const NEVER = false` alias condition WIDENS
4635
+ /// under tsc, so a reference never excludes. A do-while(false) body is
4636
+ /// never excluded either — the test runs AFTER the body, so the body
4637
+ /// executes once and tsc counts its assignments. A `for (;;)` with an
4638
+ /// OMITTED condition is the opposite judgment — an infinite loop
4639
+ /// (alwaysExits) — and never lands here: literal `false` ≠ omitted.
4640
+ private tscExcludedArm(construct: ts.Node, arm: ts.Node | undefined): boolean {
4641
+ if (arm === undefined) return false;
4642
+ if (ts.isIfStatement(construct)) {
4643
+ if (construct.expression.kind === ts.SyntaxKind.FalseKeyword) return arm === construct.thenStatement;
4644
+ if (construct.expression.kind === ts.SyntaxKind.TrueKeyword) return arm === construct.elseStatement;
4645
+ return false;
4646
+ }
4647
+ if (ts.isForStatement(construct)) {
4648
+ return (
4649
+ construct.condition !== undefined &&
4650
+ construct.condition.kind === ts.SyntaxKind.FalseKeyword &&
4651
+ (arm === construct.statement || arm === construct.incrementor)
4652
+ );
4653
+ }
4654
+ return (
4655
+ ts.isWhileStatement(construct) &&
4656
+ construct.expression.kind === ts.SyntaxKind.FalseKeyword &&
4657
+ arm === construct.statement
4658
+ );
4659
+ }
4660
+
4661
+ /// The narrows dead at a finally block's entry: tsc types a finally from
4662
+ /// the pre-try state minus every key the try or catch body may assign
4663
+ /// null/undefined to — path-insensitively, because an exception can hand
4664
+ /// control to the finally from between any two statements, so a later
4665
+ /// non-null re-assignment does not revive the narrow there. A provably
4666
+ /// non-null assignment keeps a live-slot `.?` spelling (it reads the
4667
+ /// variable, never a stale value; valid at every interruption point,
4668
+ /// since the slot holds the guarded value before the write and the
4669
+ /// non-null replacement after it). A capture spelling still drops —
4670
+ /// defensively: every capture-binding construct declines the capture
4671
+ /// form when its scope assigns the target (captureServesBranch and the
4672
+ /// exit-guard's assignsTarget check), so a capture live here never has
4673
+ /// an assignment to survive.
4674
+ ///
4675
+ /// The scan counts exactly the assignments tsc's CFA counts — killing a
4676
+ /// key tsc keeps strips a substitution the finally's reads were typed
4677
+ /// against and emits member access on a raw optional, invalid Zig. Two
4678
+ /// exclusions, both pinned against the checker provider:
4679
+ /// - code under a KEYWORD-LITERAL constant condition tsc treats as
4680
+ /// unreachable never counts (tscExcludedArm — the same judgment the
4681
+ /// branch-join layer applies): `if (false) ...`, the else of
4682
+ /// `if (true) ...`, a `while (false)` body, and the right side of
4683
+ /// `false && ...` / `true || ...` all keep the finally narrowed
4684
+ /// (probed). Only the bare keywords qualify — a `const NEVER = false`
4685
+ /// alias condition WIDENS under tsc (probed), and it still walks here;
4686
+ /// the same keyword-only judgment alwaysExits applies to constant-true
4687
+ /// loops. Anything else (do-while, non-literal conditions) stays on
4688
+ /// the conservative path-insensitive walk.
4689
+ /// - nested function/callback bodies never count (the throwsWithin skip
4690
+ /// idiom): tsc keeps the finally narrowed even when a callback DEFINED
4691
+ /// in the try assigns the target — called there or not (probed) — so
4692
+ /// counting those assignments would kill a narrow tsc typed the
4693
+ /// finally's reads with.
4694
+ /// Real conditional assignments (`if (flag) p = null`) still count: tsc
4695
+ /// widens for any reachable may-assign, whatever the path condition.
4696
+ private finallyEntryKills(stmt: ts.TryStatement, ctx: Ctx): Set<string> {
4697
+ const kills = new Set<string>();
4698
+ const visit = (n: ts.Node): void => {
4699
+ if (ts.isArrowFunction(n) || ts.isFunctionExpression(n) || ts.isFunctionDeclaration(n)) return;
4700
+ if (ts.isIfStatement(n)) {
4701
+ if (this.tscExcludedArm(n, n.thenStatement)) {
4702
+ if (n.elseStatement) visit(n.elseStatement);
4703
+ return;
4704
+ }
4705
+ if (n.elseStatement && this.tscExcludedArm(n, n.elseStatement)) {
4706
+ visit(n.thenStatement);
4707
+ return;
4708
+ }
4709
+ }
4710
+ if (ts.isWhileStatement(n) && this.tscExcludedArm(n, n.statement)) return;
4711
+ if (ts.isForStatement(n) && this.tscExcludedArm(n, n.statement)) {
4712
+ // `for (<init>; false; <inc>) <body>`: the initializer still runs
4713
+ // once (tsc counts its assignments); the bare-false condition holds
4714
+ // nothing to count; the body and the incrementor are excluded — the
4715
+ // incrementor runs only after a body iteration that never happens.
4716
+ if (n.initializer) visit(n.initializer);
4717
+ return;
4718
+ }
4719
+ if (ts.isBinaryExpression(n)) {
4720
+ const op = n.operatorToken.kind;
4721
+ if (op === ts.SyntaxKind.AmpersandAmpersandToken && n.left.kind === ts.SyntaxKind.FalseKeyword) return;
4722
+ if (op === ts.SyntaxKind.BarBarToken && n.left.kind === ts.SyntaxKind.TrueKeyword) return;
4723
+ }
4724
+ if (ts.isBinaryExpression(n) && n.operatorToken.kind === ts.SyntaxKind.EqualsToken) {
4725
+ const key = this.narrowKey(n.left);
4726
+ if (key !== null) {
4727
+ const subst = ctx.memberSubst.get(key);
4728
+ const empties = this.tast.emptiesOf(n.right);
4729
+ const mayBeEmpty = empties.null || empties.undefined;
4730
+ const survives = subst !== undefined && subst.endsWith(".?") && !mayBeEmpty;
4731
+ if (!survives && (subst !== undefined || mayBeEmpty)) kills.add(key);
4732
+ }
4733
+ }
4734
+ ts.forEachChild(n, visit);
4735
+ };
4736
+ visit(stmt.tryBlock);
4737
+ if (stmt.catchClause) visit(stmt.catchClause.block);
4738
+ return kills;
4739
+ }
4740
+
3308
4741
  private emitTryCore(stmt: ts.TryStatement, ctx: Ctx): void {
3309
4742
  const cc = stmt.catchClause;
3310
4743
  if (!cc) {
3311
- // try/finally: throws propagate past this construct (the defer runs).
4744
+ // try/finally: throws propagate past this construct (the defer runs
4745
+ // first) to ctx's handler — the caller when ctx.tryLabel is null, an
4746
+ // enclosing catch otherwise. No catch fallthrough is added HERE, so
4747
+ // kill dropping inherits ctx.tryLabel/ctx.catchResumes unchanged:
4748
+ // the inherited flags already answer for whichever handler a throw
4749
+ // reaches, and a body ending in `return` may still drop its kills
4750
+ // when nothing up the chain can resume past a merge.
3312
4751
  this.push(ctx, `{`);
3313
4752
  const sub = this.nestedCtx(ctx);
3314
4753
  this.emitBlockStatements(stmt.tryBlock.statements, sub);
@@ -3335,10 +4774,46 @@ export class Emitter {
3335
4774
  this.push(outer, `${body}: {`);
3336
4775
  const inner = this.nestedCtx(outer);
3337
4776
  inner.tryLabel = body;
4777
+ // The body's kills may only drop when no exception path can resume
4778
+ // past this try: a catch that falls through re-enters the merge
4779
+ // carrying whatever a mid-body throw killed. A catch closes every such
4780
+ // path only when EVERY route out of it leaves the function — asked
4781
+ // against ctx, not the body label, because the catch's own throws
4782
+ // break to ctx's enclosing handler — and then it also closes paths
4783
+ // from any try nested in this body, so the flag is overwritten rather
4784
+ // than or-ed with the inherited value.
4785
+ inner.catchResumes = !this.allRoutesLeaveFunction(cc.block.statements, {
4786
+ returnLeaves: ctx.retLabel === null,
4787
+ throwResumes: ctx.catchResumes === true,
4788
+ });
4789
+ // Fresh pending set for THIS try: kills routed here rode throw edges
4790
+ // into this catch (popNarrowKillFrame's route form) and apply at
4791
+ // the post-try merge below. A nested try's body re-derives its own set,
4792
+ // so kills always land at the same destination the throw route resolves
4793
+ // to; the catch block itself inherits the ENCLOSING set through ctx
4794
+ // (its throws escape outward, never back into this try).
4795
+ const pendingKills = new Set<string>();
4796
+ inner.pendingCatchKills = pendingKills;
3338
4797
  this.emitBlockStatements(stmt.tryBlock.statements, inner);
3339
4798
  if (done !== null) this.push(inner, `break :${done};`);
3340
4799
  outer.lines.push(...inner.lines);
3341
4800
  this.push(outer, `}`);
4801
+ // Exception-kills handoff: kills travel the same edges control does,
4802
+ // and the routes that fed this set are throws that land in THIS catch
4803
+ // — so they enter as the catch's INPUT state (tsc types the catch from
4804
+ // the state at the throw points: a narrowing an always-throwing arm
4805
+ // killed before throwing is dead inside the catch) and then follow the
4806
+ // catch's own routes out, via the catch list's kill-frame routing. A
4807
+ // catch that falls through carries them to the post-try continuation;
4808
+ // a catch that breaks/continues stages them at that edge's landing
4809
+ // point; a catch whose every route leaves the function drops them —
4810
+ // the post-try continuation is then reached only by clean paths, where
4811
+ // tsc keeps the narrow, so applying them there unconditionally would
4812
+ // poison the normal fallthrough. The body's normal-exit kills already
4813
+ // applied at the body's own merge just above, so the catch also sees
4814
+ // those (tsc-correct too: a mid-body throw can follow any fall-through
4815
+ // assignment). They never touch the intra-try flow already emitted
4816
+ // above.
3342
4817
  const catchCtx: Ctx = { ...outer, lines: [] };
3343
4818
  if (cc.variableDeclaration && ts.isIdentifier(cc.variableDeclaration.name)) {
3344
4819
  if (this.identifierUsed(cc.block, cc.variableDeclaration)) {
@@ -3347,7 +4822,7 @@ export class Emitter {
3347
4822
  this.push(catchCtx, `const ${ename} = thrown_payload;`);
3348
4823
  }
3349
4824
  }
3350
- this.emitBlockStatements(cc.block.statements, catchCtx);
4825
+ this.emitBlockStatements(cc.block.statements, catchCtx, undefined, pendingKills);
3351
4826
  outer.lines.push(...catchCtx.lines);
3352
4827
  ctx.lines.push(...outer.lines);
3353
4828
  this.push(ctx, `}`);
@@ -3394,18 +4869,32 @@ export class Emitter {
3394
4869
  const cond = this.emitExpr(stmt.expression, ctx, { k: "bool" }).code;
3395
4870
  if (ctx.lines.length !== before) this.fail(stmt, "while-condition requiring lowered statements");
3396
4871
  const body = ts.isBlock(stmt.statement) ? stmt.statement.statements : [stmt.statement];
4872
+ // A `while (false)` body is statically unreachable to tsc's CFA
4873
+ // (tscExcludedArm), so its kills never reach the post-loop state —
4874
+ // merging them would strip a narrow tsc typed the fall-through reads
4875
+ // with. The body still emits; only the flow bookkeeping skips.
4876
+ const deadBody = this.tscExcludedArm(stmt, stmt.statement);
3397
4877
  if (label === null && body.length === 1 && this.isSimpleAssignment(body[0])) {
4878
+ // Probe in a flow scope (see childCtx): taken, the assignment's
4879
+ // kills apply below exactly as a merge would; discarded, the full
4880
+ // body re-emission repeats them.
4881
+ const bodyJoin = new Set<string>();
3398
4882
  const sub = this.childCtx(ctx);
3399
4883
  sub.indent = 0;
3400
- this.emitStatement(body[0], sub);
4884
+ this.withNarrowScope(ctx, "merge", () => this.emitStatement(body[0], sub), bodyJoin);
3401
4885
  if (sub.lines.length === 1) {
3402
4886
  this.push(ctx, `while (${cond}) ${sub.lines[0].trim()}`);
4887
+ this.applyJoinedNarrowKills(ctx, deadBody ? new Set() : bodyJoin);
3403
4888
  return;
3404
4889
  }
3405
4890
  }
3406
4891
  this.push(ctx, `${head} (${cond}) {`);
3407
4892
  const sub = this.nestedCtx(ctx);
3408
- this.emitBlockStatements(body, sub);
4893
+ if (deadBody) {
4894
+ this.withNarrowScope(ctx, "drop", () => this.emitBlockStatements(body, sub));
4895
+ } else {
4896
+ this.emitBlockStatements(body, sub);
4897
+ }
3409
4898
  ctx.lines.push(...sub.lines);
3410
4899
  this.push(ctx, `}`);
3411
4900
  }
@@ -3422,15 +4911,26 @@ export class Emitter {
3422
4911
  if (!this.bindsContinue(stmt.statement, label)) {
3423
4912
  this.push(ctx, `${head} (true) {`);
3424
4913
  const sub = this.nestedCtx(ctx);
3425
- this.emitBlockStatements(body, sub);
4914
+ // tsc evaluates the do-while condition AFTER the body and carries the
4915
+ // body's flow state into it — a terminal guard in the body narrows
4916
+ // the trailing test. The body and the lowered `if (!(cond)) break;`
4917
+ // therefore emit inside ONE narrowing scope (the `trailing` hook),
4918
+ // restored only at the loop boundary: a restore between them would
4919
+ // strip the narrow before the read it covers. Iteration-entry state
4920
+ // is not at risk — the test is the last text in the loop body, so
4921
+ // nothing emits under its narrows past the back edge, and the
4922
+ // restore still runs before the post-loop continuation.
3426
4923
  // A body that always exits never reaches the test in JS either; the
3427
4924
  // emitted trailing test would be Zig unreachable-code.
3428
- if (!this.alwaysExits(stmt.statement)) {
3429
- const before = sub.lines.length;
3430
- const cond = this.emitExpr(stmt.expression, sub, { k: "bool" }).code;
3431
- if (sub.lines.length !== before) this.fail(stmt, "do-while condition requiring lowered statements");
3432
- this.push(sub, `if (!(${cond})) break;`);
3433
- }
4925
+ const trailing = this.alwaysExits(stmt.statement)
4926
+ ? undefined
4927
+ : (): void => {
4928
+ const before = sub.lines.length;
4929
+ const cond = this.emitExpr(stmt.expression, sub, { k: "bool" }).code;
4930
+ if (sub.lines.length !== before) this.fail(stmt, "do-while condition requiring lowered statements");
4931
+ this.push(sub, `if (!(${cond})) break;`);
4932
+ };
4933
+ this.emitBlockStatements(body, sub, undefined, undefined, trailing);
3434
4934
  ctx.lines.push(...sub.lines);
3435
4935
  this.push(ctx, `}`);
3436
4936
  return;
@@ -3450,7 +4950,17 @@ export class Emitter {
3450
4950
 
3451
4951
  /// Whether any `break`/`continue` under `body` names this label (JS
3452
4952
  /// allows an unreferenced label; Zig rejects one, so it must drop).
3453
- /// Duplicate nested labels cannot shadow — tsc rejects them.
4953
+ /// Duplicate nested labels cannot shadow on one nesting path — tsc
4954
+ /// rejects them — but labels are FUNCTION-scoped: a nested function may
4955
+ /// legally reuse the name for a label of its own, and its `break`/
4956
+ /// `continue` binds that inner label, never this one. The walk stops at
4957
+ /// function boundaries (the breaksToLabel rule), or a reuse would keep a
4958
+ /// Zig label emitted that nothing in THIS function consumes — an
4959
+ /// unused-label error.
4960
+ /// An EMISSION-SHAPE walk: tsc-excluded arms deliberately COUNT here
4961
+ /// (contrast the flow walks — see tscExcludedArm). A dead `break outer`
4962
+ /// still emits as `break :outer`, and Zig's unused-label check is
4963
+ /// syntactic, so the label must stay emitted and stays used.
3454
4964
  private labelReferenced(body: ts.Node, name: string): boolean {
3455
4965
  let found = false;
3456
4966
  const visit = (n: ts.Node): void => {
@@ -3459,6 +4969,7 @@ export class Emitter {
3459
4969
  found = true;
3460
4970
  return;
3461
4971
  }
4972
+ if (ts.isFunctionLike(n)) return;
3462
4973
  ts.forEachChild(n, visit);
3463
4974
  };
3464
4975
  visit(body);
@@ -3467,7 +4978,15 @@ export class Emitter {
3467
4978
 
3468
4979
  /// Whether a loop body contains a `continue` that binds to THIS loop: an
3469
4980
  /// unlabeled one outside any nested loop, or a labeled one naming this
3470
- /// loop's label.
4981
+ /// loop's label. Labels are function-scoped, so the walk stops at
4982
+ /// function boundaries (the breaksToLabel rule): a nested function may
4983
+ /// legally reuse the label name for a labeled loop of its own, and its
4984
+ /// `continue` binds that inner loop, never this one.
4985
+ /// An EMISSION-SHAPE walk: tsc-excluded arms deliberately COUNT here
4986
+ /// (contrast the flow walks — see tscExcludedArm). Both consumers pick
4987
+ /// the do-while lowering form, and a dead `continue` still EMITS — only
4988
+ /// the first-pass-flag form gives that text a spelling whose jump
4989
+ /// semantics match JS.
3471
4990
  private bindsContinue(body: ts.Node, label: string | null): boolean {
3472
4991
  let found = false;
3473
4992
  const visit = (n: ts.Node, insideNested: boolean): void => {
@@ -3480,6 +4999,7 @@ export class Emitter {
3480
4999
  }
3481
5000
  return;
3482
5001
  }
5002
+ if (ts.isFunctionLike(n)) return;
3483
5003
  const nested =
3484
5004
  insideNested ||
3485
5005
  ts.isWhileStatement(n) ||
@@ -3487,14 +5007,117 @@ export class Emitter {
3487
5007
  ts.isForStatement(n) ||
3488
5008
  ts.isForOfStatement(n) ||
3489
5009
  ts.isForInStatement(n);
3490
- // Callbacks cannot `continue` an outer loop (tsc rejects it), so
3491
- // function boundaries need no special casing here.
3492
5010
  ts.forEachChild(n, (c) => visit(c, nested));
3493
5011
  };
3494
5012
  visit(body, false);
3495
5013
  return found;
3496
5014
  }
3497
5015
 
5016
+ /// Whether an unlabeled `break` statement binds a `switch` rather than a
5017
+ /// loop: the nearest enclosing loop-or-switch, walking out of the break,
5018
+ /// is a switch. (tsc already rejects a break with neither.)
5019
+ private breakBindsEnclosingSwitch(stmt: ts.BreakStatement): boolean {
5020
+ let cur: ts.Node | undefined = stmt.parent;
5021
+ while (cur) {
5022
+ if (
5023
+ ts.isWhileStatement(cur) ||
5024
+ ts.isDoStatement(cur) ||
5025
+ ts.isForStatement(cur) ||
5026
+ ts.isForOfStatement(cur) ||
5027
+ ts.isForInStatement(cur) ||
5028
+ ts.isFunctionLike(cur)
5029
+ ) {
5030
+ return false;
5031
+ }
5032
+ if (ts.isSwitchStatement(cur)) return true;
5033
+ cur = cur.parent;
5034
+ }
5035
+ return false;
5036
+ }
5037
+
5038
+ /// Whether a `break` inside this switch's clauses (or this loop's body)
5039
+ /// binds the switch/loop itself: an unlabeled one outside any nested
5040
+ /// loop or switch, or a labeled one naming a label wrapped directly
5041
+ /// around this statement. Such a break resumes right AFTER the
5042
+ /// statement — the switch/loop falls through.
5043
+ /// Labels are function-scoped in JS, so the walk stops at function
5044
+ /// boundaries (the breaksToLabel rule): a nested helper may legally
5045
+ /// reuse a wrapping label's name for a label of its own, and its `break`
5046
+ /// binds the helper's label, never this construct — counting it read a
5047
+ /// constant-true loop as fallible and merged branch kills tsc keeps.
5048
+ /// This is a FLOW-SEMANTICS walk (it feeds alwaysExits' terminality,
5049
+ /// which mirrors tsc's CFA): a break under a tsc-excluded arm is not an
5050
+ /// edge the CFA can take, so it never counts (tscExcludedArm — Zig's
5051
+ /// comptime-false folding reads the emitted text the same way).
5052
+ private bindsBreak(
5053
+ stmt: ts.SwitchStatement | ts.WhileStatement | ts.DoStatement | ts.ForStatement,
5054
+ ): boolean {
5055
+ const wrappingLabels = new Set<string>();
5056
+ let p: ts.Node | undefined = stmt.parent;
5057
+ while (p && ts.isLabeledStatement(p)) {
5058
+ wrappingLabels.add(p.label.text);
5059
+ p = p.parent;
5060
+ }
5061
+ let found = false;
5062
+ const visit = (n: ts.Node, insideNested: boolean): void => {
5063
+ if (found) return;
5064
+ if (ts.isBreakStatement(n)) {
5065
+ if (n.label) {
5066
+ if (wrappingLabels.has(n.label.text)) found = true;
5067
+ } else if (!insideNested) {
5068
+ found = true;
5069
+ }
5070
+ return;
5071
+ }
5072
+ if (ts.isFunctionLike(n)) return;
5073
+ const nested =
5074
+ insideNested ||
5075
+ ts.isWhileStatement(n) ||
5076
+ ts.isDoStatement(n) ||
5077
+ ts.isForStatement(n) ||
5078
+ ts.isForOfStatement(n) ||
5079
+ ts.isForInStatement(n) ||
5080
+ ts.isSwitchStatement(n);
5081
+ ts.forEachChild(n, (c) => {
5082
+ if (!this.tscExcludedArm(n, c)) visit(c, nested);
5083
+ });
5084
+ };
5085
+ if (ts.isSwitchStatement(stmt)) {
5086
+ ts.forEachChild(stmt.caseBlock, (c) => visit(c, false));
5087
+ } else {
5088
+ // Loop heads hold no break (tsc rejects one there); only the body
5089
+ // can bind this loop.
5090
+ visit(stmt.statement, false);
5091
+ }
5092
+ return found;
5093
+ }
5094
+
5095
+ /// Whether any `break` naming `label` sits inside `node`. Function
5096
+ /// boundaries stop the walk: a labeled break cannot cross one (tsc
5097
+ /// rejects it), and a nested function may legally reuse the label name
5098
+ /// for a labeled statement of its own. tsc rejects duplicate labels on
5099
+ /// the same nesting path, so no inner rebinding can shadow `label`.
5100
+ /// A FLOW-SEMANTICS walk like bindsBreak (it feeds alwaysExits' labeled
5101
+ /// terminality): a labeled break under a tsc-excluded arm never counts
5102
+ /// (tscExcludedArm). Contrast labelReferenced, the EMISSION-SHAPE twin
5103
+ /// that must keep counting.
5104
+ private breaksToLabel(node: ts.Node, label: string): boolean {
5105
+ let found = false;
5106
+ const visit = (n: ts.Node): void => {
5107
+ if (found) return;
5108
+ if (ts.isBreakStatement(n)) {
5109
+ if (n.label !== undefined && n.label.text === label) found = true;
5110
+ return;
5111
+ }
5112
+ if (ts.isFunctionLike(n)) return;
5113
+ ts.forEachChild(n, (c) => {
5114
+ if (!this.tscExcludedArm(n, c)) visit(c);
5115
+ });
5116
+ };
5117
+ visit(node);
5118
+ return found;
5119
+ }
5120
+
3498
5121
  private isSimpleAssignment(stmt: ts.Statement): boolean {
3499
5122
  if (!ts.isExpressionStatement(stmt)) return false;
3500
5123
  const e = stmt.expression;
@@ -3596,8 +5219,11 @@ export class Emitter {
3596
5219
  this.push(ctx, `${varKw} ${name} = ${seed.code};`);
3597
5220
  this.push(ctx, `var ${lenVar}: usize = ${name}.len;`);
3598
5221
  }
3599
- ctx.memberSubst.set(decl.name.text, `${name}[0..${lenVar}]`);
3600
- ctx.memberSubst.set(`${decl.name.text}.length`, `@as(i64, @intCast(${lenVar}))`);
5222
+ const declKey = this.narrowKey(decl.name);
5223
+ if (declKey !== null) {
5224
+ ctx.memberSubst.set(declKey, `${name}[0..${lenVar}]`);
5225
+ ctx.memberSubst.set(`${declKey}.length`, `@as(i64, @intCast(${lenVar}))`);
5226
+ }
3601
5227
  return;
3602
5228
  }
3603
5229
  if (sliceT.k === "slice" && ts.isArrayLiteralExpression(init) && init.elements.length === 0) {
@@ -3625,7 +5251,10 @@ export class Emitter {
3625
5251
  if (v.code === name) return; // lowered directly into a named temp
3626
5252
  const annotation = this.varAnnotation(decl, t, reassigned, ctx);
3627
5253
  this.push(ctx, `${kw} ${name}${annotation} = ${v.code};`);
3628
- if (v.filterLen) ctx.memberSubst.set(`${decl.name.text}.length`, `@as(i64, @intCast(${v.filterLen}))`);
5254
+ if (v.filterLen) {
5255
+ const declKey = this.narrowKey(decl.name);
5256
+ if (declKey !== null) ctx.memberSubst.set(`${declKey}.length`, `@as(i64, @intCast(${v.filterLen}))`);
5257
+ }
3629
5258
  }
3630
5259
 
3631
5260
  /// R6b: `const { total, done: doneCount } = stats;` — record-field
@@ -3765,10 +5394,19 @@ export class Emitter {
3765
5394
  const exit = this.singleExitText(stmt.thenStatement, ctx);
3766
5395
  if (exit !== null) {
3767
5396
  this.push(ctx, `if (${base} != .${zigId(tag)}) ${exit}`);
3768
- const t = this.zTypeOfExpr(cond.left.expression, ctx);
3769
- if (t.k === "union") this.narrowUnion(cond.left.expression, t.name, tag, ctx);
3770
- return;
5397
+ } else {
5398
+ // Multi-statement exits (a throw is always two emitted statements)
5399
+ // keep the guard's narrowing through the block form.
5400
+ this.push(ctx, `if (${base} != .${zigId(tag)}) {`);
5401
+ const sub = this.nestedCtx(ctx);
5402
+ const exitStmts = ts.isBlock(stmt.thenStatement) ? stmt.thenStatement.statements : [stmt.thenStatement];
5403
+ this.emitBlockStatements(exitStmts, sub);
5404
+ ctx.lines.push(...sub.lines);
5405
+ this.push(ctx, `}`);
3771
5406
  }
5407
+ const t = this.zTypeOfExpr(cond.left.expression, ctx);
5408
+ if (t.k === "union") this.narrowUnion(cond.left.expression, t.name, tag, ctx);
5409
+ return;
3772
5410
  }
3773
5411
 
3774
5412
  // R7: `if (x === null) <exit>` -> `const v = x orelse <exit>;` for
@@ -3784,19 +5422,56 @@ export class Emitter {
3784
5422
  const t = this.zTypeOfExpr(exitTest.target, ctx);
3785
5423
  if (t.k === "optional") {
3786
5424
  const exit = this.singleExitText(stmt.thenStatement, ctx);
3787
- if (exit !== null) {
5425
+ // A guard whose narrowed value the rest of the scope never reads
5426
+ // must not bind a capture — an unused Zig const is a compile
5427
+ // error — so it stays a plain null test (one-statement exits
5428
+ // here; multi-statement unread exits ride the generic arm below).
5429
+ if (!this.followingReadsTarget(stmt, exitTest.target)) {
5430
+ if (exit !== null) {
5431
+ this.requireFaithfulEmptyTest(exitTest.target, exitTest.flavor, cond);
5432
+ const prop = this.emitExpr(exitTest.target, ctx).code;
5433
+ this.push(ctx, `if (${prop} == null) ${exit}`);
5434
+ return;
5435
+ }
5436
+ } else {
3788
5437
  this.requireFaithfulEmptyTest(exitTest.target, exitTest.flavor, cond);
3789
5438
  const prop = this.emitExpr(exitTest.target, ctx).code;
3790
- // A guard whose narrowed value the rest of the scope never reads
3791
- // must not bind a capture — an unused Zig const is a compile
3792
- // error — so it stays a plain null test.
3793
- if (!this.followingReadsTarget(stmt, exitTest.target)) {
3794
- this.push(ctx, `if (${prop} == null) ${exit}`);
5439
+ // A reassigned target cannot narrow through a capture (the capture
5440
+ // goes stale at the assignment): keep the plain null test and
5441
+ // install the `.?` spelling, whose reads see the live variable and
5442
+ // which the assignment path keeps alive across provably non-null
5443
+ // writes.
5444
+ if (this.assignsTarget([...this.followingStatementsOf(stmt)], exitTest.target)) {
5445
+ if (exit !== null) {
5446
+ this.push(ctx, `if (${prop} == null) ${exit}`);
5447
+ } else {
5448
+ this.push(ctx, `if (${prop} == null) {`);
5449
+ const sub = this.nestedCtx(ctx);
5450
+ const exitStmts = ts.isBlock(stmt.thenStatement) ? stmt.thenStatement.statements : [stmt.thenStatement];
5451
+ this.emitBlockStatements(exitStmts, sub);
5452
+ ctx.lines.push(...sub.lines);
5453
+ this.push(ctx, `}`);
5454
+ }
5455
+ const exitKey = this.narrowKey(exitTest.target);
5456
+ if (exitKey !== null) ctx.memberSubst.set(exitKey, `${prop}.?`);
3795
5457
  return;
3796
5458
  }
3797
5459
  const name = this.freshName(ctx, this.narrowHint(exitTest.target));
3798
- this.push(ctx, `const ${name} = ${prop} orelse ${exit}`);
3799
- ctx.memberSubst.set(normalize(exitTest.target), name);
5460
+ if (exit !== null) {
5461
+ this.push(ctx, `const ${name} = ${prop} orelse ${exit}`);
5462
+ } else {
5463
+ // Multi-statement exits (a throw is always two emitted
5464
+ // statements) take the block form; the block never falls
5465
+ // through, so Zig types it noreturn and the unwrap holds.
5466
+ this.push(ctx, `const ${name} = ${prop} orelse {`);
5467
+ const sub = this.nestedCtx(ctx);
5468
+ const exitStmts = ts.isBlock(stmt.thenStatement) ? stmt.thenStatement.statements : [stmt.thenStatement];
5469
+ this.emitBlockStatements(exitStmts, sub);
5470
+ ctx.lines.push(...sub.lines);
5471
+ this.push(ctx, `};`);
5472
+ }
5473
+ const exitKey = this.narrowKey(exitTest.target);
5474
+ if (exitKey !== null) ctx.memberSubst.set(exitKey, name);
3800
5475
  return;
3801
5476
  }
3802
5477
  }
@@ -3813,30 +5488,59 @@ export class Emitter {
3813
5488
  this.branchReadsTarget(stmt.elseStatement, exitTest.target)
3814
5489
  ) {
3815
5490
  const t = this.zTypeOfExpr(exitTest.target, ctx);
3816
- if (t.k === "optional") {
5491
+ const key = this.narrowKey(exitTest.target);
5492
+ if (t.k === "optional" && key !== null) {
3817
5493
  this.requireFaithfulEmptyTest(exitTest.target, exitTest.flavor, cond);
3818
- const key = normalize(exitTest.target);
3819
5494
  const prop = this.emitExpr(exitTest.target, ctx).code;
3820
- const name = this.freshName(ctx, this.narrowHint(exitTest.target));
3821
- this.push(ctx, `if (${prop}) |${name}| {`);
3822
- const saved = ctx.memberSubst.get(key);
3823
- ctx.memberSubst.set(key, name);
3824
- const sub = this.nestedCtx(ctx);
5495
+ const join = new Set<string>();
3825
5496
  const hitBody = ts.isBlock(stmt.elseStatement) ? stmt.elseStatement.statements : [stmt.elseStatement];
3826
- this.emitBlockStatements(hitBody, sub);
3827
- ctx.lines.push(...sub.lines);
3828
- ctx.memberSubst.delete(key);
3829
- if (saved !== undefined) ctx.memberSubst.set(key, saved);
3830
- this.push(ctx, `} else {`);
3831
- const esub = this.nestedCtx(ctx);
3832
5497
  const missBody = ts.isBlock(stmt.thenStatement) ? stmt.thenStatement.statements : [stmt.thenStatement];
3833
- this.emitBlockStatements(missBody, esub);
3834
- ctx.lines.push(...esub.lines);
3835
- this.push(ctx, `}`);
5498
+ // A branch that reassigns the target before any read could
5499
+ // consume a capture takes the plain-test `.?` spelling instead
5500
+ // (see captureServesBranch) — a capture would bind unused or go
5501
+ // stale behind a join.
5502
+ if (this.captureServesBranch(stmt.elseStatement, exitTest.target)) {
5503
+ const name = this.freshName(ctx, this.narrowHint(exitTest.target));
5504
+ this.push(ctx, `if (${prop}) |${name}| {`);
5505
+ const saved = ctx.memberSubst.get(key);
5506
+ ctx.memberSubst.set(key, name);
5507
+ const sub = this.nestedCtx(ctx);
5508
+ this.emitBlockStatements(hitBody, sub, join);
5509
+ ctx.lines.push(...sub.lines);
5510
+ ctx.memberSubst.delete(key);
5511
+ if (saved !== undefined) ctx.memberSubst.set(key, saved);
5512
+ this.push(ctx, `} else {`);
5513
+ const esub = this.nestedCtx(ctx);
5514
+ this.emitBlockStatements(missBody, esub, join);
5515
+ ctx.lines.push(...esub.lines);
5516
+ this.push(ctx, `}`);
5517
+ } else {
5518
+ this.push(ctx, `if (${prop} == null) {`);
5519
+ const esub = this.nestedCtx(ctx);
5520
+ this.emitBlockStatements(missBody, esub, join);
5521
+ ctx.lines.push(...esub.lines);
5522
+ this.push(ctx, `} else {`);
5523
+ const saved = ctx.memberSubst.get(key);
5524
+ ctx.memberSubst.set(key, `${prop}.?`);
5525
+ const sub = this.nestedCtx(ctx);
5526
+ this.emitBlockStatements(hitBody, sub, join);
5527
+ ctx.lines.push(...sub.lines);
5528
+ ctx.memberSubst.delete(key);
5529
+ if (saved !== undefined) ctx.memberSubst.set(key, saved);
5530
+ this.push(ctx, `}`);
5531
+ }
5532
+ this.applyJoinedNarrowKills(ctx, join);
3836
5533
  // A miss branch that always exits narrows everything AFTER the if
3837
5534
  // too (TS's control-flow narrowing): reads there unwrap through the
3838
5535
  // safety-checked `.?` — provably non-null, the miss path returned.
3839
- if (this.alwaysExits(stmt.thenStatement) && this.followingReadsTarget(stmt, exitTest.target)) {
5536
+ // UNLESS the surviving arm killed the target: tsc's post-if state
5537
+ // is the guard-implied narrow MINUS the joined kills, so a killed
5538
+ // key stays dead and the code after re-checks instead.
5539
+ if (
5540
+ !join.has(key) &&
5541
+ this.alwaysExits(stmt.thenStatement) &&
5542
+ this.followingReadsTarget(stmt, exitTest.target)
5543
+ ) {
3840
5544
  ctx.memberSubst.set(key, `${prop}.?`);
3841
5545
  }
3842
5546
  return;
@@ -3853,17 +5557,27 @@ export class Emitter {
3853
5557
  this.branchReadsTarget(stmt.thenStatement, presentTest.target)
3854
5558
  ) {
3855
5559
  const t = this.zTypeOfExpr(presentTest.target, ctx);
3856
- if (t.k === "optional") {
5560
+ const key = this.narrowKey(presentTest.target);
5561
+ if (t.k === "optional" && key !== null) {
3857
5562
  this.requireFaithfulEmptyTest(presentTest.target, presentTest.flavor, cond);
3858
- const key = normalize(presentTest.target);
3859
5563
  const prop = this.emitExpr(presentTest.target, ctx).code;
3860
- const name = this.freshName(ctx, this.narrowHint(presentTest.target));
5564
+ // A branch that reassigns the target before any read could
5565
+ // consume a capture takes the plain-test `.?` spelling instead
5566
+ // (see captureServesBranch) — a capture would bind unused or go
5567
+ // stale behind a join; `.?` reads always see the live slot.
5568
+ const liveCapture = this.captureServesBranch(stmt.thenStatement, presentTest.target);
5569
+ const name = liveCapture ? this.freshName(ctx, this.narrowHint(presentTest.target)) : `${prop}.?`;
3861
5570
  const single = unwrapSingle(stmt.thenStatement);
3862
- if (!stmt.elseStatement && single && ts.isReturnStatement(single)) {
5571
+ if (liveCapture && !stmt.elseStatement && single && ts.isReturnStatement(single)) {
3863
5572
  const saved = ctx.memberSubst.get(key);
3864
5573
  ctx.memberSubst.set(key, name);
5574
+ // Probe in a flow scope (see childCtx). Its kills discard both
5575
+ // ways: a lines-free probe processed no statements (nothing can
5576
+ // kill without lowering lines), and the discarded case re-emits
5577
+ // the branch below under the block path's own scope.
3865
5578
  const sub = this.childCtx(ctx);
3866
- const v = single.expression ? this.emitReturn(single.expression, sub) : null;
5579
+ const v = this.withNarrowScope(ctx, "merge", () =>
5580
+ single.expression ? this.emitReturn(single.expression, sub) : null, new Set());
3867
5581
  ctx.memberSubst.delete(key);
3868
5582
  if (saved !== undefined) ctx.memberSubst.set(key, saved);
3869
5583
  if (sub.lines.length === 0 && v) {
@@ -3871,12 +5585,13 @@ export class Emitter {
3871
5585
  return;
3872
5586
  }
3873
5587
  }
3874
- this.push(ctx, `if (${prop}) |${name}| {`);
5588
+ const join = new Set<string>();
5589
+ this.push(ctx, liveCapture ? `if (${prop}) |${name}| {` : `if (${prop} != null) {`);
3875
5590
  const saved = ctx.memberSubst.get(key);
3876
5591
  ctx.memberSubst.set(key, name);
3877
5592
  const sub = this.nestedCtx(ctx);
3878
5593
  const thenBody = ts.isBlock(stmt.thenStatement) ? stmt.thenStatement.statements : [stmt.thenStatement];
3879
- this.emitBlockStatements(thenBody, sub);
5594
+ this.emitBlockStatements(thenBody, sub, join);
3880
5595
  ctx.lines.push(...sub.lines);
3881
5596
  ctx.memberSubst.delete(key);
3882
5597
  if (saved !== undefined) ctx.memberSubst.set(key, saved);
@@ -3884,10 +5599,24 @@ export class Emitter {
3884
5599
  this.push(ctx, `} else {`);
3885
5600
  const esub = this.nestedCtx(ctx);
3886
5601
  const elseBody = ts.isBlock(stmt.elseStatement) ? stmt.elseStatement.statements : [stmt.elseStatement];
3887
- this.emitBlockStatements(elseBody, esub);
5602
+ this.emitBlockStatements(elseBody, esub, join);
3888
5603
  ctx.lines.push(...esub.lines);
3889
5604
  }
3890
5605
  this.push(ctx, `}`);
5606
+ this.applyJoinedNarrowKills(ctx, join);
5607
+ // An else branch that always exits narrows everything AFTER the if
5608
+ // too (the mirror of the R7-dual rule above): only the hit path
5609
+ // falls through, so reads there unwrap via the safety-checked `.?`
5610
+ // — unless that hit path killed the target (post-if state is the
5611
+ // narrow minus the joined kills; a killed key re-checks instead).
5612
+ if (
5613
+ !join.has(key) &&
5614
+ stmt.elseStatement &&
5615
+ this.alwaysExits(stmt.elseStatement) &&
5616
+ this.followingReadsTarget(stmt, presentTest.target)
5617
+ ) {
5618
+ ctx.memberSubst.set(key, `${prop}.?`);
5619
+ }
3891
5620
  return;
3892
5621
  }
3893
5622
  }
@@ -3909,20 +5638,31 @@ export class Emitter {
3909
5638
  const thenStmts = ts.isBlock(stmt.thenStatement) ? stmt.thenStatement.statements : [stmt.thenStatement];
3910
5639
  // Single-return then-branch without else stays on one line when short.
3911
5640
  if (!stmt.elseStatement && thenStmts.length === 1 && ts.isReturnStatement(thenStmts[0])) {
5641
+ // Probe in a flow scope (see childCtx). Its kills discard both ways:
5642
+ // a lines-free probe processed no statements, and the discarded case
5643
+ // re-emits the branch below under the block path's own scope.
3912
5644
  const sub = this.childCtx(ctx);
3913
5645
  const r = thenStmts[0];
3914
- const v = this.withKindNarrow(posGuard, ctx, () =>
5646
+ const v = this.withNarrowScope(ctx, "merge", () => this.withKindNarrow(posGuard, ctx, () =>
3915
5647
  r.expression ? this.emitReturn(r.expression, sub) : null,
3916
- );
5648
+ ), new Set());
3917
5649
  const text = this.returnText(ctx, v, r);
3918
5650
  if (sub.lines.length === 0 && condText.length + text.length <= 80) {
3919
5651
  this.push(ctx, `if (${condText}) ${text}`);
3920
5652
  return;
3921
5653
  }
3922
5654
  }
5655
+ const join = new Set<string>();
5656
+ // A tsc-unreachable arm (bare keyword-literal condition — see
5657
+ // tscExcludedArm) still emits, but contributes no kills to the join:
5658
+ // tsc's CFA excludes the arm, so a kill from it would strip a narrow
5659
+ // tsc typed the fall-through reads with (a raw optional read, invalid
5660
+ // Zig). Its kills feed a discarded set instead of the join.
5661
+ const discard = new Set<string>();
3923
5662
  this.push(ctx, `if (${condText}) {`);
3924
5663
  const sub = this.nestedCtx(ctx);
3925
- this.withKindNarrow(posGuard, ctx, () => this.emitBlockStatements(thenStmts, sub));
5664
+ const thenJoin = this.tscExcludedArm(stmt, stmt.thenStatement) ? discard : join;
5665
+ this.withKindNarrow(posGuard, ctx, () => this.emitBlockStatements(thenStmts, sub, thenJoin));
3926
5666
  ctx.lines.push(...sub.lines);
3927
5667
  if (stmt.elseStatement) {
3928
5668
  if (ts.isIfStatement(stmt.elseStatement)) {
@@ -3930,16 +5670,66 @@ export class Emitter {
3930
5670
  this.push(ctx, `} else ${""}`.trimEnd());
3931
5671
  // Rewrite: emit as `} else if (...) {` by recursing with a marker.
3932
5672
  ctx.lines.pop();
3933
- this.emitElseIf(stmt.elseStatement, ctx);
5673
+ this.emitElseIf(stmt.elseStatement, ctx, join);
5674
+ this.applyJoinedNarrowKills(ctx, join);
5675
+ // This exit path narrows like the common tail below: an exiting
5676
+ // empty-test arm at the HEAD of a chain still narrows everything
5677
+ // after the whole statement (the else-if arms ride the non-empty
5678
+ // path), and skipping it here left fall-through reads optional.
5679
+ this.applyPostIfNarrow(stmt, exitTest, presentTest, ctx, join);
3934
5680
  return;
3935
5681
  }
3936
5682
  this.push(ctx, `} else {`);
3937
5683
  const esub = this.nestedCtx(ctx);
3938
5684
  const elseStmts = ts.isBlock(stmt.elseStatement) ? stmt.elseStatement.statements : [stmt.elseStatement];
3939
- this.withKindNarrow(negGuard, ctx, () => this.emitBlockStatements(elseStmts, esub));
5685
+ const elseJoin = this.tscExcludedArm(stmt, stmt.elseStatement) ? discard : join;
5686
+ this.withKindNarrow(negGuard, ctx, () => this.emitBlockStatements(elseStmts, esub, elseJoin));
3940
5687
  ctx.lines.push(...esub.lines);
3941
5688
  }
3942
5689
  this.push(ctx, `}`);
5690
+ this.applyJoinedNarrowKills(ctx, join);
5691
+ this.applyPostIfNarrow(stmt, exitTest, presentTest, ctx, join);
5692
+ }
5693
+
5694
+ /// tsc narrows AFTER an if whose empty-testing arm always exits — only
5695
+ /// the non-empty path falls through. The tailored R7 paths in emitIf
5696
+ /// return for the shapes where an arm READS the target; these are the
5697
+ /// generic leftovers (the miss arm has an else — possibly a whole
5698
+ /// else-if chain — or no arm reads the target), so fall-through reads
5699
+ /// unwrap via the safety-checked `.?`. Every exit path from emitIf that
5700
+ /// finished emitting the statement must apply this — with the
5701
+ /// statement's just-joined kill set: tsc's post-if state is the
5702
+ /// guard-implied narrow MINUS the arms' kills, so a target a surviving
5703
+ /// arm killed stays dead (installing it anyway would resurrect the
5704
+ /// narrow the join buried, emitting a `.?` read or test against a slot
5705
+ /// that can be null again).
5706
+ private applyPostIfNarrow(
5707
+ stmt: ts.IfStatement,
5708
+ exitTest: { target: ts.Expression; flavor: "null" | "undefined" } | null,
5709
+ presentTest: { target: ts.Expression; flavor: "null" | "undefined" } | null,
5710
+ ctx: Ctx,
5711
+ join: ReadonlySet<string>,
5712
+ ): void {
5713
+ const postNarrow =
5714
+ (exitTest && this.alwaysExits(stmt.thenStatement) ? exitTest : null) ??
5715
+ (presentTest && stmt.elseStatement && this.alwaysExits(stmt.elseStatement) ? presentTest : null);
5716
+ if (
5717
+ postNarrow &&
5718
+ (ts.isPropertyAccessExpression(postNarrow.target) || ts.isIdentifier(postNarrow.target)) &&
5719
+ this.followingReadsTarget(stmt, postNarrow.target)
5720
+ ) {
5721
+ const key = this.narrowKey(postNarrow.target);
5722
+ if (key === null || join.has(key)) return;
5723
+ const t = this.zTypeOfExpr(postNarrow.target, ctx);
5724
+ const empties = this.tast.emptiesOf(postNarrow.target);
5725
+ // The unfaithful-empty spellings keep their R7c teaching on the
5726
+ // paths that emit tests; here the narrow just quietly declines.
5727
+ const faithful = postNarrow.flavor === "null" ? !empties.undefined : !empties.null;
5728
+ if (t.k === "optional" && faithful) {
5729
+ const code = this.emitExpr(postNarrow.target, ctx).code;
5730
+ ctx.memberSubst.set(key, `${code}.?`);
5731
+ }
5732
+ }
3943
5733
  }
3944
5734
 
3945
5735
  /// Capture-name hint for a narrowed optional target.
@@ -3949,50 +5739,143 @@ export class Emitter {
3949
5739
  return "opt";
3950
5740
  }
3951
5741
 
3952
- /// Whether a guarded branch reads its narrowed target — a Zig capture the
5742
+ /// Whether a guarded branch READS its narrowed target — a Zig capture the
3953
5743
  /// branch never uses would be an unused-capture error, so unread guards
3954
- /// keep the plain `!= null` comparison instead.
5744
+ /// keep the plain `!= null` comparison instead. A plain assignment's
5745
+ /// TARGET is not a read: the write goes to the raw slot, never the
5746
+ /// capture, so a write-only arm (a pure kill) must decline the capture
5747
+ /// form or the capture binds unused.
3955
5748
  private branchReadsTarget(branch: ts.Statement, target: ts.Expression): boolean {
3956
5749
  if (ts.isIdentifier(target)) {
3957
5750
  const decl = this.tast.declarationOf(target);
3958
- if (decl) return this.identifierUsed(branch, decl);
5751
+ if (decl) return this.identifierRead(branch, decl);
3959
5752
  }
3960
- return branch.getText().includes(target.getText());
5753
+ // Property chains compare by declaration-qualified key, never text —
5754
+ // a shadowed spelling in a nested callback is not a read (anyReadsKey).
5755
+ return this.anyReadsKey([branch], this.narrowKey(target));
5756
+ }
5757
+
5758
+ /// identifierUsed, minus references that are the bare TARGET of a plain
5759
+ /// `=` assignment (compound assignments and `++`/`--` read the slot and
5760
+ /// still count).
5761
+ private identifierRead(body: ts.Node, decl: ts.Node): boolean {
5762
+ let found = false;
5763
+ const visit = (n: ts.Node): void => {
5764
+ if (found) return;
5765
+ if (
5766
+ ts.isIdentifier(n) &&
5767
+ this.tast.declarationOf(n) === decl &&
5768
+ n.parent !== decl &&
5769
+ !(
5770
+ ts.isBinaryExpression(n.parent) &&
5771
+ n.parent.operatorToken.kind === ts.SyntaxKind.EqualsToken &&
5772
+ n.parent.left === n
5773
+ )
5774
+ ) {
5775
+ found = true;
5776
+ return;
5777
+ }
5778
+ ts.forEachChild(n, visit);
5779
+ };
5780
+ visit(body);
5781
+ return found;
3961
5782
  }
3962
5783
 
3963
5784
  /// Whether any statement AFTER an early-exit guard reads the guarded
3964
5785
  /// target — the scope a `const v = x orelse <exit>;` capture serves. An
3965
- /// unread capture would be an unused Zig const, a compile error. The
3966
- /// text match is boundary-aware so `model.now` never matches inside
3967
- /// `model.nowDurationMs`.
5786
+ /// unread capture would be an unused Zig const, a compile error.
5787
+ /// Property chains compare by declaration-qualified key (anyReadsKey),
5788
+ /// which is inherently boundary-aware — `model.now` is a different key
5789
+ /// from `model.nowDurationMs`, and a shadowed spelling in a nested
5790
+ /// callback is a different declaration.
3968
5791
  private followingReadsTarget(stmt: ts.IfStatement, target: ts.Expression): boolean {
5792
+ const following: ts.Node[] = [...this.followingStatementsOf(stmt)];
5793
+ // Flow off the end of a do-while body continues INTO the trailing
5794
+ // test (tsc evaluates the condition after the body), and the lowered
5795
+ // `if (!(cond)) break;` emits inside the body's narrowing scope — a
5796
+ // condition read is a read the guard's capture serves.
5797
+ const trailingTest = this.trailingDoWhileTestOf(stmt);
5798
+ if (trailingTest !== null) following.push(trailingTest);
5799
+ if (following.length === 0) return false;
5800
+ if (ts.isIdentifier(target)) {
5801
+ const decl = this.tast.declarationOf(target);
5802
+ if (decl) return following.some((s) => this.identifierUsed(s, decl));
5803
+ }
5804
+ return this.anyReadsKey(following, this.narrowKey(target));
5805
+ }
5806
+
5807
+ /// The statements after `stmt` in its own list — the scope an early-exit
5808
+ /// guard's narrowing serves. A plain lexical block is no flow boundary
5809
+ /// (emitStatement flattens it), so the walk continues past it: a guard at
5810
+ /// the end of such a block narrows the statements after the BLOCK,
5811
+ /// transitively out through enclosing plain blocks.
5812
+ private followingStatementsOf(stmt: ts.Statement): readonly ts.Statement[] {
3969
5813
  const parent = stmt.parent;
3970
- let following: readonly ts.Statement[] = [];
3971
5814
  if (ts.isBlock(parent) || ts.isSourceFile(parent) || ts.isCaseClause(parent) || ts.isDefaultClause(parent)) {
3972
5815
  const statements = parent.statements;
3973
5816
  const at = statements.indexOf(stmt);
3974
- if (at >= 0) following = statements.slice(at + 1);
5817
+ if (at >= 0) {
5818
+ const rest = statements.slice(at + 1);
5819
+ if (ts.isBlock(parent) && isPlainLexicalBlock(parent)) {
5820
+ return [...rest, ...this.followingStatementsOf(parent)];
5821
+ }
5822
+ return rest;
5823
+ }
3975
5824
  }
3976
- if (following.length === 0) return false;
3977
- if (ts.isIdentifier(target)) {
3978
- const decl = this.tast.declarationOf(target);
3979
- if (decl) return following.some((s) => this.identifierUsed(s, decl));
5825
+ return [];
5826
+ }
5827
+
5828
+ /// The do-while trailing test the flow after `stmt` runs into, when that
5829
+ /// test actually emits inside the body's narrowing scope — i.e. `stmt`
5830
+ /// sits in the body list (transitively through plain lexical blocks) of
5831
+ /// a do-while lowered to the `while (true)` + trailing-exit-test form.
5832
+ /// The first-pass-flag form (a body binding `continue`) hoists the test
5833
+ /// ahead of the body, where a body narrow's capture is out of scope, and
5834
+ /// an always-exiting body emits no test at all — both return null, so a
5835
+ /// guard read only by the condition binds no capture there (an unused
5836
+ /// Zig const is a compile error).
5837
+ private trailingDoWhileTestOf(stmt: ts.Statement): ts.Expression | null {
5838
+ let cur: ts.Statement = stmt;
5839
+ for (;;) {
5840
+ const parent: ts.Node = cur.parent;
5841
+ if (ts.isBlock(parent) && isPlainLexicalBlock(parent)) {
5842
+ cur = parent;
5843
+ continue;
5844
+ }
5845
+ const holder = ts.isBlock(parent) ? parent.parent : parent;
5846
+ if (!ts.isDoStatement(holder)) return null;
5847
+ // Mirror emitStatement's label derivation: the loop's Zig label
5848
+ // exists only when a labeled break/continue references it.
5849
+ const label =
5850
+ ts.isLabeledStatement(holder.parent) && this.labelReferenced(holder, holder.parent.label.text)
5851
+ ? loopLabel(holder.parent.label.text)
5852
+ : null;
5853
+ if (this.bindsContinue(holder.statement, label)) return null;
5854
+ if (this.alwaysExits(holder.statement)) return null;
5855
+ return holder.expression;
3980
5856
  }
3981
- const escaped = target.getText().replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3982
- const read = new RegExp(`${escaped}(?![A-Za-z0-9_$])`);
3983
- return following.some((s) => read.test(s.getText()));
3984
5857
  }
3985
5858
 
3986
- private emitElseIf(stmt: ts.IfStatement, ctx: Ctx): void {
5859
+ /// Every arm of the chain — each else-if body and the final else — is a
5860
+ /// SIBLING of the head if's then arm: its merge-class kills collect into
5861
+ /// the chain-wide `join` the head applies after the whole statement, so
5862
+ /// no arm emits against a preceding arm's kills (they are alternatives,
5863
+ /// not a sequence).
5864
+ private emitElseIf(stmt: ts.IfStatement, ctx: Ctx, join: Set<string>): void {
3987
5865
  // A chained condition that needs lowered statements cannot sit between
3988
5866
  // `}` and `else if`; open a plain else block and start a fresh if inside.
3989
- // The probe works on a copied name set so it burns no real names.
5867
+ // The probe works on a copied name set so it burns no real names, and
5868
+ // brackets in a flow scope (see childCtx) — both routes below re-emit
5869
+ // the condition for real.
3990
5870
  const probe: Ctx = { ...ctx, lines: [], used: new Set(ctx.used) };
3991
- this.emitExpr(stmt.expression, probe, { k: "bool" });
5871
+ this.withNarrowScope(ctx, "merge", () => this.emitExpr(stmt.expression, probe, { k: "bool" }), new Set());
3992
5872
  if (probe.lines.length > 0) {
3993
5873
  this.push(ctx, `} else {`);
3994
5874
  const inner = this.nestedCtx(ctx);
3995
- this.emitIf(stmt, inner);
5875
+ // The nested if is one arm of the enclosing chain: bracket it in a
5876
+ // flow scope so its narrows stay contained and its kills join with
5877
+ // its siblings' instead of applying mid-chain.
5878
+ this.withNarrowScope(ctx, "merge", () => this.emitIf(stmt, inner), join);
3996
5879
  ctx.lines.push(...inner.lines);
3997
5880
  this.push(ctx, `}`);
3998
5881
  return;
@@ -4001,17 +5884,19 @@ export class Emitter {
4001
5884
  this.push(ctx, `} else if (${condText}) {`);
4002
5885
  const sub = this.nestedCtx(ctx);
4003
5886
  const thenStmts = ts.isBlock(stmt.thenStatement) ? stmt.thenStatement.statements : [stmt.thenStatement];
4004
- this.emitBlockStatements(thenStmts, sub);
5887
+ // tsc-unreachable arms contribute no kills to the chain's join (see
5888
+ // emitIf's discard note; tscExcludedArm).
5889
+ this.emitBlockStatements(thenStmts, sub, this.tscExcludedArm(stmt, stmt.thenStatement) ? new Set() : join);
4005
5890
  ctx.lines.push(...sub.lines);
4006
5891
  if (stmt.elseStatement) {
4007
5892
  if (ts.isIfStatement(stmt.elseStatement)) {
4008
- this.emitElseIf(stmt.elseStatement, ctx);
5893
+ this.emitElseIf(stmt.elseStatement, ctx, join);
4009
5894
  return;
4010
5895
  }
4011
5896
  this.push(ctx, `} else {`);
4012
5897
  const esub = this.nestedCtx(ctx);
4013
5898
  const elseStmts = ts.isBlock(stmt.elseStatement) ? stmt.elseStatement.statements : [stmt.elseStatement];
4014
- this.emitBlockStatements(elseStmts, esub);
5899
+ this.emitBlockStatements(elseStmts, esub, this.tscExcludedArm(stmt, stmt.elseStatement) ? new Set() : join);
4015
5900
  ctx.lines.push(...esub.lines);
4016
5901
  }
4017
5902
  this.push(ctx, `}`);
@@ -4024,15 +5909,31 @@ export class Emitter {
4024
5909
  return text;
4025
5910
  }
4026
5911
 
5912
+ /// A guard's exit branch as ONE Zig statement (`return v;`, `break;`,
5913
+ /// `continue;`, labeled forms included), or null when it needs a block
5914
+ /// (multi-statement bodies; a throw always emits two statements).
4027
5915
  private singleExitText(stmt: ts.Statement, ctx: Ctx): string | null {
4028
5916
  const single = unwrapSingle(stmt);
4029
5917
  if (single && ts.isReturnStatement(single)) {
4030
5918
  if (!single.expression) return this.returnText(ctx, null, single);
5919
+ // Probe in a flow scope (see childCtx): a lines-free probe processed
5920
+ // no statements, so the discarded kill set is empty; a lines-bearing
5921
+ // probe is declined and the caller re-emits under its own scope.
4031
5922
  const sub = this.childCtx(ctx);
4032
- const v = this.emitReturn(single.expression, sub);
5923
+ const v = this.withNarrowScope(ctx, "merge", () => this.emitReturn(single.expression!, sub), new Set());
4033
5924
  if (sub.lines.length === 0) return this.returnText(ctx, v, single);
4034
5925
  return null;
4035
5926
  }
5927
+ if (single && (ts.isBreakStatement(single) || ts.isContinueStatement(single))) {
5928
+ // A break bound to a switch has no one-statement Zig spelling (Zig
5929
+ // `break` binds loops); declining here routes it through statement
5930
+ // emission, where it stops the build with its teaching.
5931
+ if (ts.isBreakStatement(single) && !single.label && this.breakBindsEnclosingSwitch(single)) {
5932
+ return null;
5933
+ }
5934
+ const kw = ts.isBreakStatement(single) ? "break" : "continue";
5935
+ return single.label ? `${kw} :${loopLabel(single.label.text)};` : `${kw};`;
5936
+ }
4036
5937
  return null;
4037
5938
  }
4038
5939
 
@@ -4041,10 +5942,14 @@ export class Emitter {
4041
5942
  cond: ts.Expression,
4042
5943
  op: ts.SyntaxKind = ts.SyntaxKind.EqualsEqualsEqualsToken,
4043
5944
  ): { base: ts.Expression; tag: string } | null {
4044
- if (!ts.isBinaryExpression(cond) || cond.operatorToken.kind !== op) return null;
5945
+ // Wrappers strip exactly as in emptyTestOf: a parenthesized, asserted,
5946
+ // or `as`/`satisfies`-cast guard or operand must narrow the same arm
5947
+ // the bare spelling does (emission erases every one of them).
5948
+ const c = unwrapExpr(cond);
5949
+ if (!ts.isBinaryExpression(c) || c.operatorToken.kind !== op) return null;
4045
5950
  const sides: Array<[ts.Expression, ts.Expression]> = [
4046
- [cond.left, cond.right],
4047
- [cond.right, cond.left],
5951
+ [unwrapExpr(c.left), unwrapExpr(c.right)],
5952
+ [unwrapExpr(c.right), unwrapExpr(c.left)],
4048
5953
  ];
4049
5954
  for (const [kindSide, litSide] of sides) {
4050
5955
  if (
@@ -4072,15 +5977,28 @@ export class Emitter {
4072
5977
  const t = unwrapOptional(this.zTypeOfExpr(guard.base, ctx));
4073
5978
  if (t.k !== "union") return emitBranch();
4074
5979
  const savedSubst = new Map(ctx.memberSubst);
5980
+ // stillOptionalSubst rides along: narrowUnion overwrites an optional
5981
+ // payload's marker with ITS access spelling, and a marker left out of
5982
+ // sync with the restored memberSubst breaks the identity check
5983
+ // zTypeOfExpr keys on — a redundant kind guard inside a payload
5984
+ // capture would leave the capture looking non-null for the rest of
5985
+ // the arm, routing reads around the null-narrowing lowerings.
5986
+ const savedStillOptional = new Map(ctx.stillOptionalSubst);
4075
5987
  const savedNarrow = new Map(ctx.narrowedUnion);
5988
+ this.pushNarrowKillFrame(ctx);
4076
5989
  this.narrowUnion(guard.base, t.name, guard.tag, ctx);
4077
5990
  try {
4078
5991
  return emitBranch();
4079
5992
  } finally {
4080
5993
  ctx.memberSubst.clear();
4081
5994
  for (const [k, v] of savedSubst) ctx.memberSubst.set(k, v);
5995
+ ctx.stillOptionalSubst.clear();
5996
+ for (const [k, v] of savedStillOptional) ctx.stillOptionalSubst.set(k, v);
4082
5997
  ctx.narrowedUnion.clear();
4083
5998
  for (const [k, v] of savedNarrow) ctx.narrowedUnion.set(k, v);
5999
+ // Assignment kills inside the branch stay dead past this restore
6000
+ // (the snapshot would resurrect them; see popNarrowKillFrame).
6001
+ this.popNarrowKillFrame(ctx);
4084
6002
  }
4085
6003
  }
4086
6004
 
@@ -4090,12 +6008,16 @@ export class Emitter {
4090
6008
  const arm = info.arms.find((a) => a.tag === tag);
4091
6009
  if (!arm) return;
4092
6010
  const baseText = this.emitExpr(expr, ctx).code;
4093
- const key = normalize(expr);
6011
+ const key = this.narrowKey(expr);
6012
+ if (key === null) return;
4094
6013
  ctx.narrowedUnion.set(key, tag);
4095
6014
  for (const f of arm.fields) {
4096
6015
  const access =
4097
6016
  arm.fields.length === 1 ? `${baseText}.${zigId(tag)}` : `${baseText}.${zigId(tag)}.${fieldName(f)}`;
4098
6017
  ctx.memberSubst.set(`${key}.${f.tsName}`, access);
6018
+ // Kind-narrowing selects the arm; it proves nothing about a field
6019
+ // that is itself optional — the payload access keeps the optional.
6020
+ if (this.fieldZType(f).k === "optional") ctx.stillOptionalSubst.set(`${key}.${f.tsName}`, access);
4099
6021
  }
4100
6022
  }
4101
6023
 
@@ -4139,16 +6061,53 @@ export class Emitter {
4139
6061
  return test;
4140
6062
  }
4141
6063
 
4142
- /// Whether any of the nodes reads the guarded target (decl identity for
4143
- /// identifiers, source text for property chains — same heuristic as
4144
- /// branchReadsTarget).
6064
+ /// Whether any of the nodes READS the guarded target — declaration
6065
+ /// identity for identifiers, declaration-QUALIFIED narrowKeys for
6066
+ /// property chains (anyReadsKey). Never source text: a shadowed spelling
6067
+ /// inside a nested callback (`xs.map((box) => box.q)`) is not a read of
6068
+ /// the outer `box.q`, and matching it by text binds a capture the
6069
+ /// declaration-keyed substitution (correctly) never rewrites — a Zig
6070
+ /// unused-capture error.
6071
+ ///
6072
+ /// Reads, not uses (identifierRead, the same judgment branchReadsTarget
6073
+ /// and captureServesBranch apply): the bare TARGET of a plain `=`
6074
+ /// assignment writes the raw slot, never the capture, so a write-only
6075
+ /// occurrence cannot consume a binding — gating a capture on it binds
6076
+ /// the capture unused, a Zig error. Compound assignments and `++`/`--`
6077
+ /// read the slot and still count. Property-chain targets are immutable
6078
+ /// model data, so their key walk needs no write exclusion.
4145
6079
  private anyReadsTarget(nodes: readonly ts.Node[], target: ts.Expression): boolean {
4146
6080
  if (ts.isIdentifier(target)) {
4147
6081
  const decl = this.tast.declarationOf(target);
4148
- if (decl) return nodes.some((n) => this.identifierUsed(n, decl));
4149
- }
4150
- const text = target.getText();
4151
- return nodes.some((n) => n.getText().includes(text));
6082
+ if (decl) return nodes.some((n) => this.identifierRead(n, decl));
6083
+ }
6084
+ return this.anyReadsKey(nodes, this.narrowKey(target));
6085
+ }
6086
+
6087
+ /// The property-chain read walk every capture/substitution GATE in the
6088
+ /// narrowing machinery uses: visit the nodes' property accesses (and
6089
+ /// identifiers, for the no-declaration corner), canonicalize each
6090
+ /// through narrowKey, and compare against the target's key — the same
6091
+ /// identity the installed substitutions are looked up by, so a gate that
6092
+ /// fires here is a gate whose capture WILL be consumed. Wrapper
6093
+ /// spellings (`(box.q)`, `box.q!`) match through the key's own
6094
+ /// canonicalization; a longer chain (`box.q.name`) matches via its
6095
+ /// inner access on the recursive walk.
6096
+ private anyReadsKey(nodes: readonly ts.Node[], key: string | null): boolean {
6097
+ // A keyless target (see narrowKey) has no reads to serve: nothing can
6098
+ // be substituted for it, so every gate over it declines.
6099
+ if (key === null) return false;
6100
+ let found = false;
6101
+ const visit = (n: ts.Node): void => {
6102
+ if (found) return;
6103
+ if ((ts.isPropertyAccessExpression(n) || ts.isIdentifier(n)) && this.narrowKey(n) === key) {
6104
+ found = true;
6105
+ return;
6106
+ }
6107
+ ts.forEachChild(n, visit);
6108
+ };
6109
+ for (const n of nodes) visit(n);
6110
+ return found;
4152
6111
  }
4153
6112
 
4154
6113
  /// Whether the nodes ASSIGN the guarded local (only identifiers are
@@ -4186,6 +6145,49 @@ export class Emitter {
4186
6145
  return found;
4187
6146
  }
4188
6147
 
6148
+ /// Whether a guarded branch can bind a Zig CAPTURE for its narrowed
6149
+ /// target. tsc keeps the narrow through a provably non-null
6150
+ /// reassignment, but a capture goes stale there — the assignment
6151
+ /// emitter transitions the substitution to the live-slot `.?` spelling
6152
+ /// — so the capture form only holds when every plain `=` assignment to
6153
+ /// the target sits at the branch's top statement level (straight-line
6154
+ /// flow the transition covers) AND some read precedes the first
6155
+ /// assignment to consume the binding. An assignment inside a nested
6156
+ /// construct (an if arm, a loop body — whose back edge reaches even
6157
+ /// the reads spelled above it) hands the branch to the `.?` spelling
6158
+ /// up front, which is valid for every read the guard dominates. A
6159
+ /// branch that never assigns the target keeps the capture; property
6160
+ /// targets are never assignable.
6161
+ private captureServesBranch(branch: ts.Statement, target: ts.Expression): boolean {
6162
+ if (!ts.isIdentifier(target)) return true;
6163
+ const decl = this.tast.declarationOf(target);
6164
+ if (!decl) return true;
6165
+ const stmts = ts.isBlock(branch) ? branch.statements : [branch];
6166
+ const plainAssignOf = (s: ts.Statement): ts.BinaryExpression | null =>
6167
+ ts.isExpressionStatement(s) &&
6168
+ ts.isBinaryExpression(s.expression) &&
6169
+ s.expression.operatorToken.kind === ts.SyntaxKind.EqualsToken &&
6170
+ ts.isIdentifier(s.expression.left) &&
6171
+ this.tast.declarationOf(s.expression.left) === decl
6172
+ ? s.expression
6173
+ : null;
6174
+ let anyAssign = false;
6175
+ let readBeforeAssign = false;
6176
+ for (const s of stmts) {
6177
+ const assign = plainAssignOf(s);
6178
+ if (assign) {
6179
+ // The RHS evaluates before the write, so its reads still consume
6180
+ // the capture.
6181
+ if (!anyAssign && this.identifierRead(assign.right, decl)) readBeforeAssign = true;
6182
+ anyAssign = true;
6183
+ continue;
6184
+ }
6185
+ if (this.assignsTarget([s], target)) return false;
6186
+ if (!anyAssign && this.identifierRead(s, decl)) readBeforeAssign = true;
6187
+ }
6188
+ return anyAssign ? readBeforeAssign : true;
6189
+ }
6190
+
4189
6191
  /// True when some conjunct null-guards a target a LATER conjunct reads —
4190
6192
  /// the chain needs one of the R7d lowerings to stay valid Zig.
4191
6193
  private chainHasNullGuard(conjuncts: readonly ts.Expression[], op: ts.SyntaxKind, ctx: Ctx): boolean {
@@ -4211,9 +6213,10 @@ export class Emitter {
4211
6213
  const rest = conjuncts.slice(1);
4212
6214
  if (rest.length === 0) return emitOne(c0);
4213
6215
  const guard = this.nullGuardOf(c0, op, ctx);
4214
- if (guard && this.anyReadsTarget(rest, guard.target)) {
6216
+ const guardKey = guard === null ? null : this.narrowKey(guard.target);
6217
+ if (guard && guardKey !== null && this.anyReadsTarget(rest, guard.target)) {
4215
6218
  this.requireFaithfulEmptyTest(guard.target, guard.flavor, c0);
4216
- const key = normalize(guard.target);
6219
+ const key = guardKey;
4217
6220
  const prop = this.emitExpr(guard.target, ctx).code;
4218
6221
  const cap = this.freshName(ctx, this.narrowHint(guard.target));
4219
6222
  const saved = ctx.memberSubst.get(key);
@@ -4246,18 +6249,21 @@ export class Emitter {
4246
6249
  const isAnd = op === ts.SyntaxKind.AmpersandAmpersandToken;
4247
6250
  const zop = isAnd ? "and" : "or";
4248
6251
  const saved = new Map(ctx.memberSubst);
6252
+ this.pushNarrowKillFrame(ctx);
4249
6253
  const emitChain = (conjs: readonly ts.Expression[]): string => {
4250
6254
  const c0 = conjs[0];
4251
6255
  const rest = conjs.slice(1);
4252
6256
  const guard = this.nullGuardOf(c0, op, ctx);
4253
6257
  if (guard) {
4254
6258
  this.requireFaithfulEmptyTest(guard.target, guard.flavor, c0);
4255
- const key = normalize(guard.target);
6259
+ const key = this.narrowKey(guard.target);
4256
6260
  const prop = this.emitExpr(guard.target, ctx).code;
4257
6261
  const head = `${prop} ${isAnd ? "!=" : "=="} null`;
4258
6262
  if (rest.length === 0) return head;
4259
- ctx.memberSubst.set(key, `${prop}.?`);
4260
- guards.set(key, `${prop}.?`);
6263
+ if (key !== null) {
6264
+ ctx.memberSubst.set(key, `${prop}.?`);
6265
+ guards.set(key, `${prop}.?`);
6266
+ }
4261
6267
  return `${head} ${zop} ${emitChain(rest)}`;
4262
6268
  }
4263
6269
  const head = precedenceParen(c0, zop, this.emitExpr(c0, ctx, { k: "bool" }).code);
@@ -4271,6 +6277,10 @@ export class Emitter {
4271
6277
  const code = emitChain(conjuncts);
4272
6278
  ctx.memberSubst.clear();
4273
6279
  for (const [k, v] of saved) ctx.memberSubst.set(k, v);
6280
+ // A conjunct can smuggle statements in (a block-bodied callback, an
6281
+ // R10b value-position step); an assignment kill made there must stay
6282
+ // dead past this restore (see popNarrowKillFrame).
6283
+ this.popNarrowKillFrame(ctx);
4274
6284
  return code;
4275
6285
  }
4276
6286
 
@@ -4278,11 +6288,15 @@ export class Emitter {
4278
6288
  private withSubsts<T>(guards: ReadonlyMap<string, string>, ctx: Ctx, emit: () => T): T {
4279
6289
  const saved = new Map(ctx.memberSubst);
4280
6290
  for (const [k, v] of guards) ctx.memberSubst.set(k, v);
6291
+ this.pushNarrowKillFrame(ctx);
4281
6292
  try {
4282
6293
  return emit();
4283
6294
  } finally {
4284
6295
  ctx.memberSubst.clear();
4285
6296
  for (const [k, v] of saved) ctx.memberSubst.set(k, v);
6297
+ // Assignment kills inside the scope stay dead past this restore
6298
+ // (the snapshot would resurrect them; see popNarrowKillFrame).
6299
+ this.popNarrowKillFrame(ctx);
4286
6300
  }
4287
6301
  }
4288
6302
 
@@ -4351,8 +6365,9 @@ export class Emitter {
4351
6365
  // A reassigned local cannot narrow through a capture (the capture
4352
6366
  // goes stale); the unwrap spelling below reads the live variable.
4353
6367
  if (this.assignsTarget(readers, g.target)) break;
6368
+ const key = this.narrowKey(g.target);
6369
+ if (key === null) break;
4354
6370
  this.requireFaithfulEmptyTest(g.target, g.flavor, conjuncts[gi]);
4355
- const key = normalize(g.target);
4356
6371
  const prop = this.emitExpr(g.target, ctx).code;
4357
6372
  const cap = this.freshName(ctx, this.narrowHint(g.target));
4358
6373
  caps.push({ key, saved: ctx.memberSubst.get(key) });
@@ -4404,14 +6419,15 @@ export class Emitter {
4404
6419
  const condText = this.emitNullGuardChainUnwrap(conjuncts, op, ctx, guards);
4405
6420
  const kindGuards = this.chainKindGuards(conjuncts, op);
4406
6421
  const thenStmts = ts.isBlock(stmt.thenStatement) ? stmt.thenStatement.statements : [stmt.thenStatement];
6422
+ const join = new Set<string>();
4407
6423
  this.push(ctx, `if (${condText}) {`);
4408
6424
  const tSub = this.nestedCtx(ctx);
4409
6425
  if (isAnd) {
4410
6426
  this.withSubsts(guards, ctx, () =>
4411
- this.withKindNarrows(kindGuards, ctx, () => this.emitBlockStatements(thenStmts, tSub)),
6427
+ this.withKindNarrows(kindGuards, ctx, () => this.emitBlockStatements(thenStmts, tSub, join)),
4412
6428
  );
4413
6429
  } else {
4414
- this.emitBlockStatements(thenStmts, tSub);
6430
+ this.emitBlockStatements(thenStmts, tSub, join);
4415
6431
  }
4416
6432
  ctx.lines.push(...tSub.lines);
4417
6433
  if (stmt.elseStatement) {
@@ -4420,18 +6436,23 @@ export class Emitter {
4420
6436
  const elseStmts = ts.isBlock(stmt.elseStatement) ? stmt.elseStatement.statements : [stmt.elseStatement];
4421
6437
  if (!isAnd) {
4422
6438
  this.withSubsts(guards, ctx, () =>
4423
- this.withKindNarrows(kindGuards, ctx, () => this.emitBlockStatements(elseStmts, eSub)),
6439
+ this.withKindNarrows(kindGuards, ctx, () => this.emitBlockStatements(elseStmts, eSub, join)),
4424
6440
  );
4425
6441
  } else {
4426
- this.emitBlockStatements(elseStmts, eSub);
6442
+ this.emitBlockStatements(elseStmts, eSub, join);
4427
6443
  }
4428
6444
  ctx.lines.push(...eSub.lines);
4429
6445
  }
4430
6446
  this.push(ctx, `}`);
6447
+ this.applyJoinedNarrowKills(ctx, join);
4431
6448
  if (exitDual) {
4432
6449
  // `if (x === null || <bad>) return ...;` — the code below runs only
4433
- // with x present, so the unwrap substitutions stay active.
4434
- for (const [k, v] of guards) ctx.memberSubst.set(k, v);
6450
+ // with x present, so the unwrap substitutions stay active — minus
6451
+ // any target the arm killed on a non-leaving exit (a break/continue
6452
+ // route merges its kills; the post-statement state subtracts them).
6453
+ for (const [k, v] of guards) {
6454
+ if (!join.has(k)) ctx.memberSubst.set(k, v);
6455
+ }
4435
6456
  }
4436
6457
  return true;
4437
6458
  }
@@ -4463,7 +6484,15 @@ export class Emitter {
4463
6484
  this.push(ctx, `${head} (${cond}) : (${inc}) {`);
4464
6485
  const sub = this.nestedCtx(ctx);
4465
6486
  const body = ts.isBlock(stmt.statement) ? stmt.statement.statements : [stmt.statement];
4466
- this.emitBlockStatements(body, sub);
6487
+ // A `for (; false;)` body is statically unreachable to tsc's CFA
6488
+ // (tscExcludedArm), so its kills never reach the post-loop state —
6489
+ // the same drop emitWhile applies to a `while (false)` body. The
6490
+ // body still emits; only the flow bookkeeping skips.
6491
+ if (this.tscExcludedArm(stmt, stmt.statement)) {
6492
+ this.withNarrowScope(ctx, "drop", () => this.emitBlockStatements(body, sub));
6493
+ } else {
6494
+ this.emitBlockStatements(body, sub);
6495
+ }
4467
6496
  ctx.lines.push(...sub.lines);
4468
6497
  this.push(ctx, `}`);
4469
6498
  }
@@ -4682,10 +6711,18 @@ export class Emitter {
4682
6711
  const info = this.table.unions.get(baseType.name);
4683
6712
  if (!info) this.fail(stmt, `unknown union ${baseType.name}`);
4684
6713
  const base = this.emitExpr(scrutinee.expression, ctx).code;
4685
- const baseKey = normalize(scrutinee.expression);
6714
+ const baseKey = this.narrowKey(scrutinee.expression);
4686
6715
  this.push(ctx, `switch (${base}) {`);
4687
6716
  const armCtx = { ...ctx, indent: ctx.indent + 1 };
4688
6717
  const covered = new Set<string>();
6718
+ // Clauses are pure siblings — alternatives from the switch's entry
6719
+ // state, never a sequence: tsc's noFallthroughCasesInSwitch (on in the
6720
+ // subset's program options) rejects a non-empty clause that falls into
6721
+ // the next, and label stacking shares ONE body. So each clause's
6722
+ // merge-class kills join here and apply only after every clause has
6723
+ // emitted (see applyJoinedNarrowKills) — applying them per clause
6724
+ // would strip a later clause of a narrowing tsc keeps there.
6725
+ const join = new Set<string>();
4689
6726
  let sawDefault = false;
4690
6727
  // Label stacking (`case "a": case "b": body`): JS runs the next body
4691
6728
  // for every stacked label, so the labels coalesce into one Zig arm.
@@ -4717,7 +6754,7 @@ export class Emitter {
4717
6754
  continue;
4718
6755
  }
4719
6756
  const sub = this.nestedCtx(armCtx);
4720
- this.emitBlockStatements(stmts, sub);
6757
+ this.emitBlockStatements(stmts, sub, join);
4721
6758
  const single = sub.lines.length === 1 ? sub.lines[0].trim() : null;
4722
6759
  if (single && (single.startsWith("return ") || single.startsWith("break :")) && single.endsWith(";")) {
4723
6760
  const armText = `else => ${single.slice(0, -1)},`;
@@ -4747,11 +6784,16 @@ export class Emitter {
4747
6784
  if (last && ts.isBreakStatement(last) && !last.label) stmts = stmts.slice(0, -1);
4748
6785
 
4749
6786
  const sub = this.nestedCtx(armCtx);
4750
- // Payload capture + member substitution for this arm's fields.
6787
+ // Payload capture + member substitution for this arm's fields. Field
6788
+ // use is judged by the declaration-qualified key the substitutions
6789
+ // are installed under — a same-named field of some OTHER value in
6790
+ // the body (`box.v` beside payload field `v`) is not a payload read,
6791
+ // and binding the capture for it would leave it unused.
4751
6792
  const savedSubst = new Map(ctx.memberSubst);
6793
+ const savedStillOptional = new Map(ctx.stillOptionalSubst);
4752
6794
  let capture = "";
4753
- const payloadUsed = arm.fields.some((f) =>
4754
- stmts.some((s) => s.getText().includes(`.${f.tsName}`)),
6795
+ const payloadUsed = baseKey !== null && arm.fields.some((f) =>
6796
+ this.anyReadsKey(stmts, `${baseKey}.${f.tsName}`),
4755
6797
  );
4756
6798
  if (pending.length > 0 && payloadUsed) {
4757
6799
  // The shared body would need one capture per differently-shaped
@@ -4762,14 +6804,37 @@ export class Emitter {
4762
6804
  const cap = this.freshName(sub, zigLocalName(arm.fields[0].tsName));
4763
6805
  capture = `|${cap}| `;
4764
6806
  sub.memberSubst.set(`${baseKey}.${arm.fields[0].tsName}`, cap);
6807
+ // The capture holds the payload AS-IS: an optional field stays
6808
+ // optional through it (this is a rename, not a null-narrowing).
6809
+ if (this.fieldZType(arm.fields[0]).k === "optional") {
6810
+ sub.stillOptionalSubst.set(`${baseKey}.${arm.fields[0].tsName}`, cap);
6811
+ }
4765
6812
  } else if (arm.fields.length > 1 && payloadUsed) {
4766
6813
  const cap = this.freshName(sub, zigId(arm.tag));
4767
6814
  capture = `|${cap}| `;
4768
- for (const f of arm.fields) sub.memberSubst.set(`${baseKey}.${f.tsName}`, `${cap}.${fieldName(f)}`);
6815
+ for (const f of arm.fields) {
6816
+ sub.memberSubst.set(`${baseKey}.${f.tsName}`, `${cap}.${fieldName(f)}`);
6817
+ if (this.fieldZType(f).k === "optional") {
6818
+ sub.stillOptionalSubst.set(`${baseKey}.${f.tsName}`, `${cap}.${fieldName(f)}`);
6819
+ }
6820
+ }
4769
6821
  }
6822
+ this.pushNarrowKillFrame(ctx);
4770
6823
  this.emitBlockStatements(stmts, sub);
4771
- // Restore: captures are arm-scoped.
4772
- for (const k of [...ctx.memberSubst.keys()]) if (!savedSubst.has(k)) ctx.memberSubst.delete(k);
6824
+ // Restore: captures are arm-scoped, and the still-optional markers
6825
+ // stay paired with the substitutions they annotate. Repopulate from
6826
+ // the snapshot rather than deleting the arm's additions — a nested
6827
+ // switch on the same subject OVERWRITES entries the snapshot already
6828
+ // held (its capture shadows the outer one), and a delete-only sweep
6829
+ // would leave the inner capture name active after its block closed.
6830
+ ctx.memberSubst.clear();
6831
+ for (const [k, v] of savedSubst) ctx.memberSubst.set(k, v);
6832
+ ctx.stillOptionalSubst.clear();
6833
+ for (const [k, v] of savedStillOptional) ctx.stillOptionalSubst.set(k, v);
6834
+ // Assignment kills inside the arm join with the sibling clauses'
6835
+ // and apply after the last clause (the snapshot above must not
6836
+ // resurrect them; see applyJoinedNarrowKills).
6837
+ for (const key of this.popNarrowKillFrame(ctx, "drop")) join.add(key);
4773
6838
 
4774
6839
  const labels = [...pending, tag].map((t) => `.${zigId(t)}`).join(", ");
4775
6840
  pending = [];
@@ -4795,6 +6860,7 @@ export class Emitter {
4795
6860
  }
4796
6861
  }
4797
6862
  this.push(ctx, `}`);
6863
+ this.applyJoinedNarrowKills(ctx, join);
4798
6864
  }
4799
6865
 
4800
6866
  /// R13d: a switch over a literal-union VALUE. Member labels become enum or
@@ -4812,6 +6878,9 @@ export class Emitter {
4812
6878
  this.push(ctx, `switch (${base}) {`);
4813
6879
  const armCtx = { ...ctx, indent: ctx.indent + 1 };
4814
6880
  const covered = new Set<string>();
6881
+ // Clauses are siblings (noFallthroughCasesInSwitch; stacked labels
6882
+ // share one body): kills join and apply after the last clause.
6883
+ const join = new Set<string>();
4815
6884
  let pending: string[] = [];
4816
6885
  let sawDefault = false;
4817
6886
  let allExit = true;
@@ -4860,7 +6929,7 @@ export class Emitter {
4860
6929
  const armLabel = label ? [...pending, label].join(", ") : "else";
4861
6930
  pending = [];
4862
6931
  const sub = this.nestedCtx(armCtx);
4863
- this.emitBlockStatements(stmts, sub);
6932
+ this.emitBlockStatements(stmts, sub, join);
4864
6933
  const single = sub.lines.length === 1 ? sub.lines[0].trim() : null;
4865
6934
  if (single && (single.startsWith("return ") || single.startsWith("break :")) && single.endsWith(";")) {
4866
6935
  const armText = `${armLabel} => ${single.slice(0, -1)},`;
@@ -4876,17 +6945,37 @@ export class Emitter {
4876
6945
  if (pending.length > 0) this.push(armCtx, `${pending.join(", ")} => {},`);
4877
6946
  if (!sawDefault) {
4878
6947
  const total = t.k === "enum" ? t.members.length : t.values.length;
6948
+ // Coverage of the declared members, or of the scrutinee's sound
6949
+ // coverage type (valueSwitchCoversScrutineeType — declared-type based,
6950
+ // never the raw flow type): either proves the fallthrough arm never
6951
+ // runs, and alwaysExits claims terminality off the second, so the
6952
+ // emitted shape must close exactly the path the claim closed. When
6953
+ // the judgment declines, the else completes (`else => {}`) and the
6954
+ // terminality claim declines with it — a reached `unreachable` is
6955
+ // never acceptable.
6956
+ const coveredByType = covered.size === total || this.valueSwitchCoversScrutineeType(stmt);
6957
+ // AGREEMENT: alwaysExits claims terminality off this same coverage
6958
+ // judgment, and a claimed-terminal switch must never lower to a
6959
+ // completable shape (`else => {}`). The claim's conditions imply
6960
+ // coveredByType && allExit, so the disagreement cannot arise; if a
6961
+ // future edit splits the two judgments, stop the build rather than
6962
+ // emit an arm that completes where the claim said it cannot.
6963
+ if (!(coveredByType && allExit) && this.alwaysExits(stmt)) {
6964
+ this.fail(stmt, "a switch claimed always-exiting whose lowering left a completable fallthrough arm (terminality/lowering disagreement)");
6965
+ }
4879
6966
  if (t.k === "numAlias") {
4880
6967
  // The Zig scrutinee is an integer type, so an else arm is always
4881
6968
  // required. With every member covered by an exiting arm the else is
4882
6969
  // unreachable by the TypeScript types.
4883
- this.push(armCtx, covered.size === total && allExit ? `else => unreachable,` : `else => {},`);
6970
+ this.push(armCtx, coveredByType && allExit ? `else => unreachable,` : `else => {},`);
4884
6971
  } else if (covered.size < total) {
4885
- // JS: an uncovered member skips the switch.
4886
- this.push(armCtx, `else => {},`);
6972
+ // JS: an uncovered member skips the switch; one the TypeScript
6973
+ // types rule out never reaches it.
6974
+ this.push(armCtx, coveredByType && allExit ? `else => unreachable,` : `else => {},`);
4887
6975
  }
4888
6976
  }
4889
6977
  this.push(ctx, `}`);
6978
+ this.applyJoinedNarrowKills(ctx, join);
4890
6979
  }
4891
6980
 
4892
6981
  /// R13f: a switch over a PLAIN number/string value lowers to an if/else
@@ -4964,30 +7053,61 @@ export class Emitter {
4964
7053
  }
4965
7054
  // Trailing label-only clauses (and a trailing empty default): JS no-ops.
4966
7055
  const defaultArm = arms.find((a) => a.alsoDefault) ?? null;
7056
+ // AGREEMENT: alwaysExits may claim this switch terminal (defaultless,
7057
+ // no bound break, case labels covering the scrutinee's SOUND coverage
7058
+ // type, every clause group exiting — the same memoized
7059
+ // valueSwitchCoversScrutineeType judgment emitValueSwitch closes its
7060
+ // `else => unreachable` off). The lowered chain must then close too:
7061
+ // left open, the claim suppresses the trailing completion a value
7062
+ // block or a returning function needs, and the chain's end — which
7063
+ // the claim just promised is unreachable — completes into invalid
7064
+ // Zig. The coverage judgment is sound by construction (declared type,
7065
+ // or a flow type no nested assigner can have run against), so the
7066
+ // closing arm is an `else` real execution never reaches.
7067
+ const claimsTerminal = this.alwaysExits(stmt);
7068
+ // The lowered if/else chain's arms are the switch's clauses — siblings
7069
+ // (noFallthroughCasesInSwitch): kills join and apply after the chain.
7070
+ const join = new Set<string>();
4967
7071
  let opened = false;
4968
7072
  for (const arm of arms) {
4969
7073
  if (arm.conds.length === 0) continue; // a pure default arm emits as the else below
4970
7074
  const cond = arm.conds.join(" or ");
4971
7075
  this.push(ctx, `${opened ? "} else " : ""}if (${cond}) {`);
4972
7076
  const sub = this.nestedCtx(ctx);
4973
- this.emitBlockStatements(arm.stmts, sub);
7077
+ this.emitBlockStatements(arm.stmts, sub, join);
4974
7078
  ctx.lines.push(...sub.lines);
4975
7079
  opened = true;
4976
7080
  }
4977
7081
  if (defaultArm && opened) {
4978
7082
  this.push(ctx, `} else {`);
4979
7083
  const sub = this.nestedCtx(ctx);
4980
- this.emitBlockStatements(defaultArm.stmts, sub);
7084
+ this.emitBlockStatements(defaultArm.stmts, sub, join);
4981
7085
  ctx.lines.push(...sub.lines);
4982
7086
  } else if (defaultArm) {
4983
7087
  // Every case label was empty-trailing (or none existed): the default
4984
- // body runs unconditionally.
7088
+ // body runs unconditionally — straight-line flow, so its kills merge
7089
+ // as usual rather than joining with the (nonexistent) other arms.
4985
7090
  const sub = this.childCtx(ctx);
4986
7091
  this.emitBlockStatements(defaultArm.stmts, sub);
4987
7092
  ctx.lines.push(...sub.lines);
7093
+ this.applyJoinedNarrowKills(ctx, join);
4988
7094
  return;
7095
+ } else if (opened && claimsTerminal) {
7096
+ // The claimed-terminal defaultless chain closes its never-reached
7097
+ // fallthrough (see the AGREEMENT note above).
7098
+ this.push(ctx, `} else {`);
7099
+ const sub = this.nestedCtx(ctx);
7100
+ this.push(sub, `unreachable;`);
7101
+ ctx.lines.push(...sub.lines);
7102
+ } else if (claimsTerminal) {
7103
+ // Terminal without any emitted arm cannot happen (a terminality
7104
+ // claim needs an exiting, statement-bearing clause); if a future
7105
+ // edit breaks that, stop the build rather than emit a shape that
7106
+ // completes where the claim said it cannot.
7107
+ this.fail(stmt, "a switch claimed always-exiting whose lowering emitted no arms (terminality/lowering disagreement)");
4989
7108
  }
4990
7109
  if (opened) this.push(ctx, `}`);
7110
+ this.applyJoinedNarrowKills(ctx, join);
4991
7111
  if (sawDefault && !defaultArm && clauses.length > 0) {
4992
7112
  // A trailing empty default is a JS no-op; nothing to emit.
4993
7113
  }
@@ -5015,6 +7135,9 @@ export class Emitter {
5015
7135
  ) {
5016
7136
  return; // breaks inside these target them, not the switch
5017
7137
  }
7138
+ // A nested function's breaks bind inside the function (the
7139
+ // breaksToLabel boundary rule), never this switch.
7140
+ if (ts.isFunctionLike(n)) return;
5018
7141
  if (ts.isBreakStatement(n) && !n.label) {
5019
7142
  this.fail(n, "an early `break` inside a plain-value switch clause (end the clause with a single trailing `break` or a `return`)");
5020
7143
  }
@@ -5143,16 +7266,42 @@ export class Emitter {
5143
7266
  // narrowing dies with the assignment, exactly like TS.
5144
7267
  const t = this.zTypeOfExprClassed(expr.left, ctx);
5145
7268
  const v = this.emitExpr(expr.right, ctx, t, undefined);
5146
- const key = normalize(expr.left);
5147
- const hadSubst = ctx.memberSubst.get(key);
5148
- if (hadSubst !== undefined) ctx.memberSubst.delete(key);
7269
+ const key = this.narrowKey(expr.left);
7270
+ const hadSubst = key === null ? undefined : ctx.memberSubst.get(key);
7271
+ if (key !== null && hadSubst !== undefined) ctx.memberSubst.delete(key);
5149
7272
  const target = this.emitExpr(expr.left, ctx).code;
5150
- if (hadSubst !== undefined && hadSubst.endsWith(".?")) {
7273
+ const empties = this.tast.emptiesOf(expr.right);
7274
+ const mayBeEmpty = empties.null || empties.undefined;
7275
+ if (key !== null && hadSubst !== undefined && hadSubst.endsWith(".?") && !mayBeEmpty) {
5151
7276
  // `.?` substitutions read the live variable, so they survive an
5152
- // assignment of a provably non-null value. Capture substitutions
5153
- // would read the stale capture — those stay dropped.
5154
- const empties = this.tast.emptiesOf(expr.right);
5155
- if (!empties.null && !empties.undefined) ctx.memberSubst.set(key, hadSubst);
7277
+ // assignment of a provably non-null value.
7278
+ ctx.memberSubst.set(key, hadSubst);
7279
+ } else if (
7280
+ key !== null &&
7281
+ hadSubst !== undefined &&
7282
+ !mayBeEmpty &&
7283
+ hadSubst !== ctx.stillOptionalSubst.get(key) &&
7284
+ this.zTypeOfExpr(expr.left, ctx).k === "optional"
7285
+ ) {
7286
+ // A capture substitution would read the stale capture, but tsc
7287
+ // keeps the target narrowed through a provably non-null
7288
+ // assignment — so the substitution TRANSITIONS to the live-slot
7289
+ // `.?` spelling from this point onward: still narrowed, reads go
7290
+ // through the reassigned slot. (The still-optional renames are
7291
+ // payload aliases, not null-narrows; they have no `.?` form.)
7292
+ ctx.memberSubst.set(key, `${target}.?`);
7293
+ }
7294
+ if (key !== null && !ctx.memberSubst.has(key) && (hadSubst !== undefined || mayBeEmpty)) {
7295
+ // The narrowing died with this assignment (the value may be null
7296
+ // again, or the substitution has no live-slot form to transition
7297
+ // to). Record the kill so scope
7298
+ // exits, whose snapshot restores give containment, do not
7299
+ // resurrect it past the merge — and record it even when NO
7300
+ // substitution was live: a construct's post-exit narrow
7301
+ // (applyPostIfNarrow and kin) subtracts the joined kills, and
7302
+ // tsc buries the guard-implied narrow for every possibly-null
7303
+ // assignment an arm makes, active substitution or not.
7304
+ ctx.narrowKilled[ctx.narrowKilled.length - 1]?.add(key);
5156
7305
  }
5157
7306
  this.push(ctx, `${target} = ${this.byteStoreNarrowed(expr, v.code, ctx)};`);
5158
7307
  return;
@@ -5930,7 +8079,8 @@ export class Emitter {
5930
8079
  }
5931
8080
 
5932
8081
  private emitExprValue(expr: ts.Expression, ctx: Ctx, expected?: ZType, nameHint?: string): Emitted {
5933
- const subst = ctx.memberSubst.get(normalize(expr));
8082
+ const substKey = this.narrowKey(expr);
8083
+ const subst = substKey === null ? undefined : ctx.memberSubst.get(substKey);
5934
8084
  if (subst !== undefined) return { code: subst };
5935
8085
 
5936
8086
  if (ts.isParenthesizedExpression(expr)) {
@@ -6021,8 +8171,10 @@ export class Emitter {
6021
8171
  }
6022
8172
  const baseCode = this.emitExpr(expr.expression, ctx).code;
6023
8173
  const cap = this.freshName(ctx, nameHint ?? "elems");
8174
+ // Probe in a flow scope (see childCtx): a lines-free index probe
8175
+ // processed no statements, and a lines-bearing one stops the build.
6024
8176
  const idxCtx = this.childCtx(ctx);
6025
- const idx = this.emitIndex(expr.argumentExpression, idxCtx);
8177
+ const idx = this.withNarrowScope(ctx, "merge", () => this.emitIndex(expr.argumentExpression, idxCtx), new Set());
6026
8178
  if (idxCtx.lines.length > 0) {
6027
8179
  // JS only evaluates the index when the base is non-null; an index
6028
8180
  // needing its own statements cannot ride the inline capture.
@@ -6059,8 +8211,8 @@ export class Emitter {
6059
8211
  }
6060
8212
 
6061
8213
  private emitPropertyAccess(expr: ts.PropertyAccessExpression, ctx: Ctx): Emitted {
6062
- const key = normalize(expr);
6063
- const subst = ctx.memberSubst.get(key);
8214
+ const key = this.narrowKey(expr);
8215
+ const subst = key === null ? undefined : ctx.memberSubst.get(key);
6064
8216
  if (subst !== undefined) return { code: subst };
6065
8217
  // Layer-3 re-derivation of NS1017 (`Cmd.none` outside the return slot)
6066
8218
  // and NS1025 (its Sub mirror).
@@ -6100,8 +8252,8 @@ export class Emitter {
6100
8252
  if (ts.isOptionalChain(expr)) return this.emitOptionalChain(expr, ctx);
6101
8253
  const prop = expr.name.text;
6102
8254
  if (prop === "length") {
6103
- const lenKey = `${expr.expression.getText()}.length`;
6104
- const lenSubst = ctx.memberSubst.get(lenKey.replace(/\s+/g, ""));
8255
+ const baseLenKey = this.narrowKey(expr.expression);
8256
+ const lenSubst = baseLenKey === null ? undefined : ctx.memberSubst.get(`${baseLenKey}.length`);
6105
8257
  if (lenSubst !== undefined) return { code: lenSubst };
6106
8258
  const baseT = this.zTypeOfExpr(expr.expression, ctx);
6107
8259
  const base = this.emitExpr(expr.expression, ctx);
@@ -6274,8 +8426,10 @@ export class Emitter {
6274
8426
  if (op === ts.SyntaxKind.QuestionQuestionToken) {
6275
8427
  // `x ?? null` folds JS undefined and null into one empty value — which
6276
8428
  // is exactly what the native optional already is, so the left side IS
6277
- // the result (this is also how a `?.` chain value normalizes).
6278
- if (expr.right.kind === ts.SyntaxKind.NullKeyword) {
8429
+ // the result (this is also how a `?.` chain value normalizes). The
8430
+ // wrapped spellings (`x ?? (null)`) and the `x ?? undefined` flavor
8431
+ // fold identically.
8432
+ if (this.isEmptyLiteral(expr.right)) {
6279
8433
  return this.emitExpr(expr.left, ctx, expected);
6280
8434
  }
6281
8435
  // Both sides see the expected type: either may need an enum re-tag.
@@ -6480,11 +8634,33 @@ export class Emitter {
6480
8634
  // `x === null ? A : x` -> `x orelse A` (the `=== undefined` spelling on
6481
8635
  // undefined-flavored values maps the same way, per R7c).
6482
8636
  const missTest = this.emptyTestOf(cond);
6483
- if (missTest && normalize(expr.whenFalse) === normalize(missTest.target)) {
8637
+ const missArmKey = this.narrowKey(expr.whenFalse);
8638
+ if (missTest && missArmKey !== null && missArmKey === this.narrowKey(missTest.target)) {
6484
8639
  this.requireFaithfulEmptyTest(missTest.target, missTest.flavor, cond);
6485
- const target = this.emitExpr(missTest.target, ctx).code;
6486
- const alt = this.emitExpr(expr.whenTrue, ctx).code;
6487
- return { code: `${target} orelse ${alt}` };
8640
+ // Probe both sides in throwaway child ctxs: the fusion only holds
8641
+ // when the miss arm is statement-free. An arm that lowers statements
8642
+ // (a spread literal builds its copy line by line) must not ride the
8643
+ // orelse — those lines would land ABOVE it and run even on the
8644
+ // non-empty path — so it falls through to the narrowed-ternary
8645
+ // lowering below, which scopes them to the branch that runs.
8646
+ const tT = this.zTypeOfExpr(missTest.target, ctx);
8647
+ const armWant =
8648
+ expected ? unwrapOptional(expected) : tT.k === "optional" ? tT.inner : undefined;
8649
+ // Both probes bracket in a flow scope (see childCtx): discarded, they
8650
+ // must leave no trace; taken, the miss arm's real kills join onto the
8651
+ // post-expression state below.
8652
+ const fuseJoin = new Set<string>();
8653
+ const targetSub = this.childCtx(ctx);
8654
+ const target = this.withNarrowScope(ctx, "merge", () => this.emitExpr(missTest.target, targetSub).code, fuseJoin);
8655
+ const altSub = this.childCtx(ctx);
8656
+ const alt = this.withNarrowScope(ctx, "merge", () => this.emitExpr(expr.whenTrue, altSub, armWant).code, fuseJoin);
8657
+ if (altSub.lines.length === 0) {
8658
+ // The target is evaluated exactly once; its lowered lines (if any)
8659
+ // ride ahead of the orelse like any condition's.
8660
+ ctx.lines.push(...targetSub.lines);
8661
+ this.applyJoinedNarrowKills(ctx, fuseJoin);
8662
+ return { code: `${target} orelse ${alt}` };
8663
+ }
6488
8664
  }
6489
8665
  // `x === null ? A : <uses x>` (and the `=== undefined` find-miss
6490
8666
  // spelling) — the narrowing dual of the `!==` case below: TS narrows
@@ -6495,22 +8671,14 @@ export class Emitter {
6495
8671
  missTest &&
6496
8672
  (ts.isPropertyAccessExpression(missTest.target) || ts.isIdentifier(missTest.target)) &&
6497
8673
  // An unread capture would be a Zig unused-capture error; unread
6498
- // guards keep the plain comparison.
6499
- expr.whenFalse.getText().includes(missTest.target.getText())
8674
+ // guards keep the plain comparison. Declaration identity for
8675
+ // identifier targets: a wrapped read (`q!`) is still a read of q.
8676
+ this.anyReadsTarget([expr.whenFalse], missTest.target)
6500
8677
  ) {
6501
8678
  const t = this.zTypeOfExpr(missTest.target, ctx);
6502
8679
  if (t.k === "optional") {
6503
8680
  this.requireFaithfulEmptyTest(missTest.target, missTest.flavor, cond);
6504
- const key = normalize(missTest.target);
6505
- const target = this.emitExpr(missTest.target, ctx).code;
6506
- const cap = this.freshName(ctx, this.narrowHint(missTest.target));
6507
- const saved = ctx.memberSubst.get(key);
6508
- ctx.memberSubst.set(key, cap);
6509
- const hitV = this.emitExpr(expr.whenFalse, ctx, expected ? unwrapOptional(expected) : undefined).code;
6510
- ctx.memberSubst.delete(key);
6511
- if (saved !== undefined) ctx.memberSubst.set(key, saved);
6512
- const missV = this.emitExpr(expr.whenTrue, ctx, expected).code;
6513
- return { code: `if (${target}) |${cap}| ${hitV} else ${missV}` };
8681
+ return this.emitNarrowedTernary(expr, missTest.target, expr.whenFalse, expr.whenTrue, ctx, expected, nameHint);
6514
8682
  }
6515
8683
  }
6516
8684
  // `x !== null ? <uses x> : B` -> `if (x) |v| ... else B`.
@@ -6519,22 +8687,14 @@ export class Emitter {
6519
8687
  hitTest &&
6520
8688
  (ts.isPropertyAccessExpression(hitTest.target) || ts.isIdentifier(hitTest.target)) &&
6521
8689
  // An unread capture would be a Zig unused-capture error; unread guards
6522
- // keep the plain comparison.
6523
- expr.whenTrue.getText().includes(hitTest.target.getText())
8690
+ // keep the plain comparison. Declaration identity for identifier
8691
+ // targets: a wrapped read (`q!`) is still a read of q.
8692
+ this.anyReadsTarget([expr.whenTrue], hitTest.target)
6524
8693
  ) {
6525
8694
  const t = this.zTypeOfExpr(hitTest.target, ctx);
6526
8695
  if (t.k === "optional") {
6527
8696
  this.requireFaithfulEmptyTest(hitTest.target, hitTest.flavor, cond);
6528
- const key = normalize(hitTest.target);
6529
- const target = this.emitExpr(hitTest.target, ctx).code;
6530
- const cap = this.freshName(ctx, this.narrowHint(hitTest.target));
6531
- const saved = ctx.memberSubst.get(key);
6532
- ctx.memberSubst.set(key, cap);
6533
- const thenV = this.emitExpr(expr.whenTrue, ctx, expected ? unwrapOptional(expected) : undefined).code;
6534
- ctx.memberSubst.delete(key);
6535
- if (saved !== undefined) ctx.memberSubst.set(key, saved);
6536
- const elseV = this.emitExpr(expr.whenFalse, ctx, expected).code;
6537
- return { code: `if (${target}) |${cap}| ${thenV} else ${elseV}` };
8697
+ return this.emitNarrowedTernary(expr, hitTest.target, expr.whenTrue, expr.whenFalse, ctx, expected, nameHint);
6538
8698
  }
6539
8699
  }
6540
8700
  // R7d: a null-guarded chain condition — `x !== null && x.a > 0 ? x.a :
@@ -6564,38 +8724,46 @@ export class Emitter {
6564
8724
  this.withSubsts(guards, ctx, () =>
6565
8725
  this.withKindNarrows(kindGuards, ctx, () => this.emitExpr(e, sub, want).code),
6566
8726
  );
8727
+ // Each arm probes and emits from the ENTRY state, kills joining
8728
+ // after the last arm (see childCtx's isolation law).
8729
+ const probeJoin = new Set<string>();
6567
8730
  const thenSub2 = this.childCtx(ctx);
6568
- const thenCode = isAnd
8731
+ const thenCode = this.withNarrowScope(ctx, "merge", () => isAnd
6569
8732
  ? emitNarrowed(thenSub2, expr.whenTrue, narrowedExpected)
6570
- : this.emitExpr(expr.whenTrue, thenSub2, expected ? unwrapOptional(expected) : expected).code;
8733
+ : this.emitExpr(expr.whenTrue, thenSub2, expected ? unwrapOptional(expected) : expected).code, probeJoin);
6571
8734
  const elseSub2 = this.childCtx(ctx);
6572
- const elseCode = isAnd
8735
+ const elseCode = this.withNarrowScope(ctx, "merge", () => isAnd
6573
8736
  ? this.emitExpr(expr.whenFalse, elseSub2, expected).code
6574
- : emitNarrowed(elseSub2, expr.whenFalse, expected);
8737
+ : emitNarrowed(elseSub2, expr.whenFalse, expected), probeJoin);
6575
8738
  if (thenSub2.lines.length === 0 && elseSub2.lines.length === 0) {
8739
+ // The probes ARE the emission here: their kills are the join.
8740
+ this.applyJoinedNarrowKills(ctx, probeJoin);
6576
8741
  return { code: `if (${condText}) ${thenCode} else ${elseCode}` };
6577
8742
  }
6578
8743
  // A branch needing lowered statements: re-emit each into a nested
6579
8744
  // block assigning a named temp (the R17b lowering the plain
6580
- // conditional path uses).
8745
+ // conditional path uses). probeJoin is discarded with the probe
8746
+ // lines — the re-emissions below record the real kills.
8747
+ const chainJoin = new Set<string>();
6581
8748
  const t2 = expected ?? this.zTypeOfExpr(expr, ctx);
6582
8749
  const name = this.freshName(ctx, nameHint ?? "value");
6583
8750
  this.push(ctx, `var ${name}: ${this.table.zigTypeRef(t2)} = undefined;`);
6584
8751
  this.push(ctx, `if (${condText}) {`);
6585
8752
  const nt = this.nestedCtx(ctx);
6586
- const ntCode = isAnd
8753
+ const ntCode = this.withNarrowScope(ctx, "merge", () => isAnd
6587
8754
  ? emitNarrowed(nt, expr.whenTrue, narrowedExpected)
6588
- : this.emitExpr(expr.whenTrue, nt, expected ? unwrapOptional(expected) : expected).code;
8755
+ : this.emitExpr(expr.whenTrue, nt, expected ? unwrapOptional(expected) : expected).code, chainJoin);
6589
8756
  nt.lines.push(" ".repeat(nt.indent) + `${name} = ${ntCode};`);
6590
8757
  ctx.lines.push(...nt.lines);
6591
8758
  this.push(ctx, `} else {`);
6592
8759
  const ne = this.nestedCtx(ctx);
6593
- const neCode = isAnd
8760
+ const neCode = this.withNarrowScope(ctx, "merge", () => isAnd
6594
8761
  ? this.emitExpr(expr.whenFalse, ne, expected).code
6595
- : emitNarrowed(ne, expr.whenFalse, expected);
8762
+ : emitNarrowed(ne, expr.whenFalse, expected), chainJoin);
6596
8763
  ne.lines.push(" ".repeat(ne.indent) + `${name} = ${neCode};`);
6597
8764
  ctx.lines.push(...ne.lines);
6598
8765
  this.push(ctx, `}`);
8766
+ this.applyJoinedNarrowKills(ctx, chainJoin);
6599
8767
  return { code: name };
6600
8768
  }
6601
8769
  }
@@ -6604,36 +8772,115 @@ export class Emitter {
6604
8772
  // R13c: kind guards narrow the branch TS narrows, in ternaries too.
6605
8773
  const posGuard = this.kindGuardOf(cond);
6606
8774
  const negGuard = this.kindGuardOf(cond, ts.SyntaxKind.ExclamationEqualsEqualsToken);
6607
- // Branches that need lowered statements (spreads): lower via a named temp.
8775
+ // Branches that need lowered statements (spreads): lower via a named
8776
+ // temp. Each arm probes and emits from the ENTRY state, kills joining
8777
+ // after the last arm (see childCtx's isolation law).
8778
+ const probeJoin = new Set<string>();
6608
8779
  const thenSub = this.childCtx(ctx);
6609
- const thenV = this.withKindNarrow(posGuard, ctx, () =>
8780
+ const thenV = this.withNarrowScope(ctx, "merge", () => this.withKindNarrow(posGuard, ctx, () =>
6610
8781
  this.emitExpr(expr.whenTrue, thenSub, expected ? unwrapOptional(expected) : expected),
6611
- );
8782
+ ), probeJoin);
6612
8783
  const elseSub = this.childCtx(ctx);
6613
- const elseV = this.withKindNarrow(negGuard, ctx, () => this.emitExpr(expr.whenFalse, elseSub, expected));
8784
+ const elseV = this.withNarrowScope(ctx, "merge", () =>
8785
+ this.withKindNarrow(negGuard, ctx, () => this.emitExpr(expr.whenFalse, elseSub, expected)), probeJoin);
6614
8786
  // The condition is evaluated exactly once, so it may lower statements
6615
8787
  // (array-method scans) into the surrounding ctx ahead of the branch.
6616
8788
  const condText = this.emitExpr(cond, ctx, { k: "bool" }).code;
6617
8789
  if (thenSub.lines.length === 0 && elseSub.lines.length === 0) {
8790
+ // The probes ARE the emission here: their kills are the join.
8791
+ this.applyJoinedNarrowKills(ctx, probeJoin);
6618
8792
  return { code: `if (${condText}) ${thenV.code} else ${elseV.code}` };
6619
8793
  }
6620
- // R17b-style lowering into an assignment target.
8794
+ // R17b-style lowering into an assignment target. probeJoin is discarded
8795
+ // with the probe lines — the re-emissions record the real kills.
8796
+ const join = new Set<string>();
6621
8797
  const t = expected ?? this.zTypeOfExpr(expr, ctx);
6622
8798
  const name = this.freshName(ctx, nameHint ?? "value");
6623
8799
  this.push(ctx, `var ${name}: ${this.table.zigTypeRef(t)} = undefined;`);
6624
8800
  this.push(ctx, `if (${condText}) {`);
6625
8801
  const ts1 = this.nestedCtx(ctx);
6626
- const v1 = this.withKindNarrow(posGuard, ctx, () =>
8802
+ const v1 = this.withNarrowScope(ctx, "merge", () => this.withKindNarrow(posGuard, ctx, () =>
6627
8803
  this.emitExpr(expr.whenTrue, ts1, expected ? unwrapOptional(expected) : expected),
6628
- );
8804
+ ), join);
6629
8805
  ts1.lines.push(" ".repeat(ts1.indent) + `${name} = ${v1.code};`);
6630
8806
  ctx.lines.push(...ts1.lines);
6631
8807
  this.push(ctx, `} else {`);
6632
8808
  const ts2 = this.nestedCtx(ctx);
6633
- const v2 = this.withKindNarrow(negGuard, ctx, () => this.emitExpr(expr.whenFalse, ts2, expected));
8809
+ const v2 = this.withNarrowScope(ctx, "merge", () =>
8810
+ this.withKindNarrow(negGuard, ctx, () => this.emitExpr(expr.whenFalse, ts2, expected)), join);
6634
8811
  ts2.lines.push(" ".repeat(ts2.indent) + `${name} = ${v2.code};`);
6635
8812
  ctx.lines.push(...ts2.lines);
6636
8813
  this.push(ctx, `}`);
8814
+ this.applyJoinedNarrowKills(ctx, join);
8815
+ return { code: name };
8816
+ }
8817
+
8818
+ /// R7-narrowed ternary: `if (target) |cap| <narrowed> else <other>`, with
8819
+ /// the capture substitution active over the arm TS narrows. Arms whose
8820
+ /// emission lowers statements (a spread literal builds its arena copy
8821
+ /// line by line; a nested lowered ternary needs its temp) cannot ride an
8822
+ /// if-EXPRESSION arm — the pushed lines would land above the conditional,
8823
+ /// running BOTH arms unconditionally and reading the capture before it
8824
+ /// binds. Those take the R17b statement lowering instead: a typed temp
8825
+ /// assigned under a statement if/else, so exactly the taken arm's
8826
+ /// statements run, once.
8827
+ private emitNarrowedTernary(
8828
+ expr: ts.ConditionalExpression,
8829
+ targetExpr: ts.Expression,
8830
+ narrowedArm: ts.Expression,
8831
+ otherArm: ts.Expression,
8832
+ ctx: Ctx,
8833
+ expected: ZType | undefined,
8834
+ nameHint: string | undefined,
8835
+ ): Emitted {
8836
+ // The callers gate on a read of the target (anyReadsTarget), which a
8837
+ // keyless target can never satisfy — the key is present here.
8838
+ const key = this.narrowKey(targetExpr)!;
8839
+ const target = this.emitExpr(targetExpr, ctx).code;
8840
+ const cap = this.freshName(ctx, this.narrowHint(targetExpr));
8841
+ const emitNarrowedArm = (sub: Ctx): string => {
8842
+ const saved = ctx.memberSubst.get(key);
8843
+ ctx.memberSubst.set(key, cap);
8844
+ const code = this.emitExpr(narrowedArm, sub, expected ? unwrapOptional(expected) : undefined).code;
8845
+ ctx.memberSubst.delete(key);
8846
+ if (saved !== undefined) ctx.memberSubst.set(key, saved);
8847
+ return code;
8848
+ };
8849
+ // Probe both arms in throwaway child ctxs: statement-free arms keep
8850
+ // the tight expression form (the common case — numbers, tags, field
8851
+ // reads — stays exactly as before). Each arm probes and emits from the
8852
+ // ENTRY state, kills joining after the last arm (see childCtx's
8853
+ // isolation law).
8854
+ const probeJoin = new Set<string>();
8855
+ const narrowedSub = this.childCtx(ctx);
8856
+ const narrowedV = this.withNarrowScope(ctx, "merge", () => emitNarrowedArm(narrowedSub), probeJoin);
8857
+ const otherSub = this.childCtx(ctx);
8858
+ const otherV = this.withNarrowScope(ctx, "merge", () => this.emitExpr(otherArm, otherSub, expected).code, probeJoin);
8859
+ if (narrowedSub.lines.length === 0 && otherSub.lines.length === 0) {
8860
+ // The probes ARE the emission here: their kills are the join.
8861
+ this.applyJoinedNarrowKills(ctx, probeJoin);
8862
+ return { code: `if (${target}) |${cap}| ${narrowedV} else ${otherV}` };
8863
+ }
8864
+ // R17b-style lowering: re-emit each arm into its own scoped block
8865
+ // feeding the temp (the probe lines are discarded — they were never
8866
+ // pushed to ctx, and probeJoin drops with them; the re-emissions
8867
+ // record the real kills).
8868
+ const join = new Set<string>();
8869
+ const t = expected ?? this.zTypeOfExpr(expr, ctx);
8870
+ const name = this.freshName(ctx, nameHint ?? "value");
8871
+ this.push(ctx, `var ${name}: ${this.table.zigTypeRef(t)} = undefined;`);
8872
+ this.push(ctx, `if (${target}) |${cap}| {`);
8873
+ const ts1 = this.nestedCtx(ctx);
8874
+ const v1 = this.withNarrowScope(ctx, "merge", () => emitNarrowedArm(ts1), join);
8875
+ ts1.lines.push(" ".repeat(ts1.indent) + `${name} = ${v1};`);
8876
+ ctx.lines.push(...ts1.lines);
8877
+ this.push(ctx, `} else {`);
8878
+ const ts2 = this.nestedCtx(ctx);
8879
+ const v2 = this.withNarrowScope(ctx, "merge", () => this.emitExpr(otherArm, ts2, expected).code, join);
8880
+ ts2.lines.push(" ".repeat(ts2.indent) + `${name} = ${v2};`);
8881
+ ctx.lines.push(...ts2.lines);
8882
+ this.push(ctx, `}`);
8883
+ this.applyJoinedNarrowKills(ctx, join);
6637
8884
  return { code: name };
6638
8885
  }
6639
8886
 
@@ -7277,7 +9524,16 @@ export class Emitter {
7277
9524
  const cap = this.freshName(ctx, hint);
7278
9525
  const sub = this.nestedCtx(ctx);
7279
9526
  sub.memberSubst = new Map(ctx.memberSubst);
7280
- sub.memberSubst.set(normalize(recv), cap);
9527
+ // The rewrite targets exactly this receiver NODE (emitCall re-emits
9528
+ // it under the capture). A receiver without a canonical narrowing key
9529
+ // still needs the rewrite, so it gets a node-scoped key — unique to
9530
+ // the node, never a narrowing fact another occurrence could match.
9531
+ let recvKey = this.narrowKey(recv);
9532
+ if (recvKey === null) {
9533
+ recvKey = `@recv#${this.narrowKeyNextId++}`;
9534
+ this.nodeNarrowKeys.set(recv, recvKey);
9535
+ }
9536
+ sub.memberSubst.set(recvKey, cap);
7281
9537
  const inner = this.emitCall(expr, sub, undefined, nameHint);
7282
9538
  const resT = this.zTypeOfExprClassed(expr, sub);
7283
9539
  if (resT.k === "void") this.fail(expr, `optional-chain call .${callee.name.text} without a mapped value type`);
@@ -7309,11 +9565,27 @@ export class Emitter {
7309
9565
  );
7310
9566
  }
7311
9567
  const body = cb.body.statements;
9568
+ // Every exit is terminal (a constant-true loop, or throws) with no
9569
+ // `return v` anywhere: tsc types the body `never`, but the labeled
9570
+ // value block below would carry a label no `break` uses — a Zig
9571
+ // compile error — and a callback that can never produce its value has
9572
+ // no useful emission anyway.
9573
+ if (!body.some((s) => containsReturn(s))) {
9574
+ this.fail(cb, "a callback none of whose paths returns a value (every path loops forever or throws)");
9575
+ }
7312
9576
  const last = body[body.length - 1];
7313
9577
  const earlyReturns = body.slice(0, -1).some((s) => containsReturn(s));
7314
9578
  if (last && ts.isReturnStatement(last) && last.expression && !earlyReturns) {
7315
- this.emitBlockStatements(body.slice(0, -1), sub);
7316
- return this.emitExpr(last.expression, sub, expected).code;
9579
+ // The prefix's guards narrow the trailing return's expression, so both
9580
+ // emit inside ONE flow scope — a scope around the prefix alone would
9581
+ // restore the maps before the expression they guard. The restore still
9582
+ // runs before the caller continues, so the callback's narrowing never
9583
+ // reaches its siblings in the emitted loop body.
9584
+ const trailing = last.expression;
9585
+ return this.withNarrowScope(sub, "merge", () => {
9586
+ this.emitStatementList(body.slice(0, -1), sub);
9587
+ return this.emitExpr(trailing, sub, expected).code;
9588
+ });
7317
9589
  }
7318
9590
  const label = this.freshName(sub, "cb");
7319
9591
  const name = this.freshName(sub, hint);
@@ -7323,9 +9595,15 @@ export class Emitter {
7323
9595
  inner.cmdReturn = null;
7324
9596
  inner.subReturn = null;
7325
9597
  inner.returnType = expected;
7326
- this.emitBlockStatements(body, inner);
9598
+ // The callback edge-kill stage: an arm that kills a narrow and then
9599
+ // `return`s exits along the lowered `break :label` edge, whose
9600
+ // destination is the continuation AFTER this value block — so its
9601
+ // kills apply here, once the block closes, and the arm's siblings and
9602
+ // the trailing in-callback flow keep the narrows tsc keeps there.
9603
+ const kills = this.stagedEdgeKills(sub, "callback", null, () => this.emitBlockStatements(body, inner));
7327
9604
  sub.lines.push(...inner.lines);
7328
9605
  this.push(sub, `};`);
9606
+ this.applyJoinedNarrowKills(sub, kills);
7329
9607
  return name;
7330
9608
  }
7331
9609
 
@@ -8111,8 +10389,15 @@ export class Emitter {
8111
10389
  const t = this.zTypeOfExprRaw(expr, ctx);
8112
10390
  // A narrowing substitution (null-guard capture or `.?` unwrap) proves
8113
10391
  // the value non-null for every use it rewrites, so the expression's
8114
- // effective type is the inner one.
8115
- if (t.k === "optional" && ctx.memberSubst.has(normalize(expr))) return t.inner;
10392
+ // effective type is the inner one. A RENAMING substitution — a union
10393
+ // payload capture whose field is itself optional — holds the payload
10394
+ // as-is and must keep the optional (stillOptionalSubst records those
10395
+ // by their exact replacement).
10396
+ if (t.k === "optional") {
10397
+ const key = this.narrowKey(expr);
10398
+ const rep = key === null ? undefined : ctx.memberSubst.get(key);
10399
+ if (key !== null && rep !== undefined && rep !== ctx.stillOptionalSubst.get(key)) return t.inner;
10400
+ }
8116
10401
  return t;
8117
10402
  }
8118
10403
 
@@ -8275,19 +10560,41 @@ export class Emitter {
8275
10560
  return ctx.thisType ?? { k: "void" };
8276
10561
  }
8277
10562
  if (ts.isConditionalExpression(expr)) {
8278
- // A null branch makes the ternary's VALUE optional (`hit === undefined
8279
- // ? null : hit.at` is `?i64`, not `i64`) — dropping it here would type
8280
- // locals non-optional and break every later null test on them.
8281
- const trueNull = expr.whenTrue.kind === ts.SyntaxKind.NullKeyword;
8282
- const falseNull = expr.whenFalse.kind === ts.SyntaxKind.NullKeyword;
8283
- if (trueNull && falseNull) return { k: "void" };
8284
- if (trueNull || falseNull) {
8285
- const t = this.zTypeOfExpr(trueNull ? expr.whenFalse : expr.whenTrue, ctx);
10563
+ // An empty branch — `null` or the global `undefined` — makes the
10564
+ // ternary's VALUE optional (`hit === undefined ? null : hit.at` is
10565
+ // `?i64`, not `i64`; `q === null ? undefined : q` stays `?P`) —
10566
+ // dropping it here would type locals non-optional and break every
10567
+ // later null test on them.
10568
+ const trueEmpty = this.isEmptyLiteral(expr.whenTrue);
10569
+ const falseEmpty = this.isEmptyLiteral(expr.whenFalse);
10570
+ if (trueEmpty && falseEmpty) return { k: "void" };
10571
+ if (trueEmpty || falseEmpty) {
10572
+ const t = this.zTypeOfExpr(trueEmpty ? expr.whenFalse : expr.whenTrue, ctx);
8286
10573
  return t.k === "optional" || t.k === "void" ? t : { k: "optional", inner: t };
8287
10574
  }
10575
+ // The condition's own null test narrows the arm that reuses the
10576
+ // tested value, exactly as tsc types it: `q === null ? {...f} : q`
10577
+ // and `q !== null ? q : {...f}` both VALUE as the non-optional Quote,
10578
+ // never `?Quote` — keeping the raw optional here types an inferred
10579
+ // local `?Quote` and its first non-optional use fails to compile.
10580
+ // The unwrap only holds when the OTHER arm cannot contribute null:
10581
+ // a known-optional other arm keeps the optional (its null flows
10582
+ // through), and the empty-literal arms (`null`/`undefined`, wrapped
10583
+ // or bare, in either position) were handled above.
10584
+ const missTest = this.emptyTestOf(expr.condition);
10585
+ const hitTest = this.emptyTestOf(expr.condition, ts.SyntaxKind.ExclamationEqualsEqualsToken);
10586
+ const narrowedByCond = (arm: ts.Expression, t: ZType, other: ts.Expression): ZType => {
10587
+ const test = arm === expr.whenFalse ? missTest : hitTest;
10588
+ if (test === null || t.k !== "optional") return t;
10589
+ const armKey = this.narrowKey(arm);
10590
+ if (armKey === null || armKey !== this.narrowKey(test.target)) return t;
10591
+ const otherT = this.zTypeOfExpr(other, ctx);
10592
+ return otherT.k === "optional" ? t : t.inner;
10593
+ };
8288
10594
  const t = this.zTypeOfExpr(expr.whenTrue, ctx);
8289
- if (t.k !== "void") return t;
8290
- return this.zTypeOfExpr(expr.whenFalse, ctx);
10595
+ if (t.k !== "void") return narrowedByCond(expr.whenTrue, t, expr.whenFalse);
10596
+ const f = this.zTypeOfExpr(expr.whenFalse, ctx);
10597
+ return narrowedByCond(expr.whenFalse, f, expr.whenTrue);
8291
10598
  }
8292
10599
  if (ts.isBinaryExpression(expr)) {
8293
10600
  const op = expr.operatorToken.kind;
@@ -8747,6 +11054,16 @@ function f64Literal(v: number): string {
8747
11054
  return /[.eE]/.test(s) ? s : `${s}.0`;
8748
11055
  }
8749
11056
 
11057
+ /// The UTF-8 byte length of literal text. The wire's length prefixes
11058
+ /// count BYTES, and the emitted Zig string literal carries the text as
11059
+ /// UTF-8, so every gate on a literal must count bytes too: `.length`
11060
+ /// counts UTF-16 code units and would pass a 200-character CJK name
11061
+ /// that arrives as 600 bytes, straight past the teaching and into the
11062
+ /// runtime's 255-byte length prefix.
11063
+ function utf8ByteLength(s: string): number {
11064
+ return Buffer.byteLength(s, "utf8");
11065
+ }
11066
+
8750
11067
  function escapeZigString(s: string): string {
8751
11068
  let out = "";
8752
11069
  for (const ch of s) {
@@ -8760,8 +11077,18 @@ function escapeZigString(s: string): string {
8760
11077
  return out;
8761
11078
  }
8762
11079
 
8763
- function normalize(expr: ts.Node): string {
8764
- return expr.getText().replace(/\s+/g, "");
11080
+ /// A block statement sitting directly in a statement list — a plain lexical
11081
+ /// block, where control always falls straight through. Everything else a
11082
+ /// Block can be (an if/else arm, a loop or callback body, a try/catch
11083
+ /// block, a labeled statement's body) is a merge context: control JOINS at
11084
+ /// its exit, so narrowing must bracket it there.
11085
+ function isPlainLexicalBlock(b: ts.Block): boolean {
11086
+ return (
11087
+ ts.isBlock(b.parent) ||
11088
+ ts.isSourceFile(b.parent) ||
11089
+ ts.isCaseClause(b.parent) ||
11090
+ ts.isDefaultClause(b.parent)
11091
+ );
8765
11092
  }
8766
11093
 
8767
11094
  function unwrapOptional(t: ZType): ZType {