@native-sdk/cli 0.5.3 → 0.6.0

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 (172) hide show
  1. package/build/app.zig +91 -2
  2. package/build.zig +756 -5
  3. package/build.zig.zon +7 -0
  4. package/native-sdk.d.ts +19 -1
  5. package/package.json +9 -9
  6. package/packages/core/package-lock.json +2 -2
  7. package/packages/core/package.json +1 -1
  8. package/packages/core/rt/rt.zig +416 -9
  9. package/packages/core/sdk/core.ts +706 -5
  10. package/packages/core/sdk/events.ts +17 -8
  11. package/packages/core/src/checker.ts +305 -2
  12. package/packages/core/src/diagnostics.ts +12 -0
  13. package/packages/core/src/emitter.ts +3187 -264
  14. package/packages/core/src/typed_ast.ts +51 -4
  15. package/packages/core/src/types.ts +34 -1
  16. package/skill-data/native-ui/SKILL.md +42 -4
  17. package/skill-data/ts-core/SKILL.md +13 -3
  18. package/src/app_runner/root.zig +112 -10
  19. package/src/app_runner/ts_core_main.zig +4 -0
  20. package/src/automation/layout_fingerprint.zig +160 -0
  21. package/src/automation/protocol.zig +82 -33
  22. package/src/automation/root.zig +1 -0
  23. package/src/automation/server.zig +1 -1
  24. package/src/automation/snapshot.zig +68 -9
  25. package/src/automation/watcher.zig +1 -1
  26. package/src/embed/host.zig +5 -0
  27. package/src/embed/tests.zig +119 -1
  28. package/src/embed/ui_host.zig +13 -0
  29. package/src/platform/linux/gtk_host.c +639 -16
  30. package/src/platform/linux/gtk_host.h +25 -0
  31. package/src/platform/linux/root.zig +351 -7
  32. package/src/platform/macos/appkit_host.h +152 -8
  33. package/src/platform/macos/appkit_host.m +1816 -100
  34. package/src/platform/macos/cef_host.mm +372 -11
  35. package/src/platform/macos/root.zig +379 -11
  36. package/src/platform/null_platform.zig +696 -9
  37. package/src/platform/null_platform_tests.zig +35 -0
  38. package/src/platform/root.zig +42 -0
  39. package/src/platform/types.zig +524 -18
  40. package/src/platform/windows/root.zig +432 -9
  41. package/src/platform/windows/webview2_host.cpp +482 -45
  42. package/src/primitives/app_manifest/comptime_scene.zig +5 -0
  43. package/src/primitives/app_manifest/root.zig +1 -0
  44. package/src/primitives/app_manifest/types.zig +32 -0
  45. package/src/primitives/app_manifest/validation.zig +18 -0
  46. package/src/primitives/canvas/a11y_audit.zig +33 -11
  47. package/src/primitives/canvas/a11y_audit_tests.zig +20 -0
  48. package/src/primitives/canvas/drawing.zig +25 -0
  49. package/src/primitives/canvas/equality.zig +8 -0
  50. package/src/primitives/canvas/events.zig +103 -16
  51. package/src/primitives/canvas/frame.zig +125 -1
  52. package/src/primitives/canvas/layout_audit.zig +22 -5
  53. package/src/primitives/canvas/markdown_hostile_tests.zig +8 -4
  54. package/src/primitives/canvas/render_tests.zig +13 -10
  55. package/src/primitives/canvas/root.zig +48 -0
  56. package/src/primitives/canvas/terminal_box.zig +471 -0
  57. package/src/primitives/canvas/terminal_grid.zig +978 -0
  58. package/src/primitives/canvas/terminal_grid_tests.zig +1093 -0
  59. package/src/primitives/canvas/test_support.zig +1 -0
  60. package/src/primitives/canvas/tests.zig +2 -0
  61. package/src/primitives/canvas/text_tests.zig +39 -4
  62. package/src/primitives/canvas/tokens.zig +115 -12
  63. package/src/primitives/canvas/ui.zig +535 -12
  64. package/src/primitives/canvas/ui_markup.zig +253 -36
  65. package/src/primitives/canvas/ui_markup_binary.zig +4 -1
  66. package/src/primitives/canvas/ui_markup_compiled.zig +195 -9
  67. package/src/primitives/canvas/ui_markup_compiled_tests.zig +188 -8
  68. package/src/primitives/canvas/ui_markup_contract.zig +89 -6
  69. package/src/primitives/canvas/ui_markup_contract_tests.zig +65 -1
  70. package/src/primitives/canvas/ui_markup_huge_document_tests.zig +154 -0
  71. package/src/primitives/canvas/ui_markup_huge_model_tests.zig +1 -0
  72. package/src/primitives/canvas/ui_markup_reflect.zig +75 -24
  73. package/src/primitives/canvas/ui_markup_tests.zig +178 -9
  74. package/src/primitives/canvas/ui_markup_view.zig +220 -11
  75. package/src/primitives/canvas/ui_markup_view_tests.zig +553 -28
  76. package/src/primitives/canvas/ui_schema.zig +110 -17
  77. package/src/primitives/canvas/ui_schema_tests.zig +18 -10
  78. package/src/primitives/canvas/ui_tests.zig +141 -9
  79. package/src/primitives/canvas/widget_access.zig +28 -2
  80. package/src/primitives/canvas/widget_anchored_tests.zig +48 -0
  81. package/src/primitives/canvas/widget_invalidation.zig +81 -1
  82. package/src/primitives/canvas/widget_layout.zig +59 -11
  83. package/src/primitives/canvas/widget_layout_tests.zig +125 -4
  84. package/src/primitives/canvas/widget_render.zig +272 -18
  85. package/src/primitives/canvas/widget_render_scroll.zig +108 -27
  86. package/src/primitives/canvas/widget_routing.zig +59 -7
  87. package/src/primitives/canvas/widget_runtime.zig +23 -0
  88. package/src/primitives/canvas/widget_runtime_tests.zig +149 -0
  89. package/src/primitives/canvas/widget_semantics.zig +119 -11
  90. package/src/primitives/canvas/widget_semantics_tests.zig +409 -0
  91. package/src/primitives/canvas/widget_tree.zig +17 -0
  92. package/src/primitives/canvas/widgets.zig +132 -0
  93. package/src/root.zig +23 -0
  94. package/src/runtime/api.zig +76 -5
  95. package/src/runtime/automation_commands.zig +20 -1
  96. package/src/runtime/automation_snapshot.zig +25 -1
  97. package/src/runtime/automation_widget_dispatch.zig +73 -8
  98. package/src/runtime/bridge_payload.zig +8 -0
  99. package/src/runtime/bridge_responses.zig +5 -0
  100. package/src/runtime/builtin_bridge.zig +9 -4
  101. package/src/runtime/canvas_font_tests.zig +439 -2
  102. package/src/runtime/canvas_fonts.zig +61 -6
  103. package/src/runtime/canvas_frame.zig +62 -7
  104. package/src/runtime/canvas_frame_animation_tests.zig +5 -4
  105. package/src/runtime/canvas_frame_helpers.zig +190 -1
  106. package/src/runtime/canvas_frame_invalidation_tests.zig +531 -0
  107. package/src/runtime/canvas_frame_patch_tests.zig +161 -10
  108. package/src/runtime/canvas_frame_retained_tests.zig +5 -2
  109. package/src/runtime/canvas_image_tests.zig +195 -0
  110. package/src/runtime/canvas_images.zig +45 -12
  111. package/src/runtime/canvas_widget_accessibility_tests.zig +1 -1
  112. package/src/runtime/canvas_widget_clipboard_tests.zig +40 -0
  113. package/src/runtime/canvas_widget_context_menu.zig +269 -32
  114. package/src/runtime/canvas_widget_context_menu_tests.zig +640 -14
  115. package/src/runtime/canvas_widget_display.zig +1 -1
  116. package/src/runtime/canvas_widget_event_tests.zig +1823 -0
  117. package/src/runtime/canvas_widget_events.zig +240 -24
  118. package/src/runtime/canvas_widget_runtime.zig +213 -29
  119. package/src/runtime/canvas_widget_scroll_driver_tests.zig +170 -7
  120. package/src/runtime/canvas_widget_scroll_drivers.zig +151 -17
  121. package/src/runtime/canvas_widget_scroll_tests.zig +435 -23
  122. package/src/runtime/canvas_widget_state.zig +6 -0
  123. package/src/runtime/canvas_widget_text_tests.zig +1 -1
  124. package/src/runtime/core.zig +131 -13
  125. package/src/runtime/effects.zig +8136 -180
  126. package/src/runtime/effects_channel_tests.zig +3519 -0
  127. package/src/runtime/effects_fetch_tests.zig +89 -1
  128. package/src/runtime/effects_file_tests.zig +41 -1
  129. package/src/runtime/effects_image_tests.zig +1304 -0
  130. package/src/runtime/effects_pty_tests.zig +1362 -0
  131. package/src/runtime/effects_tests.zig +167 -9
  132. package/src/runtime/effects_video_tests.zig +3609 -0
  133. package/src/runtime/flow.zig +42 -4
  134. package/src/runtime/gpu_surface_events.zig +473 -13
  135. package/src/runtime/media_surface.zig +116 -11
  136. package/src/runtime/media_surface_tests.zig +61 -0
  137. package/src/runtime/pty.zig +1252 -0
  138. package/src/runtime/pty_windows.zig +1780 -0
  139. package/src/runtime/root.zig +36 -0
  140. package/src/runtime/runtime_event_tests.zig +20 -1
  141. package/src/runtime/session_blobs.zig +689 -0
  142. package/src/runtime/session_journal.zig +432 -62
  143. package/src/runtime/session_record.zig +43 -2
  144. package/src/runtime/session_replay.zig +556 -20
  145. package/src/runtime/session_tests.zig +2087 -1
  146. package/src/runtime/shell_layout.zig +7 -0
  147. package/src/runtime/terminal_session.zig +1569 -0
  148. package/src/runtime/terminal_session_tests.zig +450 -0
  149. package/src/runtime/terminal_vt_ghostty.zig +15 -0
  150. package/src/runtime/terminal_vt_stub.zig +13 -0
  151. package/src/runtime/testdata/fonts/NotoSansSC-Receipt.ttf +0 -0
  152. package/src/runtime/testdata/fonts/OFL.txt +93 -0
  153. package/src/runtime/tests.zig +8 -0
  154. package/src/runtime/ts_core_host.zig +1320 -45
  155. package/src/runtime/ts_core_host_tests.zig +1100 -1
  156. package/src/runtime/ts_ui_app.zig +23 -5
  157. package/src/runtime/ui_app.zig +2444 -69
  158. package/src/runtime/ui_app_tests.zig +3171 -744
  159. package/src/runtime/ui_app_virtual_variable_tests.zig +4 -2
  160. package/src/runtime/ui_app_window_tests.zig +736 -0
  161. package/src/runtime/view.zig +190 -2
  162. package/src/runtime/view_widget_scroll.zig +218 -68
  163. package/src/runtime/view_widget_text.zig +11 -2
  164. package/src/runtime/view_widget_tree.zig +111 -3
  165. package/src/runtime/window_command_bridge_tests.zig +117 -0
  166. package/src/runtime/window_storage.zig +77 -2
  167. package/src/runtime/window_view_runtime.zig +34 -2
  168. package/src/runtime/window_views.zig +62 -1
  169. package/src/terminal_session_tests_root.zig +15 -0
  170. package/src/tooling/manifest.zig +75 -0
  171. package/src/tooling/raw_manifest.zig +2 -0
  172. package/src/tooling/templates.zig +244 -8
@@ -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,13 @@ 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;
221
+ const MAX_VIDEO_PATH_BYTES = 1024;
222
+ const MAX_PTY_TERM_BYTES = 32;
223
+ const MAX_PTY_WRITE_BYTES = 4096;
224
+ /// Terminal grids ride the wire as f64 subset numbers; the engine's
225
+ /// transport is u16 — the largest grid a pty can declare.
226
+ const MAX_PTY_DIMENSION = 65535;
143
227
 
144
228
  /// The closed `Cmd.fetch` verb set, wire value = position.
145
229
  const FETCH_METHODS = ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD"];
@@ -149,6 +233,35 @@ const FETCH_METHODS = ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD"];
149
233
  /// the app's own).
150
234
  const AUDIO_STATES = ["loaded", "position", "completed", "failed", "rejected", "spectrum"];
151
235
 
236
+ /// The video event states an event arm's `state` union must carry — the
237
+ /// engine's event vocabulary, matched by member NAME (declaration order is
238
+ /// the app's own).
239
+ const VIDEO_STATES = ["loaded", "position", "completed", "failed", "rejected"];
240
+
241
+ /// The image load result states an event arm's `state` union must carry —
242
+ /// the engine's outcome vocabulary, matched by member NAME (declaration
243
+ /// order is the app's own).
244
+ const IMAGE_STATES = [
245
+ "loaded", "rejected", "not_found", "io_failed", "connect_failed", "tls_failed",
246
+ "protocol_failed", "timed_out", "http_status", "cancelled", "too_large",
247
+ "unsupported", "decode_failed", "registry_full", "alloc_failed",
248
+ ];
249
+
250
+ /// The external-source channel event states an event arm's `state`
251
+ /// union must carry — the engine's vocabulary, matched by member NAME
252
+ /// (declaration order is the app's own).
253
+ const CHANNEL_STATES = ["data", "closed", "rejected"];
254
+
255
+ /// The pty session event states an event arm's `state` union must carry
256
+ /// — the engine's vocabulary, matched by member NAME (declaration order
257
+ /// is the app's own).
258
+ const PTY_STATES = ["output", "exit"];
259
+
260
+ /// The pty exit reasons an event arm's `reason` union must carry — the
261
+ /// spawn exit vocabulary, matched by member NAME (declaration order is
262
+ /// the app's own).
263
+ const PTY_EXIT_REASONS = ["exited", "signaled", "cancelled", "rejected", "spawn_failed"];
264
+
152
265
  /// Names the emitted module's own fixtures occupy (header helpers + commit
153
266
  /// machinery): module-level claims and function locals unique around them.
154
267
  const emittedFixtureNames = [
@@ -169,6 +282,17 @@ const AUDIO_VERBS: Record<string, string> = {
169
282
  audioSetVolume: ".volume",
170
283
  };
171
284
 
285
+ /// The `Cmd.video*` control verbs and their zig enum literals.
286
+ const VIDEO_VERBS: Record<string, string> = {
287
+ videoPlay: ".play",
288
+ videoPause: ".pause",
289
+ videoStop: ".stop",
290
+ videoSeek: ".seek",
291
+ videoSetVolume: ".volume",
292
+ videoSetMuted: ".muted",
293
+ videoSetLoop: ".loop",
294
+ };
295
+
172
296
  export class Emitter {
173
297
  private readonly out: string[] = [];
174
298
 
@@ -225,6 +349,10 @@ export class Emitter {
225
349
  private readonly genericNames = new Set<string>();
226
350
  private readonly sourceName: string;
227
351
  private readonly capacities: KernelCapacities;
352
+ /// Per-switch memo for the defaultless value-switch exhaustiveness
353
+ /// consult (alwaysExits re-asks along every kill-routing scan).
354
+ private switchCoversTypeMemo = new WeakMap<ts.SwitchStatement, boolean>();
355
+
228
356
  /// Computed once at the top of emitModule (before any type emission).
229
357
  private helpers: ModelHelper[] = [];
230
358
  private unbound: { model: string[]; msg: string[] } = { model: [], msg: [] };
@@ -972,7 +1100,10 @@ export class Emitter {
972
1100
  names: new Map(),
973
1101
  used: this.moduleScopeNames(),
974
1102
  memberSubst: new Map(),
1103
+ stillOptionalSubst: new Map(),
975
1104
  narrowedUnion: new Map(),
1105
+ narrowKilled: [],
1106
+ edgeKills: [],
976
1107
  localTypes: new Map(),
977
1108
  builders: new Map(),
978
1109
  retLabel: null,
@@ -1043,8 +1174,47 @@ export class Emitter {
1043
1174
  const name = this.moduleNameOf(decl) ?? decl.name.text;
1044
1175
  // The dead-state opt-out list is transpiler config, not module data:
1045
1176
  // already validated and routed into the Model/Msg `view_unbound`
1046
- // declarations (viewUnboundNames), nothing to emit here.
1177
+ // declarations (viewUnboundNames), nothing to emit here. The split
1178
+ // modelUnbound/msgUnbound pair spells the same facts for contract
1179
+ // consumers that read declarations per side; this lane reads
1180
+ // viewUnbound only, so the pair passes through unemitted — but the
1181
+ // names stay RESERVED contract vocabulary: a data const under either
1182
+ // spelling would emit no declaration while its references still
1183
+ // emit, so anything but the list shape refuses here.
1047
1184
  if (name === "viewUnbound") continue;
1185
+ if (name === "modelUnbound" || name === "msgUnbound") {
1186
+ let init = decl.initializer;
1187
+ while (ts.isParenthesizedExpression(init) || ts.isAsExpression(init) || ts.isSatisfiesExpression(init)) init = init.expression;
1188
+ if (!ts.isArrayLiteralExpression(init) || init.elements.some((el) => !ts.isStringLiteral(el))) {
1189
+ this.fail(decl, `\`${name}\` is the contract's unbound-list vocabulary and must be a const array of string literals; rename the constant to keep it as module data`, "NS1032");
1190
+ }
1191
+ // The split pair RESTATES viewUnbound's facts for consumers
1192
+ // that read declarations per side, so its entries must resolve
1193
+ // and the resolved sets must be one set — two spellings of one
1194
+ // fact can never disagree.
1195
+ const entries = init.elements.map((el) => (el as ts.StringLiteral).text);
1196
+ const resolved = name === "modelUnbound" ? this.unbound.model : this.unbound.msg;
1197
+ const side = name === "modelUnbound" ? "Model field or exported model helper" : "Msg kind";
1198
+ for (const entry of entries) {
1199
+ if (!resolved.includes(entry)) {
1200
+ this.fail(
1201
+ decl,
1202
+ `\`${name}\` names \`"${entry}"\`, which \`viewUnbound\` does not resolve as a ${side} — the split pair restates viewUnbound's facts, so declare the name there (and as a real ${side}) first`,
1203
+ "NS1032",
1204
+ );
1205
+ }
1206
+ }
1207
+ for (const entry of resolved) {
1208
+ if (!entries.includes(entry)) {
1209
+ this.fail(
1210
+ decl,
1211
+ `\`${name}\` is missing \`"${entry}"\`, which \`viewUnbound\` declares on this side — the split pair restates viewUnbound's facts, never a subset of them`,
1212
+ "NS1032",
1213
+ );
1214
+ }
1215
+ }
1216
+ continue;
1217
+ }
1048
1218
  // The env override channel: a declarative table the generated wiring
1049
1219
  // walks at comptime (read the named variables once at launch,
1050
1220
  // dispatch each present value through its bytes arm).
@@ -1349,7 +1519,10 @@ export class Emitter {
1349
1519
  names: new Map(),
1350
1520
  used: new Set(),
1351
1521
  memberSubst: new Map(),
1522
+ stillOptionalSubst: new Map(),
1352
1523
  narrowedUnion: new Map(),
1524
+ narrowKilled: [],
1525
+ edgeKills: [],
1353
1526
  localTypes: new Map(),
1354
1527
  builders: new Map(),
1355
1528
  retLabel: null,
@@ -1460,7 +1633,7 @@ export class Emitter {
1460
1633
 
1461
1634
  // ------------------------------------------------------------------ types
1462
1635
 
1463
- private emitStruct(decl: ts.InterfaceDeclaration | ts.ClassDeclaration): void {
1636
+ private emitStruct(decl: ts.InterfaceDeclaration | ts.ClassDeclaration | ts.TypeAliasDeclaration): void {
1464
1637
  if (!decl.name) return;
1465
1638
  const info = this.table.structs.get(decl.name.text);
1466
1639
  if (!info) return;
@@ -1605,7 +1778,10 @@ export class Emitter {
1605
1778
  names: new Map(),
1606
1779
  used: this.moduleScopeNames(),
1607
1780
  memberSubst: new Map(),
1781
+ stillOptionalSubst: new Map(),
1608
1782
  narrowedUnion: new Map(),
1783
+ narrowKilled: [],
1784
+ edgeKills: [],
1609
1785
  localTypes: new Map(),
1610
1786
  builders: new Map(),
1611
1787
  retLabel: null,
@@ -1785,6 +1961,13 @@ export class Emitter {
1785
1961
  this.out.push(`};`);
1786
1962
  return;
1787
1963
  }
1964
+ const st = this.table.structs.get(name);
1965
+ if (st && st.decl === decl) {
1966
+ // An object-literal alias is a struct like an interface (the alias
1967
+ // form is a contract projection's value-storage spelling).
1968
+ this.emitStruct(decl);
1969
+ return;
1970
+ }
1788
1971
  const target = this.table.plainAliases.get(name);
1789
1972
  if (target) {
1790
1973
  this.out.push(`${pub}const ${name} = ${target};`);
@@ -1829,7 +2012,10 @@ export class Emitter {
1829
2012
  names: new Map(),
1830
2013
  used: this.moduleScopeNames(),
1831
2014
  memberSubst: new Map(),
2015
+ stillOptionalSubst: new Map(),
1832
2016
  narrowedUnion: new Map(),
2017
+ narrowKilled: [],
2018
+ edgeKills: [],
1833
2019
  localTypes: new Map(),
1834
2020
  builders: new Map(),
1835
2021
  retLabel: null,
@@ -2054,7 +2240,7 @@ export class Emitter {
2054
2240
  if (method === "host") {
2055
2241
  const nameArg = e.arguments[0];
2056
2242
  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");
2243
+ if (utf8ByteLength(nameArg.text) > 255) this.fail(nameArg, "Cmd.host name over 255 bytes");
2058
2244
  const rest = e.arguments.slice(1);
2059
2245
  // One bytes/record argument is the v2 payload form (host_bytes on
2060
2246
  // the wire); a payload with anything alongside it has no encoding.
@@ -2083,7 +2269,7 @@ export class Emitter {
2083
2269
  if (method === "request") {
2084
2270
  const nameArg = e.arguments[0];
2085
2271
  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");
2272
+ if (utf8ByteLength(nameArg.text) > 255) this.fail(nameArg, "Cmd.request name over 255 bytes");
2087
2273
  const payloadArg = e.arguments[1];
2088
2274
  if (!payloadArg) this.fail(e, "Cmd.request payload (bytes or a flat record)");
2089
2275
  if (!this.isHostPayloadArg(payloadArg, ctx)) {
@@ -2102,7 +2288,7 @@ export class Emitter {
2102
2288
  if (!keyArg || !ts.isStringLiteral(keyArg)) {
2103
2289
  this.fail(e, `\`Cmd.cancel\` takes the effect key as a string literal`, "NS1027");
2104
2290
  }
2105
- if (keyArg.text.length > 255) this.fail(keyArg, "Cmd.cancel key over 255 bytes");
2291
+ if (utf8ByteLength(keyArg.text) > 255) this.fail(keyArg, "Cmd.cancel key over 255 bytes");
2106
2292
  return `rt.cmdCancel("${escapeZigString(keyArg.text)}")`;
2107
2293
  }
2108
2294
  if (method === "readFile") {
@@ -2137,7 +2323,7 @@ export class Emitter {
2137
2323
  if (!keyArg || !ts.isStringLiteral(keyArg)) {
2138
2324
  this.fail(e, `\`Cmd.delay\` takes its key as a string literal`, "NS1027");
2139
2325
  }
2140
- if (keyArg.text.length > 255) this.fail(keyArg, "Cmd.delay key over 255 bytes");
2326
+ if (utf8ByteLength(keyArg.text) > 255) this.fail(keyArg, "Cmd.delay key over 255 bytes");
2141
2327
  const msArg = e.arguments[1];
2142
2328
  if (!msArg) this.fail(e, "Cmd.delay interval (milliseconds)");
2143
2329
  // The engine bound is 1ms..one year; a compile-time-known interval
@@ -2161,9 +2347,111 @@ export class Emitter {
2161
2347
  if (method === "audioPlay") {
2162
2348
  return this.emitAudioPlayCmd(e, ctx);
2163
2349
  }
2350
+ if (method === "imageLoad") {
2351
+ return this.emitImageLoadCmd(e, ctx);
2352
+ }
2353
+ if (method === "imageCancel") {
2354
+ const idArg = e.arguments[0];
2355
+ if (!idArg) this.fail(e, "`Cmd.imageCancel` id (the model-owned numeric ImageId)", "NS1027");
2356
+ // The same literal gate as imageLoad: an id no load could ever
2357
+ // park under has nothing to cancel — stop the build instead of
2358
+ // shipping a certain runtime no-op. Dynamic ids stay the host's
2359
+ // (an unknown id is the documented no-op).
2360
+ const idLiteral = this.numberLiteralValue(idArg);
2361
+ if (idLiteral !== null && !(Number.isSafeInteger(idLiteral) && idLiteral >= 1)) {
2362
+ this.fail(idArg, `\`Cmd.imageCancel\` id ${idLiteral} is not a positive integer ImageId below 2^53`, "NS1030");
2363
+ }
2364
+ const id = this.emitExpr(idArg, ctx, { k: "f64" }).code;
2365
+ return `rt.cmdImageCancel(${id})`;
2366
+ }
2367
+ if (method === "imageUnregister") {
2368
+ const idArg = e.arguments[0];
2369
+ if (!idArg) this.fail(e, "`Cmd.imageUnregister` id (the model-owned numeric ImageId)", "NS1027");
2370
+ // The same literal gate as imageLoad/imageCancel: an id no load
2371
+ // could ever register under has nothing to unregister — stop the
2372
+ // build instead of shipping a certain runtime no-op. Dynamic ids
2373
+ // stay the host's (an unregistered id is the documented no-op).
2374
+ const idLiteral = this.numberLiteralValue(idArg);
2375
+ if (idLiteral !== null && !(Number.isSafeInteger(idLiteral) && idLiteral >= 1)) {
2376
+ this.fail(idArg, `\`Cmd.imageUnregister\` id ${idLiteral} is not a positive integer ImageId below 2^53`, "NS1030");
2377
+ }
2378
+ const id = this.emitExpr(idArg, ctx, { k: "f64" }).code;
2379
+ return `rt.cmdImageUnregister(${id})`;
2380
+ }
2381
+ if (method === "channelOpen") {
2382
+ return this.emitChannelOpenCmd(e, ctx);
2383
+ }
2384
+ if (method === "channelClose") {
2385
+ const keyArg = e.arguments[0];
2386
+ if (!keyArg) this.fail(e, "`Cmd.channelClose` key (the app's numeric channel key)", "NS1027");
2387
+ // The same literal gate as imageCancel: a key no channel could
2388
+ // ever open under has nothing to close — stop the build instead
2389
+ // of shipping a certain runtime no-op. Dynamic keys stay the
2390
+ // host's (an unknown key is the documented no-op).
2391
+ const keyLiteral = this.numberLiteralValue(keyArg);
2392
+ if (keyLiteral !== null && !(Number.isSafeInteger(keyLiteral) && keyLiteral >= 1)) {
2393
+ this.fail(keyArg, `\`Cmd.channelClose\` key ${keyLiteral} is not a positive integer channel key below 2^53`, "NS1030");
2394
+ }
2395
+ const key = this.emitExpr(keyArg, ctx, { k: "f64" }).code;
2396
+ return `rt.cmdChannelClose(${key})`;
2397
+ }
2398
+ if (method === "ptySpawn") {
2399
+ return this.emitPtySpawnCmd(e, ctx);
2400
+ }
2401
+ if (method === "ptyWrite") {
2402
+ const keyArg = e.arguments[0];
2403
+ if (!keyArg || !ts.isStringLiteral(keyArg)) {
2404
+ this.fail(e, `\`Cmd.ptyWrite\` takes its key as a string literal`, "NS1027");
2405
+ }
2406
+ if (utf8ByteLength(keyArg.text) > 255) this.fail(keyArg, "Cmd.ptyWrite key over 255 bytes");
2407
+ // Keystrokes and pastes, not bulk transfers: a compile-time-known
2408
+ // payload over the engine's per-write bound stops the build;
2409
+ // dynamic bytes stay the engine's, counted into droppedWrites.
2410
+ const bytes = this.effectBytesArg(e, e.arguments[1], "Cmd.ptyWrite bytes", MAX_PTY_WRITE_BYTES, ctx);
2411
+ return `rt.cmdPtyWrite("${escapeZigString(keyArg.text)}", ${bytes})`;
2412
+ }
2413
+ if (method === "ptyResize") {
2414
+ const keyArg = e.arguments[0];
2415
+ if (!keyArg || !ts.isStringLiteral(keyArg)) {
2416
+ this.fail(e, `\`Cmd.ptyResize\` takes its key as a string literal`, "NS1027");
2417
+ }
2418
+ if (utf8ByteLength(keyArg.text) > 255) this.fail(keyArg, "Cmd.ptyResize key over 255 bytes");
2419
+ const cols = this.ptyDimensionArg(e, e.arguments[1], "Cmd.ptyResize", "cols", ctx);
2420
+ const rows = this.ptyDimensionArg(e, e.arguments[2], "Cmd.ptyResize", "rows", ctx);
2421
+ return `rt.cmdPtyResize("${escapeZigString(keyArg.text)}", ${cols}, ${rows})`;
2422
+ }
2423
+ if (method === "ptyKill") {
2424
+ const keyArg = e.arguments[0];
2425
+ if (!keyArg || !ts.isStringLiteral(keyArg)) {
2426
+ this.fail(e, `\`Cmd.ptyKill\` takes its key as a string literal`, "NS1027");
2427
+ }
2428
+ if (utf8ByteLength(keyArg.text) > 255) this.fail(keyArg, "Cmd.ptyKill key over 255 bytes");
2429
+ return `rt.cmdPtyKill("${escapeZigString(keyArg.text)}")`;
2430
+ }
2164
2431
  if (method in AUDIO_VERBS) {
2165
2432
  return this.emitAudioCtlCmd(e, method, ctx);
2166
2433
  }
2434
+ if (method === "videoLoad") {
2435
+ return this.emitVideoLoadCmd(e, ctx);
2436
+ }
2437
+ if (method in VIDEO_VERBS) {
2438
+ return this.emitVideoCtlCmd(e, method, ctx);
2439
+ }
2440
+ if (method === "showWindow") {
2441
+ // Window labels are declarations (app.zon / the scene), so the
2442
+ // verb takes the label as a string literal — the same discipline
2443
+ // effect keys ride (NS1027).
2444
+ const labelArg = e.arguments[0];
2445
+ if (!labelArg || !ts.isStringLiteral(labelArg)) {
2446
+ this.fail(e, `\`Cmd.showWindow\` takes the declared window label as a string literal`, "NS1027");
2447
+ }
2448
+ if (utf8ByteLength(labelArg.text) > 255) this.fail(labelArg, "Cmd.showWindow label over 255 bytes");
2449
+ return `rt.cmdWindowShow("${escapeZigString(labelArg.text)}")`;
2450
+ }
2451
+ if (method === "quitApp") {
2452
+ if (e.arguments.length !== 0) this.fail(e, "Cmd.quitApp takes no arguments");
2453
+ return "rt.cmdQuitApp()";
2454
+ }
2167
2455
  if (method === "batch") {
2168
2456
  const arr = e.arguments[0];
2169
2457
  if (!arr || !ts.isArrayLiteralExpression(arr)) this.fail(e, "Cmd.batch argument (an array literal in v1)");
@@ -2173,7 +2461,7 @@ export class Emitter {
2173
2461
  }
2174
2462
  this.fail(
2175
2463
  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)`,
2464
+ `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, videoLoad, videoPlay, videoPause, videoStop, videoSeek, videoSetVolume, videoSetMuted, videoSetLoop, showWindow, quitApp, imageLoad, imageCancel, imageUnregister, channelOpen, channelClose, ptySpawn, ptyWrite, ptyResize, ptyKill, batch)`,
2177
2465
  );
2178
2466
  }
2179
2467
  this.fail(expr, "command expression (Cmd values are built inline from the Cmd.* factories)");
@@ -2215,7 +2503,7 @@ export class Emitter {
2215
2503
  );
2216
2504
  }
2217
2505
  if (p.name.text === "key") {
2218
- if (v.text.length > 255) this.fail(v, "Cmd.request key over 255 bytes");
2506
+ if (utf8ByteLength(v.text) > 255) this.fail(v, "Cmd.request key over 255 bytes");
2219
2507
  key = v.text;
2220
2508
  } else if (p.name.text === "ok") ok = v;
2221
2509
  else if (p.name.text === "err") err = v;
@@ -2347,7 +2635,7 @@ export class Emitter {
2347
2635
  );
2348
2636
  }
2349
2637
  if (name === "key") {
2350
- if (v.text.length > 255) this.fail(v, "Cmd.spawn key over 255 bytes");
2638
+ if (utf8ByteLength(v.text) > 255) this.fail(v, "Cmd.spawn key over 255 bytes");
2351
2639
  key = v.text;
2352
2640
  } else if (name === "line") line = v;
2353
2641
  else if (name === "exit") exit = v;
@@ -2382,7 +2670,7 @@ export class Emitter {
2382
2670
  if (!keyArg || !ts.isStringLiteral(keyArg)) {
2383
2671
  this.fail(e, `\`Cmd.audioPlay\` takes its key as a string literal`, "NS1027");
2384
2672
  }
2385
- if (keyArg.text.length > 255) this.fail(keyArg, "Cmd.audioPlay key over 255 bytes");
2673
+ if (utf8ByteLength(keyArg.text) > 255) this.fail(keyArg, "Cmd.audioPlay key over 255 bytes");
2386
2674
 
2387
2675
  let source = e.arguments[1];
2388
2676
  while (source && (ts.isParenthesizedExpression(source) || ts.isAsExpression(source) || ts.isSatisfiesExpression(source))) source = source.expression;
@@ -2450,6 +2738,401 @@ export class Emitter {
2450
2738
  return `rt.cmdAudioPlay("${escapeZigString(keyArg.text)}", ${tag}, ${audio_path}, ${url}, ${cache_path}, ${expected})`;
2451
2739
  }
2452
2740
 
2741
+ /// `Cmd.imageLoad(id, source, route)`: the app's numeric ImageId (any
2742
+ /// number expression — ids are model data), an inline
2743
+ /// `{ path?, url?, cachePath?, expectedBytes? }` source (at least one of
2744
+ /// path/url), and the `{ event }` routing whose arm carries the five
2745
+ /// SDK-fixed image result fields.
2746
+ private emitImageLoadCmd(e: ts.CallExpression, ctx: Ctx): string {
2747
+ const idArg = e.arguments[0];
2748
+ if (!idArg) this.fail(e, "`Cmd.imageLoad` id (the model-owned numeric ImageId)", "NS1027");
2749
+ // A compile-time-known id the engine is certain to refuse stops the
2750
+ // build; dynamic ids stay the host's to validate through the
2751
+ // "rejected" result state. The bound is strictly BELOW 2^53
2752
+ // (Number.isSafeInteger for a positive value): 2^53 itself is the
2753
+ // first f64 that aliases a neighbor (2^53 + 1), so the host rejects
2754
+ // it too rather than guess which integer the app meant.
2755
+ const idLiteral = this.numberLiteralValue(idArg);
2756
+ if (idLiteral !== null && !(Number.isSafeInteger(idLiteral) && idLiteral >= 1)) {
2757
+ this.fail(idArg, `\`Cmd.imageLoad\` id ${idLiteral} is not a positive integer ImageId below 2^53`, "NS1030");
2758
+ }
2759
+ const id = this.emitExpr(idArg, ctx, { k: "f64" }).code;
2760
+
2761
+ let source = e.arguments[1];
2762
+ while (source && (ts.isParenthesizedExpression(source) || ts.isAsExpression(source) || ts.isSatisfiesExpression(source))) source = source.expression;
2763
+ if (!source || !ts.isObjectLiteralExpression(source)) {
2764
+ this.fail(
2765
+ e.arguments[1] ?? e,
2766
+ `\`Cmd.imageLoad\` takes an inline \`{ path?, url?, cachePath?, expectedBytes? }\` source object`,
2767
+ "NS1029",
2768
+ );
2769
+ }
2770
+ let image_path = '""';
2771
+ let url = '""';
2772
+ let cache_path = '""';
2773
+ let expected = "0";
2774
+ let has_source = false;
2775
+ for (const p of source.properties) {
2776
+ if (!ts.isPropertyAssignment(p) || !ts.isIdentifier(p.name)) {
2777
+ this.fail(p, `\`Cmd.imageLoad\` source member \`${p.getText()}\` is not a plain property`, "NS1029");
2778
+ }
2779
+ const name = p.name.text;
2780
+ if (name === "path") {
2781
+ image_path = this.effectBytesArg(e, p.initializer, "Cmd.imageLoad path", MAX_IMAGE_PATH_BYTES, ctx);
2782
+ has_source = true;
2783
+ } else if (name === "url") {
2784
+ url = this.effectBytesArg(e, p.initializer, "Cmd.imageLoad url", MAX_URL_BYTES, ctx);
2785
+ has_source = true;
2786
+ } else if (name === "cachePath") {
2787
+ cache_path = this.effectBytesArg(e, p.initializer, "Cmd.imageLoad cachePath", MAX_IMAGE_PATH_BYTES, ctx);
2788
+ } else if (name === "expectedBytes") {
2789
+ // A byte count is a whole number: file sizes have no fractional
2790
+ // bytes, and a fractional value would truncate on the host into
2791
+ // a size the app never declared — cache verification against
2792
+ // the wrong size re-downloads on every launch. The bound is the
2793
+ // id gate's (Number.isSafeInteger): past 2^53 the f64 wire
2794
+ // cannot carry the count exactly. Dynamic values stay the
2795
+ // host's, which maps unrepresentable counts to "unknown size".
2796
+ const literal = this.numberLiteralValue(p.initializer);
2797
+ if (literal !== null && !(Number.isSafeInteger(literal) && literal >= 0)) {
2798
+ this.fail(p.initializer, `\`Cmd.imageLoad\` expectedBytes ${literal} is not a whole-number byte count below 2^53`, "NS1030");
2799
+ }
2800
+ expected = this.emitExpr(p.initializer, ctx, { k: "f64" }).code;
2801
+ } else {
2802
+ this.fail(p, `\`Cmd.imageLoad\` source member \`${name}\``, "NS1029");
2803
+ }
2804
+ }
2805
+ if (!has_source) {
2806
+ this.fail(source, `\`Cmd.imageLoad\` source without a \`path\` or a \`url\` — nothing could load`, "NS1029");
2807
+ }
2808
+
2809
+ let route = e.arguments[2];
2810
+ while (route && (ts.isParenthesizedExpression(route) || ts.isAsExpression(route) || ts.isSatisfiesExpression(route))) route = route.expression;
2811
+ if (!route || !ts.isObjectLiteralExpression(route)) {
2812
+ this.fail(e.arguments[2] ?? e, `\`Cmd.imageLoad\` routing is an inline \`{ event }\` object`, "NS1027");
2813
+ }
2814
+ let event: ts.StringLiteral | null = null;
2815
+ for (const p of route.properties) {
2816
+ if (!ts.isPropertyAssignment(p) || !ts.isIdentifier(p.name)) {
2817
+ this.fail(p, `\`Cmd.imageLoad\` routing member \`${p.getText()}\` is not a plain property`, "NS1027");
2818
+ }
2819
+ let v: ts.Expression = p.initializer;
2820
+ while (ts.isParenthesizedExpression(v) || ts.isAsExpression(v) || ts.isSatisfiesExpression(v)) v = v.expression;
2821
+ if (p.name.text !== "event") {
2822
+ this.fail(p, `\`Cmd.imageLoad\` routing member \`${p.name.text}\``, "NS1027");
2823
+ }
2824
+ if (!ts.isStringLiteral(v)) {
2825
+ this.fail(p.initializer, `\`Cmd.imageLoad\` event arm is not a string literal`, "NS1027");
2826
+ }
2827
+ event = v;
2828
+ }
2829
+ if (!event) this.fail(route, `\`Cmd.imageLoad\` routing without an \`event\` arm`, "NS1027");
2830
+ const tag = this.imageEventArmTag(event, ctx);
2831
+ return `rt.cmdImageLoad(${id}, ${tag}, ${image_path}, ${url}, ${cache_path}, ${expected})`;
2832
+ }
2833
+
2834
+ /// Resolve the image result arm: exactly the five SDK-fixed fields,
2835
+ /// matched by NAME — id (a number: the requested ImageId echoed
2836
+ /// verbatim), state (a named literal-union alias carrying exactly the
2837
+ /// fifteen image states, any order), width/height/status (numbers).
2838
+ private imageEventArmTag(arg: ts.StringLiteral, ctx: Ctx): string {
2839
+ const unionName = ctx.cmdReturn!.msgUnion;
2840
+ const info = this.table.unions.get(unionName);
2841
+ if (!info) this.fail(arg, `unknown union ${unionName}`);
2842
+ const arm = info.arms.find((a) => a.tag === arg.text);
2843
+ if (!arm) {
2844
+ this.fail(arg, `routing target \`${arg.text}\` is not an arm of ${unionName}`, "NS1027");
2845
+ }
2846
+ const shape =
2847
+ "the five image result fields — id: number (the echoed ImageId), state (a named alias of exactly " +
2848
+ IMAGE_STATES.map((s) => `"${s}"`).join(" | ") +
2849
+ "), width: number, height: number, status: number";
2850
+ const fieldsByName = new Map(arm.fields.map((f) => [f.tsName, f]));
2851
+ const isNumber = (k: string): boolean => k === "number" || k === "i64" || k === "f64";
2852
+ const id = fieldsByName.get("id");
2853
+ const state = fieldsByName.get("state");
2854
+ const width = fieldsByName.get("width");
2855
+ const height = fieldsByName.get("height");
2856
+ const status = fieldsByName.get("status");
2857
+ const stateOk =
2858
+ state !== undefined &&
2859
+ state.type.k === "enum" &&
2860
+ state.type.members.length === IMAGE_STATES.length &&
2861
+ IMAGE_STATES.every((s) => state.type.k === "enum" && state.type.members.includes(s));
2862
+ const matches =
2863
+ arm.fields.length === 5 &&
2864
+ stateOk &&
2865
+ id !== undefined &&
2866
+ isNumber(id.type.k) &&
2867
+ width !== undefined &&
2868
+ isNumber(width.type.k) &&
2869
+ height !== undefined &&
2870
+ isNumber(height.type.k) &&
2871
+ status !== undefined &&
2872
+ isNumber(status.type.k);
2873
+ if (!matches) {
2874
+ this.fail(arg, `routing target \`${arg.text}\` does not carry ${shape}`, "NS1027");
2875
+ }
2876
+ return `@intFromEnum(std.meta.Tag(${unionName}).${zigId(arg.text)})`;
2877
+ }
2878
+
2879
+ /// `Cmd.channelOpen(key, route)`: the app's numeric channel key (any
2880
+ /// number expression — keys are model data) and the `{ event }` routing
2881
+ /// whose arm carries the five SDK-fixed channel event fields.
2882
+ private emitChannelOpenCmd(e: ts.CallExpression, ctx: Ctx): string {
2883
+ const keyArg = e.arguments[0];
2884
+ if (!keyArg) this.fail(e, "`Cmd.channelOpen` key (the app's numeric channel key)", "NS1027");
2885
+ // The image-id literal gate: a compile-time-known key the host is
2886
+ // certain to refuse stops the build; dynamic keys stay the host's
2887
+ // to validate through the "rejected" event state. Strictly BELOW
2888
+ // 2^53 — the first f64 that aliases a neighbor on the wire.
2889
+ const keyLiteral = this.numberLiteralValue(keyArg);
2890
+ if (keyLiteral !== null && !(Number.isSafeInteger(keyLiteral) && keyLiteral >= 1)) {
2891
+ this.fail(keyArg, `\`Cmd.channelOpen\` key ${keyLiteral} is not a positive integer channel key below 2^53`, "NS1030");
2892
+ }
2893
+ const key = this.emitExpr(keyArg, ctx, { k: "f64" }).code;
2894
+
2895
+ let route = e.arguments[1];
2896
+ while (route && (ts.isParenthesizedExpression(route) || ts.isAsExpression(route) || ts.isSatisfiesExpression(route))) route = route.expression;
2897
+ if (!route || !ts.isObjectLiteralExpression(route)) {
2898
+ this.fail(e.arguments[1] ?? e, `\`Cmd.channelOpen\` routing is an inline \`{ event }\` object`, "NS1027");
2899
+ }
2900
+ let event: ts.StringLiteral | null = null;
2901
+ for (const p of route.properties) {
2902
+ if (!ts.isPropertyAssignment(p) || !ts.isIdentifier(p.name)) {
2903
+ this.fail(p, `\`Cmd.channelOpen\` routing member \`${p.getText()}\` is not a plain property`, "NS1027");
2904
+ }
2905
+ let v: ts.Expression = p.initializer;
2906
+ while (ts.isParenthesizedExpression(v) || ts.isAsExpression(v) || ts.isSatisfiesExpression(v)) v = v.expression;
2907
+ if (p.name.text !== "event") {
2908
+ this.fail(p, `\`Cmd.channelOpen\` routing member \`${p.name.text}\``, "NS1027");
2909
+ }
2910
+ if (!ts.isStringLiteral(v)) {
2911
+ this.fail(p.initializer, `\`Cmd.channelOpen\` event arm is not a string literal`, "NS1027");
2912
+ }
2913
+ event = v;
2914
+ }
2915
+ if (!event) this.fail(route, `\`Cmd.channelOpen\` routing without an \`event\` arm`, "NS1027");
2916
+ const tag = this.channelEventArmTag(event, ctx);
2917
+ return `rt.cmdChannelOpen(${key}, ${tag})`;
2918
+ }
2919
+
2920
+ /// Resolve the channel event arm: exactly the five SDK-fixed fields,
2921
+ /// matched by NAME — key (a number: the channel key echoed verbatim),
2922
+ /// state (a named literal-union alias carrying exactly the three
2923
+ /// channel states, any order), bytes (the post payload),
2924
+ /// droppedPending/droppedTotal (numbers).
2925
+ private channelEventArmTag(arg: ts.StringLiteral, ctx: Ctx): string {
2926
+ const unionName = ctx.cmdReturn!.msgUnion;
2927
+ const info = this.table.unions.get(unionName);
2928
+ if (!info) this.fail(arg, `unknown union ${unionName}`);
2929
+ const arm = info.arms.find((a) => a.tag === arg.text);
2930
+ if (!arm) {
2931
+ this.fail(arg, `routing target \`${arg.text}\` is not an arm of ${unionName}`, "NS1027");
2932
+ }
2933
+ const shape =
2934
+ "the five channel event fields — key: number (the echoed channel key), state (a named alias of exactly " +
2935
+ CHANNEL_STATES.map((s) => `"${s}"`).join(" | ") +
2936
+ "), bytes: Uint8Array, droppedPending: number, droppedTotal: number";
2937
+ const fieldsByName = new Map(arm.fields.map((f) => [f.tsName, f]));
2938
+ const isNumber = (k: string): boolean => k === "number" || k === "i64" || k === "f64";
2939
+ const key = fieldsByName.get("key");
2940
+ const state = fieldsByName.get("state");
2941
+ const bytes = fieldsByName.get("bytes");
2942
+ const droppedPending = fieldsByName.get("droppedPending");
2943
+ const droppedTotal = fieldsByName.get("droppedTotal");
2944
+ const stateOk =
2945
+ state !== undefined &&
2946
+ state.type.k === "enum" &&
2947
+ state.type.members.length === CHANNEL_STATES.length &&
2948
+ CHANNEL_STATES.every((s) => state.type.k === "enum" && state.type.members.includes(s));
2949
+ const matches =
2950
+ arm.fields.length === 5 &&
2951
+ stateOk &&
2952
+ key !== undefined &&
2953
+ isNumber(key.type.k) &&
2954
+ bytes !== undefined &&
2955
+ bytes.type.k === "bytes" &&
2956
+ droppedPending !== undefined &&
2957
+ isNumber(droppedPending.type.k) &&
2958
+ droppedTotal !== undefined &&
2959
+ isNumber(droppedTotal.type.k);
2960
+ if (!matches) {
2961
+ this.fail(arg, `routing target \`${arg.text}\` does not carry ${shape}`, "NS1027");
2962
+ }
2963
+ return `@intFromEnum(std.meta.Tag(${unionName}).${zigId(arg.text)})`;
2964
+ }
2965
+
2966
+ /// `Cmd.ptySpawn(argv, route)`: an inline argv array of bytes elements
2967
+ /// (the spawn gates verbatim — same engine budgets, different transport)
2968
+ /// and a `{ key?, cols?, rows?, term?, event }` routing object whose arm
2969
+ /// carries the six SDK-fixed pty event fields.
2970
+ private emitPtySpawnCmd(e: ts.CallExpression, ctx: Ctx): string {
2971
+ let argvArg = e.arguments[0];
2972
+ while (argvArg && (ts.isParenthesizedExpression(argvArg) || ts.isAsExpression(argvArg) || ts.isSatisfiesExpression(argvArg))) {
2973
+ argvArg = argvArg.expression;
2974
+ }
2975
+ if (!argvArg || !ts.isArrayLiteralExpression(argvArg) || argvArg.elements.some((el) => ts.isSpreadElement(el))) {
2976
+ this.fail(
2977
+ e.arguments[0] ?? e,
2978
+ `\`Cmd.ptySpawn\` argv is an inline array literal of bytes elements ([asciiBytes("/bin/zsh"), ...])`,
2979
+ "NS1029",
2980
+ );
2981
+ }
2982
+ if (argvArg.elements.length === 0) {
2983
+ this.fail(argvArg, `\`Cmd.ptySpawn\` argv is empty; the engine needs at least the program name`, "NS1030");
2984
+ }
2985
+ if (argvArg.elements.length > MAX_SPAWN_ARGV) {
2986
+ this.fail(
2987
+ argvArg,
2988
+ `\`Cmd.ptySpawn\` argv carries ${argvArg.elements.length} elements; the engine bound is ${MAX_SPAWN_ARGV}`,
2989
+ "NS1030",
2990
+ );
2991
+ }
2992
+ const args = argvArg.elements.map((el) => this.effectBytesArg(e, el, "Cmd.ptySpawn argv element", null, ctx));
2993
+ // The 2 KiB bound is on the WHOLE argv block; stop the build only when
2994
+ // every element's byte length is knowable (dynamic elements stay the
2995
+ // engine's to validate through the event arm's "rejected" exit).
2996
+ const literalLens = argvArg.elements.map((el) => this.literalBytesLength(el));
2997
+ if (literalLens.every((len) => len !== null)) {
2998
+ const total = literalLens.reduce((n: number, len) => n + (len ?? 0), 0);
2999
+ if (total > MAX_SPAWN_ARGV_BYTES) {
3000
+ this.fail(argvArg, `\`Cmd.ptySpawn\` argv is ${total} bytes; the engine bound is ${MAX_SPAWN_ARGV_BYTES}`, "NS1030");
3001
+ }
3002
+ }
3003
+
3004
+ let route = e.arguments[1];
3005
+ while (route && (ts.isParenthesizedExpression(route) || ts.isAsExpression(route) || ts.isSatisfiesExpression(route))) route = route.expression;
3006
+ if (!route || !ts.isObjectLiteralExpression(route)) {
3007
+ this.fail(
3008
+ e.arguments[1] ?? e,
3009
+ `\`Cmd.ptySpawn\` routing is an inline \`{ key?, cols?, rows?, term?, event }\` object`,
3010
+ "NS1027",
3011
+ );
3012
+ }
3013
+ let key = "";
3014
+ let cols = "80";
3015
+ let rows = "24";
3016
+ let term = "";
3017
+ let event: ts.StringLiteral | null = null;
3018
+ for (const p of route.properties) {
3019
+ if (!ts.isPropertyAssignment(p) || !ts.isIdentifier(p.name)) {
3020
+ this.fail(p, `\`Cmd.ptySpawn\` routing member \`${p.getText()}\` is not a plain property`, "NS1027");
3021
+ }
3022
+ const name = p.name.text;
3023
+ let v: ts.Expression = p.initializer;
3024
+ while (ts.isParenthesizedExpression(v) || ts.isAsExpression(v) || ts.isSatisfiesExpression(v)) v = v.expression;
3025
+ if (name === "cols") {
3026
+ cols = this.ptyDimensionArg(e, p.initializer, "Cmd.ptySpawn", "cols", ctx);
3027
+ continue;
3028
+ }
3029
+ if (name === "rows") {
3030
+ rows = this.ptyDimensionArg(e, p.initializer, "Cmd.ptySpawn", "rows", ctx);
3031
+ continue;
3032
+ }
3033
+ if (!ts.isStringLiteral(v)) {
3034
+ this.fail(
3035
+ p.initializer,
3036
+ `\`Cmd.ptySpawn\` routing value \`${p.initializer.getText()}\` is not a string literal`,
3037
+ "NS1027",
3038
+ );
3039
+ }
3040
+ if (name === "key") {
3041
+ if (utf8ByteLength(v.text) > 255) this.fail(v, "Cmd.ptySpawn key over 255 bytes");
3042
+ key = v.text;
3043
+ } else if (name === "term") {
3044
+ // TERM values are declarations like effect keys; an empty one
3045
+ // has nothing to name and the engine bound is small.
3046
+ if (v.text.length === 0) this.fail(v, `\`Cmd.ptySpawn\` term is empty (omit it for the engine default)`, "NS1030");
3047
+ if (utf8ByteLength(v.text) > MAX_PTY_TERM_BYTES) {
3048
+ this.fail(v, `\`Cmd.ptySpawn\` term is over ${MAX_PTY_TERM_BYTES} bytes`, "NS1030");
3049
+ }
3050
+ term = v.text;
3051
+ } else if (name === "event") event = v;
3052
+ else this.fail(p, `\`Cmd.ptySpawn\` routing member \`${name}\``, "NS1027");
3053
+ }
3054
+ if (!event) this.fail(route, `\`Cmd.ptySpawn\` routing without an \`event\` arm`, "NS1027");
3055
+ const tag = this.ptyEventArmTag(event, ctx);
3056
+ return (
3057
+ `rt.cmdPtySpawn("${escapeZigString(key)}", ${tag}, ${cols}, ${rows}, ` +
3058
+ `"${escapeZigString(term)}", &.{ ${args.join(", ")} })`
3059
+ );
3060
+ }
3061
+
3062
+ /// A terminal grid dimension (ptySpawn cols/rows, ptyResize): a
3063
+ /// compile-time-known value outside the transport's 1..65535 integer
3064
+ /// range stops the build; dynamic values stay the host's (an
3065
+ /// unrepresentable spawn grid is one "rejected" exit, an
3066
+ /// unrepresentable resize a documented no-op).
3067
+ private ptyDimensionArg(call: ts.CallExpression, arg: ts.Expression | undefined, factory: string, field: string, ctx: Ctx): string {
3068
+ if (!arg) this.fail(call, `${factory} ${field} (a terminal dimension)`, "NS1029");
3069
+ const literal = this.numberLiteralValue(arg);
3070
+ if (literal !== null && !(Number.isInteger(literal) && literal >= 1 && literal <= MAX_PTY_DIMENSION)) {
3071
+ this.fail(arg, `\`${factory}\` ${field} ${literal} is not a terminal dimension (an integer in 1..${MAX_PTY_DIMENSION})`, "NS1030");
3072
+ }
3073
+ return this.emitExpr(arg, ctx, { k: "f64" }).code;
3074
+ }
3075
+
3076
+ /// Resolve the pty event arm: exactly the seven SDK-fixed fields,
3077
+ /// matched by NAME — key (the app's own session key, so two sessions
3078
+ /// on one arm are distinguishable), state (a named literal-union alias
3079
+ /// carrying exactly the two pty states, any order), bytes (the output
3080
+ /// batch), code (number), reason (a named alias carrying exactly the
3081
+ /// five spawn exit reasons, any order), signal and droppedWrites
3082
+ /// (numbers).
3083
+ private ptyEventArmTag(arg: ts.StringLiteral, ctx: Ctx): string {
3084
+ const unionName = ctx.cmdReturn!.msgUnion;
3085
+ const info = this.table.unions.get(unionName);
3086
+ if (!info) this.fail(arg, `unknown union ${unionName}`);
3087
+ const arm = info.arms.find((a) => a.tag === arg.text);
3088
+ if (!arm) {
3089
+ this.fail(arg, `routing target \`${arg.text}\` is not an arm of ${unionName}`, "NS1027");
3090
+ }
3091
+ const shape =
3092
+ "the seven pty event fields — key: string, state (a named alias of exactly " +
3093
+ PTY_STATES.map((s) => `"${s}"`).join(" | ") +
3094
+ "), bytes: Uint8Array, code: number, reason (a named alias of exactly " +
3095
+ PTY_EXIT_REASONS.map((s) => `"${s}"`).join(" | ") +
3096
+ "), signal: number, droppedWrites: number";
3097
+ const fieldsByName = new Map(arm.fields.map((f) => [f.tsName, f]));
3098
+ const isNumber = (k: string): boolean => k === "number" || k === "i64" || k === "f64";
3099
+ const key = fieldsByName.get("key");
3100
+ const state = fieldsByName.get("state");
3101
+ const bytes = fieldsByName.get("bytes");
3102
+ const code = fieldsByName.get("code");
3103
+ const reason = fieldsByName.get("reason");
3104
+ const signal = fieldsByName.get("signal");
3105
+ const droppedWrites = fieldsByName.get("droppedWrites");
3106
+ const stateOk =
3107
+ state !== undefined &&
3108
+ state.type.k === "enum" &&
3109
+ state.type.members.length === PTY_STATES.length &&
3110
+ PTY_STATES.every((s) => state.type.k === "enum" && state.type.members.includes(s));
3111
+ const reasonOk =
3112
+ reason !== undefined &&
3113
+ reason.type.k === "enum" &&
3114
+ reason.type.members.length === PTY_EXIT_REASONS.length &&
3115
+ PTY_EXIT_REASONS.every((s) => reason.type.k === "enum" && reason.type.members.includes(s));
3116
+ const matches =
3117
+ arm.fields.length === 7 &&
3118
+ key !== undefined &&
3119
+ key.type.k === "string" &&
3120
+ stateOk &&
3121
+ reasonOk &&
3122
+ bytes !== undefined &&
3123
+ bytes.type.k === "bytes" &&
3124
+ code !== undefined &&
3125
+ isNumber(code.type.k) &&
3126
+ signal !== undefined &&
3127
+ isNumber(signal.type.k) &&
3128
+ droppedWrites !== undefined &&
3129
+ isNumber(droppedWrites.type.k);
3130
+ if (!matches) {
3131
+ this.fail(arg, `routing target \`${arg.text}\` does not carry ${shape}`, "NS1027");
3132
+ }
3133
+ return `@intFromEnum(std.meta.Tag(${unionName}).${zigId(arg.text)})`;
3134
+ }
3135
+
2453
3136
  /// Resolve the audio event arm: exactly the six SDK-fixed fields, matched
2454
3137
  /// by NAME — state (a named literal-union alias carrying exactly the six
2455
3138
  /// audio states, any order), positionMs/durationMs (numbers), playing/
@@ -2506,7 +3189,7 @@ export class Emitter {
2506
3189
  if (!keyArg || !ts.isStringLiteral(keyArg)) {
2507
3190
  this.fail(e, `\`Cmd.${method}\` takes its key as a string literal`, "NS1027");
2508
3191
  }
2509
- if (keyArg.text.length > 255) this.fail(keyArg, `Cmd.${method} key over 255 bytes`);
3192
+ if (utf8ByteLength(keyArg.text) > 255) this.fail(keyArg, `Cmd.${method} key over 255 bytes`);
2510
3193
  let value = "0";
2511
3194
  if (method === "audioSeek") {
2512
3195
  const msArg = e.arguments[1];
@@ -2528,6 +3211,192 @@ export class Emitter {
2528
3211
  return `rt.cmdAudioCtl("${escapeZigString(keyArg.text)}", ${AUDIO_VERBS[method]}, ${value})`;
2529
3212
  }
2530
3213
 
3214
+ /// `Cmd.videoLoad(key, source, route)`: a string-literal key, an inline
3215
+ /// `{ surface, path?, url?, autoplay?, loop?, muted? }` source (at least
3216
+ /// one of path/url; the option booleans are literals — they encode into
3217
+ /// the wire record's flags byte at build time), and `{ event }` routing
3218
+ /// onto the seven-field video event arm.
3219
+ private emitVideoLoadCmd(e: ts.CallExpression, ctx: Ctx): string {
3220
+ const keyArg = e.arguments[0];
3221
+ if (!keyArg || !ts.isStringLiteral(keyArg)) {
3222
+ this.fail(e, `\`Cmd.videoLoad\` takes its key as a string literal`, "NS1027");
3223
+ }
3224
+ if (utf8ByteLength(keyArg.text) > 255) this.fail(keyArg, "Cmd.videoLoad key over 255 bytes");
3225
+
3226
+ let source = e.arguments[1];
3227
+ while (source && (ts.isParenthesizedExpression(source) || ts.isAsExpression(source) || ts.isSatisfiesExpression(source))) source = source.expression;
3228
+ if (!source || !ts.isObjectLiteralExpression(source)) {
3229
+ this.fail(
3230
+ e.arguments[1] ?? e,
3231
+ `\`Cmd.videoLoad\` takes an inline \`{ surface, path?, url?, autoplay?, loop?, muted? }\` source object`,
3232
+ "NS1029",
3233
+ );
3234
+ }
3235
+ let surface: string | null = null;
3236
+ let video_path = '""';
3237
+ let url = '""';
3238
+ // Wire flags: bit0 = autoplay (default on), bit1 = loop, bit2 = muted.
3239
+ let flags = 1;
3240
+ let has_source = false;
3241
+ for (const p of source.properties) {
3242
+ if (!ts.isPropertyAssignment(p) || !ts.isIdentifier(p.name)) {
3243
+ this.fail(p, `\`Cmd.videoLoad\` source member \`${p.getText()}\` is not a plain property`, "NS1029");
3244
+ }
3245
+ const name = p.name.text;
3246
+ if (name === "surface") {
3247
+ // A compile-time-known surface id the engine is certain to
3248
+ // refuse stops the build (the imageLoad id gate: 0 is the
3249
+ // no-surface sentinel, and past 2^53 the f64 wire cannot carry
3250
+ // the id exactly). Dynamic ids stay the host's to validate
3251
+ // through the "rejected" event state.
3252
+ const literal = this.numberLiteralValue(p.initializer);
3253
+ if (literal !== null && !(Number.isSafeInteger(literal) && literal >= 1)) {
3254
+ this.fail(p.initializer, `\`Cmd.videoLoad\` surface ${literal} is not a positive integer media-surface id below 2^53`, "NS1030");
3255
+ }
3256
+ surface = this.emitExpr(p.initializer, ctx, { k: "f64" }).code;
3257
+ } else if (name === "path") {
3258
+ video_path = this.effectBytesArg(e, p.initializer, "Cmd.videoLoad path", MAX_VIDEO_PATH_BYTES, ctx);
3259
+ has_source = true;
3260
+ } else if (name === "url") {
3261
+ url = this.effectBytesArg(e, p.initializer, "Cmd.videoLoad url", MAX_VIDEO_PATH_BYTES, ctx);
3262
+ has_source = true;
3263
+ } else if (name === "autoplay" || name === "loop" || name === "muted") {
3264
+ // The option booleans encode into the wire record's flags byte
3265
+ // at build time, so they are literals — a dynamic switch
3266
+ // belongs on the control verbs (videoSetMuted/videoSetLoop
3267
+ // drive the open stream).
3268
+ let v: ts.Expression = p.initializer;
3269
+ while (ts.isParenthesizedExpression(v) || ts.isAsExpression(v) || ts.isSatisfiesExpression(v)) v = v.expression;
3270
+ if (v.kind !== ts.SyntaxKind.TrueKeyword && v.kind !== ts.SyntaxKind.FalseKeyword) {
3271
+ this.fail(p.initializer, `\`Cmd.videoLoad\` ${name} must be the literal \`true\` or \`false\``, "NS1030");
3272
+ }
3273
+ const bit = name === "autoplay" ? 1 : name === "loop" ? 2 : 4;
3274
+ flags = v.kind === ts.SyntaxKind.TrueKeyword ? flags | bit : flags & ~bit;
3275
+ } else {
3276
+ this.fail(p, `\`Cmd.videoLoad\` source member \`${name}\``, "NS1029");
3277
+ }
3278
+ }
3279
+ if (surface === null) {
3280
+ this.fail(source, `\`Cmd.videoLoad\` source without a \`surface\` — the media-surface id the decoded frames feed`, "NS1029");
3281
+ }
3282
+ if (!has_source) {
3283
+ this.fail(source, `\`Cmd.videoLoad\` source without a \`path\` or a \`url\` — nothing could play`, "NS1029");
3284
+ }
3285
+
3286
+ let route = e.arguments[2];
3287
+ while (route && (ts.isParenthesizedExpression(route) || ts.isAsExpression(route) || ts.isSatisfiesExpression(route))) route = route.expression;
3288
+ if (!route || !ts.isObjectLiteralExpression(route)) {
3289
+ this.fail(e.arguments[2] ?? e, `\`Cmd.videoLoad\` routing is an inline \`{ event }\` object`, "NS1027");
3290
+ }
3291
+ let event: ts.StringLiteral | null = null;
3292
+ for (const p of route.properties) {
3293
+ if (!ts.isPropertyAssignment(p) || !ts.isIdentifier(p.name)) {
3294
+ this.fail(p, `\`Cmd.videoLoad\` routing member \`${p.getText()}\` is not a plain property`, "NS1027");
3295
+ }
3296
+ let v: ts.Expression = p.initializer;
3297
+ while (ts.isParenthesizedExpression(v) || ts.isAsExpression(v) || ts.isSatisfiesExpression(v)) v = v.expression;
3298
+ if (p.name.text !== "event") {
3299
+ this.fail(p, `\`Cmd.videoLoad\` routing member \`${p.name.text}\``, "NS1027");
3300
+ }
3301
+ if (!ts.isStringLiteral(v)) {
3302
+ this.fail(p.initializer, `\`Cmd.videoLoad\` event arm is not a string literal`, "NS1027");
3303
+ }
3304
+ event = v;
3305
+ }
3306
+ if (!event) this.fail(route, `\`Cmd.videoLoad\` routing without an \`event\` arm`, "NS1027");
3307
+ const tag = this.videoEventArmTag(event, ctx);
3308
+ return `rt.cmdVideoLoad("${escapeZigString(keyArg.text)}", ${tag}, ${surface}, ${video_path}, ${url}, ${flags})`;
3309
+ }
3310
+
3311
+ /// Resolve the video event arm: exactly the seven SDK-fixed fields,
3312
+ /// matched by NAME — state (a named literal-union alias carrying exactly
3313
+ /// the five video states, any order), positionMs/durationMs (numbers),
3314
+ /// playing/buffering (booleans), width/height (numbers).
3315
+ private videoEventArmTag(arg: ts.StringLiteral, ctx: Ctx): string {
3316
+ const unionName = ctx.cmdReturn!.msgUnion;
3317
+ const info = this.table.unions.get(unionName);
3318
+ if (!info) this.fail(arg, `unknown union ${unionName}`);
3319
+ const arm = info.arms.find((a) => a.tag === arg.text);
3320
+ if (!arm) {
3321
+ this.fail(arg, `routing target \`${arg.text}\` is not an arm of ${unionName}`, "NS1027");
3322
+ }
3323
+ const shape =
3324
+ "the seven video event fields — state (a named alias of exactly " +
3325
+ VIDEO_STATES.map((s) => `"${s}"`).join(" | ") +
3326
+ "), positionMs: number, durationMs: number, playing: boolean, buffering: boolean, width: number, height: number";
3327
+ const fieldsByName = new Map(arm.fields.map((f) => [f.tsName, f]));
3328
+ const isNumber = (k: string): boolean => k === "number" || k === "i64" || k === "f64";
3329
+ const state = fieldsByName.get("state");
3330
+ const position = fieldsByName.get("positionMs");
3331
+ const duration = fieldsByName.get("durationMs");
3332
+ const playing = fieldsByName.get("playing");
3333
+ const buffering = fieldsByName.get("buffering");
3334
+ const width = fieldsByName.get("width");
3335
+ const height = fieldsByName.get("height");
3336
+ const stateOk =
3337
+ state !== undefined &&
3338
+ state.type.k === "enum" &&
3339
+ state.type.members.length === VIDEO_STATES.length &&
3340
+ VIDEO_STATES.every((s) => state.type.k === "enum" && state.type.members.includes(s));
3341
+ const matches =
3342
+ arm.fields.length === 7 &&
3343
+ stateOk &&
3344
+ position !== undefined &&
3345
+ isNumber(position.type.k) &&
3346
+ duration !== undefined &&
3347
+ isNumber(duration.type.k) &&
3348
+ playing !== undefined &&
3349
+ playing.type.k === "bool" &&
3350
+ buffering !== undefined &&
3351
+ buffering.type.k === "bool" &&
3352
+ width !== undefined &&
3353
+ isNumber(width.type.k) &&
3354
+ height !== undefined &&
3355
+ isNumber(height.type.k);
3356
+ if (!matches) {
3357
+ this.fail(arg, `routing target \`${arg.text}\` does not carry ${shape}`, "NS1027");
3358
+ }
3359
+ return `@intFromEnum(std.meta.Tag(${unionName}).${zigId(arg.text)})`;
3360
+ }
3361
+
3362
+ /// The `Cmd.videoPlay/Pause/Stop/Seek/SetVolume/SetMuted/SetLoop`
3363
+ /// control verbs: a string-literal key plus the seek position / volume /
3364
+ /// switch value where the verb takes one.
3365
+ private emitVideoCtlCmd(e: ts.CallExpression, method: string, ctx: Ctx): string {
3366
+ const keyArg = e.arguments[0];
3367
+ if (!keyArg || !ts.isStringLiteral(keyArg)) {
3368
+ this.fail(e, `\`Cmd.${method}\` takes its key as a string literal`, "NS1027");
3369
+ }
3370
+ if (utf8ByteLength(keyArg.text) > 255) this.fail(keyArg, `Cmd.${method} key over 255 bytes`);
3371
+ let value = "0";
3372
+ if (method === "videoSeek") {
3373
+ const msArg = e.arguments[1];
3374
+ if (!msArg) this.fail(e, "Cmd.videoSeek position (milliseconds)");
3375
+ const literal = this.numberLiteralValue(msArg);
3376
+ if (literal !== null && !(literal >= 0 && Number.isFinite(literal))) {
3377
+ this.fail(msArg, `\`Cmd.videoSeek\` position ${literal} is not a millisecond offset`, "NS1030");
3378
+ }
3379
+ value = this.emitExpr(msArg, ctx, { k: "f64" }).code;
3380
+ } else if (method === "videoSetVolume") {
3381
+ const volArg = e.arguments[1];
3382
+ if (!volArg) this.fail(e, "Cmd.videoSetVolume volume (0..1)");
3383
+ const literal = this.numberLiteralValue(volArg);
3384
+ if (literal !== null && !(literal >= 0 && literal <= 1)) {
3385
+ this.fail(volArg, `\`Cmd.videoSetVolume\` volume ${literal} is outside 0..1`, "NS1030");
3386
+ }
3387
+ value = this.emitExpr(volArg, ctx, { k: "f64" }).code;
3388
+ } else if (method === "videoSetMuted" || method === "videoSetLoop") {
3389
+ // The switch verbs take any boolean expression — applying runtime
3390
+ // state to the open stream is what they exist for (the load-time
3391
+ // literals cover the start-muted/start-looping cases). It rides
3392
+ // the value field as 0/1, the audioSeek dynamic-value discipline.
3393
+ const boolArg = e.arguments[1];
3394
+ if (!boolArg) this.fail(e, `Cmd.${method} switch (a boolean)`);
3395
+ value = `@floatFromInt(@intFromBool(${this.emitExpr(boolArg, ctx, { k: "bool" }).code}))`;
3396
+ }
3397
+ return `rt.cmdVideoCtl("${escapeZigString(keyArg.text)}", ${VIDEO_VERBS[method]}, ${value})`;
3398
+ }
3399
+
2531
3400
  /// Resolve a `Cmd.now`/`Cmd.delay`/`Sub.timer` target arm to its tag,
2532
3401
  /// requiring exactly one number payload field.
2533
3402
  private numberArmTag(arg: ts.StringLiteral, unionName: string, factory: string): string {
@@ -2575,7 +3444,10 @@ export class Emitter {
2575
3444
  }
2576
3445
 
2577
3446
  /// The byte length of a compile-time `asciiBytes("...")` literal; null
2578
- /// for everything dynamic.
3447
+ /// for everything dynamic. Counted as UTF-8 bytes: for the ASCII text
3448
+ /// the intrinsic is contracted to carry the two counts agree, and for
3449
+ /// text that violates the contract the emitted Zig literal holds the
3450
+ /// UTF-8 bytes, so this is the length the engine bound actually sees.
2579
3451
  private literalBytesLength(arg: ts.Expression): number | null {
2580
3452
  let e = arg;
2581
3453
  while (ts.isParenthesizedExpression(e) || ts.isAsExpression(e) || ts.isSatisfiesExpression(e)) e = e.expression;
@@ -2583,7 +3455,7 @@ export class Emitter {
2583
3455
  const decl = this.tast.declarationOf(e.expression);
2584
3456
  if (!decl || !this.isSdkIntrinsic(decl, "asciiBytes")) return null;
2585
3457
  const inner = e.arguments[0];
2586
- return inner && ts.isStringLiteral(inner) ? inner.text.length : null;
3458
+ return inner && ts.isStringLiteral(inner) ? utf8ByteLength(inner.text) : null;
2587
3459
  }
2588
3460
 
2589
3461
  /// The numeric value of a compile-time number literal (unary minus
@@ -2854,7 +3726,7 @@ export class Emitter {
2854
3726
  if (!keyArg || !ts.isStringLiteral(keyArg)) {
2855
3727
  this.fail(e, `\`Sub.timer\` takes its key as a string literal`, "NS1027");
2856
3728
  }
2857
- if (keyArg.text.length > 255) this.fail(keyArg, "Sub.timer key over 255 bytes");
3729
+ if (utf8ByteLength(keyArg.text) > 255) this.fail(keyArg, "Sub.timer key over 255 bytes");
2858
3730
  const everyArg = e.arguments[1];
2859
3731
  if (!everyArg) this.fail(e, "Sub.timer interval (milliseconds)");
2860
3732
  const every = this.emitExpr(everyArg, ctx, { k: "f64" }).code;
@@ -2903,6 +3775,115 @@ export class Emitter {
2903
3775
  return this.table.zigTypeRef(t);
2904
3776
  }
2905
3777
 
3778
+ /// Per-declaration ids for narrowing keys (see narrowKey). A WeakMap
3779
+ /// identity id rather than the declaration's source position: positions
3780
+ /// can collide across files, and imported consts narrow too.
3781
+ private readonly narrowKeyIds = new WeakMap<ts.Declaration, number>();
3782
+ private narrowKeyNextId = 1;
3783
+
3784
+ /// Explicit node-scoped keys: a lowering that re-emits one specific
3785
+ /// expression NODE under a capture (the optional-call receiver) can
3786
+ /// register a key for it even when the expression has no canonical
3787
+ /// narrowing key. The key is unique to the node, so it can never match
3788
+ /// a different occurrence — it carries a single node's rewrite, not a
3789
+ /// narrowing fact.
3790
+ private readonly nodeNarrowKeys = new WeakMap<ts.Node, string>();
3791
+
3792
+ /// The key an expression narrows/substitutes under: normalized source
3793
+ /// text with the base identifier DECLARATION-qualified (`q#3`, member
3794
+ /// chains `q#3.v`). Emission FLATTENS plain lexical blocks and callback
3795
+ /// bodies share the enclosing maps, so raw text would let two
3796
+ /// same-named declarations collide — a block-local `const q` shadow
3797
+ /// leaves its entries live for the OUTER q after the block, and an
3798
+ /// outer capture rewrites a callback parameter's reads. Symbol identity
3799
+ /// makes the collision impossible; the maps' values and mechanics are
3800
+ /// unchanged. Wrapper spellings collide by design: parentheses,
3801
+ /// non-null assertions, `as`, and `satisfies` all erase at emission
3802
+ /// (`(q)`, `q!`, and `q as Quote` are the tested `q`), so every
3803
+ /// consumer comparing or looking up keys sees through them — an arm
3804
+ /// spelled `q!` matches its guard's `q`, and a narrow installed for `q`
3805
+ /// rewrites the `q!` read. A base the checker cannot resolve keys by
3806
+ /// plain text — same behavior as before, and such bases are never
3807
+ /// locals.
3808
+ ///
3809
+ /// Element accesses qualify recursively, like property chains — the
3810
+ /// grammar is `base[index]` where the base is this same key and the
3811
+ /// index is a canonical argument form: a literal index canonicalizes by
3812
+ /// VALUE (`xs#3[0]`, so `xs[0]`, `xs[0x0]`, and `xs["0"]` are one key,
3813
+ /// exactly the one element JS reads), and an identifier index qualifies
3814
+ /// by the index's own declaration (`xs#3[i#7]` — a shadowed `i` is a
3815
+ /// different element). Anything non-canonical — a computed index, a
3816
+ /// call — has NO narrowing key: two spellings of `xs[f()]` need not
3817
+ /// read the same element, so nothing may narrow, substitute, or match
3818
+ /// through one. Returning null here is the decline answer every
3819
+ /// consumer honors: no substitution installs, capture gates see no
3820
+ /// read, and the expression's reads stay live optionals. Raw source
3821
+ /// text is never a key — emission flattens lexical blocks, so text
3822
+ /// would let a shadowed declaration's narrow leak onto the outer name.
3823
+ private narrowKey(expr: ts.Node): string | null {
3824
+ const override = this.nodeNarrowKeys.get(expr);
3825
+ if (override !== undefined) return override;
3826
+ let e: ts.Node = expr;
3827
+ while (
3828
+ ts.isParenthesizedExpression(e) ||
3829
+ ts.isNonNullExpression(e) ||
3830
+ ts.isAsExpression(e) ||
3831
+ ts.isSatisfiesExpression(e)
3832
+ ) {
3833
+ e = e.expression;
3834
+ }
3835
+ if (ts.isPropertyAccessExpression(e)) {
3836
+ const base = this.narrowKey(e.expression);
3837
+ return base === null ? null : `${base}${e.questionDotToken ? "?." : "."}${e.name.text}`;
3838
+ }
3839
+ if (ts.isElementAccessExpression(e)) {
3840
+ const base = this.narrowKey(e.expression);
3841
+ if (base === null) return null;
3842
+ const index = this.canonicalIndexKey(e.argumentExpression);
3843
+ if (index === null) return null;
3844
+ return `${base}${e.questionDotToken ? "?." : ""}[${index}]`;
3845
+ }
3846
+ if (ts.isIdentifier(e)) {
3847
+ const decl = this.tast.declarationOf(e);
3848
+ if (decl) {
3849
+ let id = this.narrowKeyIds.get(decl);
3850
+ if (id === undefined) {
3851
+ id = this.narrowKeyNextId++;
3852
+ this.narrowKeyIds.set(decl, id);
3853
+ }
3854
+ return `${e.text}#${id}`;
3855
+ }
3856
+ return e.text;
3857
+ }
3858
+ // `this` is one object per member body (arrows keep it), never
3859
+ // shadowable — the keyword is its own key.
3860
+ if (e.kind === ts.SyntaxKind.ThisKeyword) return "this";
3861
+ return null;
3862
+ }
3863
+
3864
+ /// The canonical form of an element-access index, or null when the
3865
+ /// index is not a stable reference to one element (see narrowKey).
3866
+ /// Literals canonicalize by the VALUE JS coerces to a property key —
3867
+ /// a numeric string index is the numeric index (`xs["0"]` is `xs[0]`).
3868
+ private canonicalIndexKey(arg: ts.Expression): string | null {
3869
+ let a: ts.Expression = arg;
3870
+ while (
3871
+ ts.isParenthesizedExpression(a) ||
3872
+ ts.isNonNullExpression(a) ||
3873
+ ts.isAsExpression(a) ||
3874
+ ts.isSatisfiesExpression(a)
3875
+ ) {
3876
+ a = a.expression;
3877
+ }
3878
+ if (ts.isNumericLiteral(a)) return String(Number(a.text));
3879
+ if (ts.isStringLiteral(a) || ts.isNoSubstitutionTemplateLiteral(a)) {
3880
+ const n = Number(a.text);
3881
+ return String(n) === a.text ? String(n) : JSON.stringify(a.text);
3882
+ }
3883
+ if (ts.isIdentifier(a)) return this.narrowKey(a);
3884
+ return null;
3885
+ }
3886
+
2906
3887
  private identifierUsed(body: ts.Node, decl: ts.Node): boolean {
2907
3888
  let used = false;
2908
3889
  const visit = (n: ts.Node): void => {
@@ -2964,7 +3945,326 @@ export class Emitter {
2964
3945
  return this.uniqueName(ctx, hint);
2965
3946
  }
2966
3947
 
2967
- private emitBlockStatements(stmts: readonly ts.Statement[], ctx: Ctx): void {
3948
+ /// Open an invalidation frame: every scope that snapshots/restores the
3949
+ /// narrowing maps brackets its emission with this pair, so assignment
3950
+ /// kills recorded during the scope survive the restore (see Ctx.narrowKilled).
3951
+ private pushNarrowKillFrame(ctx: Ctx): void {
3952
+ ctx.narrowKilled.push(new Set());
3953
+ }
3954
+
3955
+ /// Close the innermost invalidation frame: re-apply its recorded kills to
3956
+ /// the just-restored narrowing maps and merge them one frame outward (an
3957
+ /// inner branch's kill must reach every enclosing exit it can fall
3958
+ /// through to). A kill on ANY fall-through path inside the scope deletes
3959
+ /// the narrow at the merge point, so a path that kept the value non-null
3960
+ /// pays a re-check — never wrong code. Only memberSubst is touched,
3961
+ /// mirroring the assignment-invalidation path (a stillOptionalSubst entry
3962
+ /// is inert once its memberSubst entry is gone, and narrowedUnion is not
3963
+ /// what `.?` substitutions live in).
3964
+ ///
3965
+ /// `drop` discards the frame's kills instead: the caller has proven the
3966
+ /// scope always leaves the emitted function, so no path carrying those
3967
+ /// kills reaches the merge point — merging them would delete narrowings
3968
+ /// tsc keeps on the surviving flow, and a read there relies on the
3969
+ /// substitution's unwrap spelling (losing it emits a field access on an
3970
+ /// optional, not a re-check).
3971
+ ///
3972
+ /// A destination array routes the kills along the scope's non-local
3973
+ /// edges instead: the scope's only in-function routes are caught throws
3974
+ /// and/or escaping break/continue/lowered-return edges, so no path
3975
+ /// carrying the kills reaches THIS merge point either — but each edge
3976
+ /// resumes somewhere in the function, and the kills must be live there.
3977
+ /// Kills travel the same edges control does: they wait in the
3978
+ /// destination sets (the enclosing try's pendingCatchKills, the target
3979
+ /// constructs' edgeKills stages) and the owning emitters apply them
3980
+ /// where the edges land — never mid-flight, where tsc keeps the
3981
+ /// surviving paths' narrows.
3982
+ private popNarrowKillFrame(ctx: Ctx, routing: KillRouting = "merge"): Set<string> {
3983
+ const killed = ctx.narrowKilled.pop() ?? new Set<string>();
3984
+ if (routing === "drop") return killed;
3985
+ if (routing !== "merge") {
3986
+ for (const dest of routing) for (const key of killed) dest.add(key);
3987
+ return killed;
3988
+ }
3989
+ for (const key of killed) ctx.memberSubst.delete(key);
3990
+ const parent = ctx.narrowKilled[ctx.narrowKilled.length - 1];
3991
+ if (parent) for (const key of killed) parent.add(key);
3992
+ return killed;
3993
+ }
3994
+
3995
+ /// Bracket `emit` in one narrowing flow scope: on exit, restore the three
3996
+ /// narrowing maps to their entry snapshot (containment), then re-apply and
3997
+ /// merge — or drop, or route to the enclosing try's pending set — the
3998
+ /// kills recorded inside (see popNarrowKillFrame).
3999
+ ///
4000
+ /// `joinInto` defers merge-class kills for a JOIN instead of applying
4001
+ /// them here: a multi-alternative construct (if/else arms, an else-if
4002
+ /// chain, switch clauses) must emit every alternative from the shared
4003
+ /// ENTRY state — tsc types the arms as alternatives, not a sequence, so
4004
+ /// one arm's kill applied mid-construct would strip a sibling of a
4005
+ /// narrowing tsc keeps there. The caller collects each arm's kills and
4006
+ /// applies the union once via applyJoinedNarrowKills, after the last
4007
+ /// alternative. Only merge-class kills defer: an always-leaving arm
4008
+ /// still drops its kills, and an arm whose only in-function routes are
4009
+ /// non-local edges still routes them to those edges' destination sets —
4010
+ /// those edges never reach a sibling.
4011
+ private withNarrowScope<T>(
4012
+ ctx: Ctx,
4013
+ mode: KillRouting,
4014
+ emit: () => T,
4015
+ joinInto?: Set<string>,
4016
+ ): T {
4017
+ const savedSubst = new Map(ctx.memberSubst);
4018
+ const savedStillOptional = new Map(ctx.stillOptionalSubst);
4019
+ const savedNarrowed = new Map(ctx.narrowedUnion);
4020
+ this.pushNarrowKillFrame(ctx);
4021
+ try {
4022
+ return emit();
4023
+ } finally {
4024
+ ctx.memberSubst.clear();
4025
+ for (const [k, v] of savedSubst) ctx.memberSubst.set(k, v);
4026
+ ctx.stillOptionalSubst.clear();
4027
+ for (const [k, v] of savedStillOptional) ctx.stillOptionalSubst.set(k, v);
4028
+ ctx.narrowedUnion.clear();
4029
+ for (const [k, v] of savedNarrowed) ctx.narrowedUnion.set(k, v);
4030
+ if (mode === "merge" && joinInto) {
4031
+ for (const key of this.popNarrowKillFrame(ctx, "drop")) joinInto.add(key);
4032
+ } else {
4033
+ this.popNarrowKillFrame(ctx, mode);
4034
+ }
4035
+ }
4036
+ }
4037
+
4038
+ /// The JOIN of a multi-alternative construct: apply the union of the
4039
+ /// alternatives' merge-class kills to the surviving flow, once, after
4040
+ /// every alternative has emitted from the shared entry state (see
4041
+ /// withNarrowScope's `joinInto`). Same application as a plain merge —
4042
+ /// delete the narrow, propagate the kill one frame outward so enclosing
4043
+ /// exits keep it dead past their restores.
4044
+ private applyJoinedNarrowKills(ctx: Ctx, join: ReadonlySet<string>): void {
4045
+ for (const key of join) {
4046
+ ctx.memberSubst.delete(key);
4047
+ ctx.narrowKilled[ctx.narrowKilled.length - 1]?.add(key);
4048
+ }
4049
+ }
4050
+
4051
+ /// Bracket a construct's emission with an edge-kill stage (Ctx.edgeKills):
4052
+ /// scopes inside that exit only along edges bound to this construct stage
4053
+ /// their kills here, and the returned set is what the caller applies at
4054
+ /// the point those edges land — applyJoinedNarrowKills after the closing
4055
+ /// brace for loops, labeled blocks, and callback value blocks; folded
4056
+ /// through the clause join for switches (the two mechanisms share one
4057
+ /// application point, so a kill is neither applied twice mid-construct
4058
+ /// nor dropped between them). The application records into the
4059
+ /// then-innermost kill frame, so a staged kill keeps propagating outward
4060
+ /// — through enclosing joins and post-narrow subtractions — exactly like
4061
+ /// a merge-class kill applied at the same spot.
4062
+ private stagedEdgeKills(
4063
+ ctx: Ctx,
4064
+ kind: EdgeKillStage["kind"],
4065
+ label: string | null,
4066
+ emit: () => void,
4067
+ ): Set<string> {
4068
+ const stage: EdgeKillStage = { kind, label, kills: new Set() };
4069
+ ctx.edgeKills.push(stage);
4070
+ try {
4071
+ emit();
4072
+ } finally {
4073
+ ctx.edgeKills.pop();
4074
+ }
4075
+ return stage.kills;
4076
+ }
4077
+
4078
+ private emitBlockStatements(
4079
+ stmts: readonly ts.Statement[],
4080
+ ctx: Ctx,
4081
+ joinInto?: Set<string>,
4082
+ entryKills?: ReadonlySet<string>,
4083
+ trailing?: () => void,
4084
+ ): void {
4085
+ // Narrowing is flow-scoped the way tsc scopes it: an early-exit guard
4086
+ // narrows the statements after it in ITS list, and whatever those
4087
+ // statements nest — never code beyond the list. The narrowing maps ride
4088
+ // the shared ctx, so the scope's entry/exit snapshot is what bounds
4089
+ // them: a `break`/`continue`/`return` guard inside a loop body or a
4090
+ // branch cannot leak its captures into code after the construct (where
4091
+ // the capture is out of scope in Zig and the narrowing wrong in TS).
4092
+ //
4093
+ // Invalidation survives the restore — an assignment inside the block
4094
+ // that killed a narrowing (assigned a possibly-null value) must stay
4095
+ // dead past the merge — UNLESS every route out of the list leaves the
4096
+ // emitted function (allRoutesLeaveFunction): then no path carrying the
4097
+ // kills reaches the merge, tsc keeps the narrow on the surviving flow,
4098
+ // and reads there depend on it.
4099
+ const env = {
4100
+ returnLeaves: ctx.retLabel === null,
4101
+ throwResumes: ctx.catchResumes === true,
4102
+ };
4103
+ const leavesFn = this.allRoutesLeaveFunction(stmts, env);
4104
+ // Edge-kills channel: when the list's only in-function routes are
4105
+ // non-local edges — throws the enclosing catch hands back, escaping
4106
+ // break/continue edges, lowered callback returns — no path carrying
4107
+ // the kills falls through into the statements after this list, so
4108
+ // merging them here would poison flow tsc keeps narrowed (the killing
4109
+ // paths cannot reach it). Kills travel the same edges control does:
4110
+ // each class stages at its destination — the try's pending set for
4111
+ // caught throws, the target construct's stage for break/continue, the
4112
+ // callback stage for lowered returns — and the owning emitter applies
4113
+ // it where the edge lands. Re-asking the route question with every
4114
+ // edge class treated as leaving isolates exactly this case: any true
4115
+ // fall-through still forces the plain merge (which is a conservative
4116
+ // superset — its kills persist into all downstream states, the edge
4117
+ // destinations included).
4118
+ // `entryKills` are kills that arrived WITH control (a catch entered on
4119
+ // throw edges that carried them): they widen the list's entry state —
4120
+ // its reads see them — and then ride this frame's routing out, exactly
4121
+ // like a kill the first statement made. Routing is what makes them
4122
+ // land where flow says: a fall-through carries them to the code after
4123
+ // the construct, an escaping break/continue stages them at that edge's
4124
+ // destination, and a list whose every route leaves the function drops
4125
+ // them (no surviving path carries them anywhere).
4126
+ // `trailing` is emission that tsc types under the list's END state — a
4127
+ // do-while's trailing exit test evaluates after the body, so a terminal
4128
+ // guard in the body narrows it. It runs inside this same scope: a scope
4129
+ // closed between the list and the test would restore the maps before
4130
+ // the read they guard (the callback trailing-return fix, applied to the
4131
+ // loop lowering).
4132
+ this.withNarrowScope(
4133
+ ctx,
4134
+ leavesFn ? "drop" : this.edgeKillRouting(stmts, env, ctx),
4135
+ () => {
4136
+ if (entryKills) {
4137
+ for (const key of entryKills) {
4138
+ ctx.memberSubst.delete(key);
4139
+ ctx.narrowKilled[ctx.narrowKilled.length - 1]?.add(key);
4140
+ }
4141
+ }
4142
+ this.emitStatementList(stmts, ctx);
4143
+ trailing?.();
4144
+ },
4145
+ joinInto,
4146
+ );
4147
+ }
4148
+
4149
+ /// The routing for a list that does NOT always leave the function: the
4150
+ /// non-local-edges-only route form when it applies, else "merge". A
4151
+ /// destination that fails to resolve (a caught throw without a pending
4152
+ /// set, an edge whose target construct has no stage) falls back to the
4153
+ /// plain merge — over-merging costs a re-check, never wrong code.
4154
+ private edgeKillRouting(
4155
+ stmts: readonly ts.Statement[],
4156
+ env: { returnLeaves: boolean; throwResumes: boolean },
4157
+ ctx: Ctx,
4158
+ ): KillRouting {
4159
+ if (!this.allRoutesLeaveFunction(stmts, { ...env, edgesLeave: true, throwResumes: false })) {
4160
+ return "merge";
4161
+ }
4162
+ const targets: Set<string>[] = [];
4163
+ if (env.throwResumes && !this.allRoutesLeaveFunction(stmts, { ...env, edgesLeave: true })) {
4164
+ // With edges leaving but caught throws resuming, any remaining
4165
+ // resuming route is a caught throw: this list exits along the
4166
+ // throw edge into the enclosing catch.
4167
+ if (ctx.pendingCatchKills == null) return "merge";
4168
+ targets.push(ctx.pendingCatchKills);
4169
+ }
4170
+ const edges = this.escapingEdgesOf(stmts, env.returnLeaves);
4171
+ const innermost = (pred: (s: EdgeKillStage) => boolean): EdgeKillStage | null => {
4172
+ for (let i = ctx.edgeKills.length - 1; i >= 0; i--) {
4173
+ if (pred(ctx.edgeKills[i])) return ctx.edgeKills[i];
4174
+ }
4175
+ return null;
4176
+ };
4177
+ for (const label of edges.breaks) {
4178
+ const stage = innermost((s) =>
4179
+ label === null ? s.kind === "loop" || s.kind === "switch" : s.label === label,
4180
+ );
4181
+ if (stage === null) return "merge";
4182
+ targets.push(stage.kills);
4183
+ }
4184
+ for (const label of edges.continues) {
4185
+ const stage = innermost((s) => s.kind === "loop" && (label === null || s.label === label));
4186
+ if (stage === null) return "merge";
4187
+ targets.push(stage.kills);
4188
+ }
4189
+ if (edges.callbackReturn) {
4190
+ const stage = innermost((s) => s.kind === "callback");
4191
+ if (stage === null) return "merge";
4192
+ targets.push(stage.kills);
4193
+ }
4194
+ // No resolvable destination at all would leave resuming routes with
4195
+ // nowhere to carry the kills — that only happens when the two route
4196
+ // analyses disagree, so keep the conservative merge.
4197
+ return targets.length > 0 ? targets : "merge";
4198
+ }
4199
+
4200
+ /// The escaping non-local edges out of a statement list: the labels (null
4201
+ /// = unlabeled) of break/continue statements whose target sits at or
4202
+ /// outside the list, and whether any lowered `return` exits it (lifted
4203
+ /// callbacks: returnLeaves is false). Binding mirrors
4204
+ /// allRoutesLeaveFunction's target tracking — a loop binds unlabeled
4205
+ /// break and continue for its subtree, a switch binds unlabeled break, a
4206
+ /// labeled statement binds its label — and callback bodies are theirs
4207
+ /// alone (tsc rejects a break/continue crossing a function boundary;
4208
+ /// their returns are analyzed at their own emission).
4209
+ private escapingEdgesOf(
4210
+ stmts: readonly ts.Statement[],
4211
+ returnLeaves: boolean,
4212
+ ): { breaks: Set<string | null>; continues: Set<string | null>; callbackReturn: boolean } {
4213
+ const breaks = new Set<string | null>();
4214
+ const continues = new Set<string | null>();
4215
+ let callbackReturn = false;
4216
+ interface Bound {
4217
+ readonly labels: ReadonlySet<string>;
4218
+ readonly breakBound: boolean;
4219
+ readonly continueBound: boolean;
4220
+ }
4221
+ const visit = (n: ts.Node, st: Bound): void => {
4222
+ if (ts.isBreakStatement(n)) {
4223
+ if (n.label ? !st.labels.has(n.label.text) : !st.breakBound) breaks.add(n.label?.text ?? null);
4224
+ return;
4225
+ }
4226
+ if (ts.isContinueStatement(n)) {
4227
+ if (n.label ? !st.labels.has(n.label.text) : !st.continueBound) continues.add(n.label?.text ?? null);
4228
+ return;
4229
+ }
4230
+ if (ts.isReturnStatement(n)) {
4231
+ if (!returnLeaves) callbackReturn = true;
4232
+ return;
4233
+ }
4234
+ if (ts.isFunctionDeclaration(n) || ts.isArrowFunction(n) || ts.isFunctionExpression(n)) return;
4235
+ if (ts.isLabeledStatement(n)) {
4236
+ visit(n.statement, { ...st, labels: new Set(st.labels).add(n.label.text) });
4237
+ return;
4238
+ }
4239
+ if (
4240
+ ts.isWhileStatement(n) ||
4241
+ ts.isDoStatement(n) ||
4242
+ ts.isForStatement(n) ||
4243
+ ts.isForOfStatement(n) ||
4244
+ ts.isForInStatement(n)
4245
+ ) {
4246
+ ts.forEachChild(n, (c) => {
4247
+ if (!this.tscExcludedArm(n, c)) visit(c, { ...st, breakBound: true, continueBound: true });
4248
+ });
4249
+ return;
4250
+ }
4251
+ if (ts.isSwitchStatement(n)) {
4252
+ ts.forEachChild(n, (c) => visit(c, { ...st, breakBound: true }));
4253
+ return;
4254
+ }
4255
+ // tsc-excluded arms carry no escaping edges: an edge the CFA cannot
4256
+ // take must not stage kills at its would-be destination
4257
+ // (tscExcludedArm — mirrors allRoutesLeaveFunction's route walk).
4258
+ ts.forEachChild(n, (c) => {
4259
+ if (!this.tscExcludedArm(n, c)) visit(c, st);
4260
+ });
4261
+ };
4262
+ const start: Bound = { labels: new Set(), breakBound: false, continueBound: false };
4263
+ for (const s of stmts) visit(s, start);
4264
+ return { breaks, continues, callbackReturn };
4265
+ }
4266
+
4267
+ private emitStatementList(stmts: readonly ts.Statement[], ctx: Ctx): void {
2968
4268
  for (let i = 0; i < stmts.length; i++) {
2969
4269
  const stmt = stmts[i];
2970
4270
  for (const c of this.leadingComments(stmt)) this.push(ctx, c);
@@ -2982,8 +4282,16 @@ export class Emitter {
2982
4282
  !next.elseStatement &&
2983
4283
  test !== null &&
2984
4284
  ts.isIdentifier(test.target) &&
2985
- test.target.text === decl.name.text &&
2986
- this.alwaysExits(next.thenStatement)
4285
+ // Declaration identity, not name text: the guard must test THIS
4286
+ // declaration for the fusion's const to stand in for it (a
4287
+ // same-named outer local tested here narrows the wrong slot).
4288
+ this.tast.declarationOf(test.target) === decl &&
4289
+ this.alwaysExits(next.thenStatement) &&
4290
+ // A reassigned `let` cannot fuse: the fusion emits `const` typed by
4291
+ // the non-optional payload, so a later `p = ...` (or a legal
4292
+ // `p = null`) has no binding to land in. The plain path already
4293
+ // types it `var p: ?T` and guards with a real `if`.
4294
+ !this.isReassigned(decl, ctx)
2987
4295
  ) {
2988
4296
  const initType = this.zTypeOfExpr(decl.initializer, ctx);
2989
4297
  if (initType.k === "optional") {
@@ -3005,10 +4313,19 @@ export class Emitter {
3005
4313
  cond: ts.Expression,
3006
4314
  op: ts.SyntaxKind = ts.SyntaxKind.EqualsEqualsEqualsToken,
3007
4315
  ): { target: ts.Expression; flavor: "null" | "undefined" } | null {
3008
- if (!ts.isBinaryExpression(cond) || cond.operatorToken.kind !== op) return null;
4316
+ // Wrapper spellings must not change what the test matches: the
4317
+ // condition, either operand, and the returned target all strip
4318
+ // parentheses, non-null assertions, `as`, and `satisfies` — emission
4319
+ // erases every one of them, and tsc's own narrowing sees through them
4320
+ // too (`(q) === null` and `q! !== null` both test `q`), so downstream
4321
+ // shape checks and key derivations see the identifier itself.
4322
+ const c = unwrapExpr(cond);
4323
+ if (!ts.isBinaryExpression(c) || c.operatorToken.kind !== op) return null;
4324
+ const left = unwrapExpr(c.left);
4325
+ const right = unwrapExpr(c.right);
3009
4326
  const sides: Array<[ts.Expression, ts.Expression]> = [
3010
- [cond.left, cond.right],
3011
- [cond.right, cond.left],
4327
+ [left, right],
4328
+ [right, left],
3012
4329
  ];
3013
4330
  for (const [target, emptySide] of sides) {
3014
4331
  const flavor = this.emptyFlavorOf(emptySide);
@@ -3029,6 +4346,17 @@ export class Emitter {
3029
4346
  return null;
3030
4347
  }
3031
4348
 
4349
+ /// A literal JS empty in VALUE position, through the value-preserving
4350
+ /// wrappers emission erases (parens, `as`, `satisfies`, non-null
4351
+ /// assertions): the `null` keyword or the global `undefined` identifier.
4352
+ /// Every ternary-arm and nullish EMPTINESS decision must use this, never
4353
+ /// a ZType check — `undefined`'s internal type is void, so a type check
4354
+ /// reads an `undefined` arm as a non-empty value and drops the
4355
+ /// optionality it carries, skipping the later guard's unwrap.
4356
+ private isEmptyLiteral(e: ts.Expression): boolean {
4357
+ return this.emptyFlavorOf(unwrapExpr(e)) !== null;
4358
+ }
4359
+
3032
4360
  /// R7c: JS keeps null and undefined distinct; the native optional folds
3033
4361
  /// both into one empty. An empty test therefore only maps when the
3034
4362
  /// target's own type carries exactly the tested empty — testing the wrong
@@ -3051,8 +4379,20 @@ export class Emitter {
3051
4379
  }
3052
4380
  }
3053
4381
 
4382
+ /// Whether a statement NEVER falls through to the statement after it.
4383
+ /// tsc's control-flow analysis narrows after any such statement — return,
4384
+ /// throw, break, and continue all qualify (a break/continue jumps to an
4385
+ /// enclosing construct's boundary, never to the next statement in
4386
+ /// sequence), so an early-exit guard narrows the remainder of its block
4387
+ /// no matter which exit the guard takes. A constant-true loop that no
4388
+ /// break binds qualifies too: it never completes normally, so tsc treats
4389
+ /// the statement after it as unreachable (and Zig types such a loop
4390
+ /// noreturn — the two terminality judgments must stay aligned).
4391
+ /// Kill-frame drops need the stronger whole-function question; that is
4392
+ /// allRoutesLeaveFunction.
3054
4393
  private alwaysExits(stmt: ts.Statement): boolean {
3055
4394
  if (ts.isReturnStatement(stmt)) return true;
4395
+ if (ts.isBreakStatement(stmt) || ts.isContinueStatement(stmt)) return true;
3056
4396
  // R20: a throw never falls through (it unwinds to a catch or out of
3057
4397
  // the function), and a try/catch exits when both arms do — any throw
3058
4398
  // mid-try lands in the catch, which exits. NS1058 keeps `finally`
@@ -3060,7 +4400,8 @@ export class Emitter {
3060
4400
  if (ts.isThrowStatement(stmt)) return true;
3061
4401
  if (ts.isTryStatement(stmt)) {
3062
4402
  const tryExits = this.alwaysExits(stmt.tryBlock);
3063
- const catchExits = stmt.catchClause === undefined || this.alwaysExits(stmt.catchClause.block);
4403
+ const catchExits =
4404
+ stmt.catchClause === undefined || this.alwaysExits(stmt.catchClause.block);
3064
4405
  return tryExits && catchExits;
3065
4406
  }
3066
4407
  if (ts.isBlock(stmt)) {
@@ -3074,43 +4415,486 @@ export class Emitter {
3074
4415
  this.alwaysExits(stmt.elseStatement)
3075
4416
  );
3076
4417
  }
4418
+ // A constant-true loop with no break bound to it never completes
4419
+ // normally, so the statement after it is unreachable — tsc's CFA types
4420
+ // post-loop code off the paths that never get there. The recognition
4421
+ // mirrors tsc's scope for our subset: the literal `true` keyword (and
4422
+ // the omitted / literal-true `for` condition) only, never arbitrary
4423
+ // constant-foldable expressions. Returns and throws inside the loop
4424
+ // leave the function without completing the loop, so they don't make
4425
+ // its end reachable (allRoutesLeaveFunction classifies them as routes
4426
+ // of their own); `continue` stays inside. Only a break bound to the
4427
+ // loop resumes right after it.
4428
+ if (ts.isWhileStatement(stmt) || ts.isDoStatement(stmt)) {
4429
+ return stmt.expression.kind === ts.SyntaxKind.TrueKeyword && !this.bindsBreak(stmt);
4430
+ }
4431
+ if (ts.isForStatement(stmt)) {
4432
+ return (
4433
+ (stmt.condition === undefined || stmt.condition.kind === ts.SyntaxKind.TrueKeyword) &&
4434
+ !this.bindsBreak(stmt)
4435
+ );
4436
+ }
3077
4437
  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.
4438
+ // A break bound to THIS switch resumes right after it, so the switch
4439
+ // completes normally even when every clause body ends in an exit
4440
+ // statement (the ubiquitous clause-terminating `break;` is exactly
4441
+ // such a break).
4442
+ if (this.bindsBreak(stmt)) return false;
4443
+ // A value switch (R13d) without a default may skip every clause —
4444
+ // unless its case labels cover the scrutinee's literal-union type,
4445
+ // in which case tsc's CFA (which is what this predicate mirrors)
4446
+ // treats the switch as always entering a clause. Kind switches are
4447
+ // exhaustive by NS1015; defaulted switches always enter a clause;
4448
+ // everything else consults the type (conservative false when the
4449
+ // scrutinee is not an enumerable literal union).
3082
4450
  const kindSwitch =
3083
4451
  ts.isPropertyAccessExpression(stmt.expression) && stmt.expression.name.text === "kind";
3084
4452
  const hasDefault = stmt.caseBlock.clauses.some((c) => ts.isDefaultClause(c));
3085
- if (!kindSwitch && !hasDefault) return false;
3086
- return stmt.caseBlock.clauses.every((c) => {
4453
+ if (!kindSwitch && !hasDefault && !this.valueSwitchCoversScrutineeType(stmt)) return false;
4454
+ // Stacked case labels (`case "a": case "b": body`) share one body:
4455
+ // JS falls through an empty clause onto the next clause's statements
4456
+ // (the switch emitters coalesce the labels into one arm the same
4457
+ // way), so an empty clause's terminality is its group's tail's — the
4458
+ // next statement-bearing clause at or after it. A trailing run of
4459
+ // empty clauses has no body at all: control falls out of the switch,
4460
+ // so the switch completes normally.
4461
+ const clauses = stmt.caseBlock.clauses;
4462
+ return clauses.every((c, i) => {
3087
4463
  let stmts: readonly ts.Statement[] = c.statements;
4464
+ for (let j = i + 1; stmts.length === 0 && j < clauses.length; j++) {
4465
+ stmts = clauses[j].statements;
4466
+ }
3088
4467
  if (stmts.length === 1 && ts.isBlock(stmts[0])) stmts = (stmts[0] as ts.Block).statements;
3089
4468
  const last = stmts[stmts.length - 1];
3090
4469
  return last !== undefined && this.alwaysExits(last);
3091
4470
  });
3092
4471
  }
4472
+ if (ts.isLabeledStatement(stmt)) {
4473
+ // A label adds exactly one edge: `break label` resumes right AFTER
4474
+ // the labeled statement, making its end reachable. So the statement
4475
+ // is terminal iff the wrapped statement is terminal AND nothing
4476
+ // inside breaks to the label. The check is additive: a wrapped
4477
+ // loop's unlabeled breaks are already the loop's own concern
4478
+ // (bindsBreak, which also sees wrapping labels), and a labeled
4479
+ // BLOCK's inner terminality comes from the block rule above.
4480
+ return (
4481
+ this.alwaysExits(stmt.statement) &&
4482
+ !this.breaksToLabel(stmt.statement, stmt.label.text)
4483
+ );
4484
+ }
3093
4485
  return false;
3094
4486
  }
3095
4487
 
4488
+ /// Whether a defaultless VALUE switch's case labels cover every member of
4489
+ /// the scrutinee's literal-union type. Enumerable scrutinees are
4490
+ /// string/number/boolean literal unions ONLY: any wider type, any
4491
+ /// non-literal member, or any case label that is not a literal after
4492
+ /// wrapper-stripping answers false — the conservative side (a false merely
4493
+ /// merges a kill tsc kept and completes the lowered fallthrough; a wrong
4494
+ /// true emits an `else => unreachable` real execution can REACH). The type
4495
+ /// consulted is scrutineeCoverageType's SOUND type, never the checker's
4496
+ /// raw flow type: tsc keeps a local's narrowing across callback bodies
4497
+ /// that assign it, so its flow-exhaustiveness can be false at runtime.
4498
+ /// alwaysExits stays syntax-only on every other construct, and every
4499
+ /// caller is an emission path where `this.tast` is live, so the capability
4500
+ /// is unconditional. THE AGREEMENT INVARIANT: the terminality claim and
4501
+ /// the emitted shape must never disagree — no switch construct may be
4502
+ /// claimed terminal while its lowering emits a completable fallthrough.
4503
+ /// Each lowering either closes or declines:
4504
+ /// - emitSwitch (kind): a Zig enum switch is exhaustive by construction
4505
+ /// (NS1015 gates uncovered arms), and a terminal claim requires every
4506
+ /// arm group to exit, so the shape closes by construction;
4507
+ /// - emitValueSwitch: a covered-by-type defaultless switch whose arms
4508
+ /// all exit closes its never-reached fallthrough with
4509
+ /// `else => unreachable` (numeric) or emits no else at all (string
4510
+ /// enums, already Zig-exhaustive), and asserts the agreement;
4511
+ /// - emitPlainSwitch: the lowered if/else chain closes a
4512
+ /// claimed-terminal defaultless switch with an `unreachable` else
4513
+ /// (its `claimsTerminal`), and asserts the agreement.
4514
+ /// All consumers read this one memoized judgment and demote together.
4515
+ private valueSwitchCoversScrutineeType(stmt: ts.SwitchStatement): boolean {
4516
+ const memo = this.switchCoversTypeMemo.get(stmt);
4517
+ if (memo !== undefined) return memo;
4518
+ const answer = this.computeValueSwitchCoversScrutineeType(stmt);
4519
+ this.switchCoversTypeMemo.set(stmt, answer);
4520
+ return answer;
4521
+ }
4522
+
4523
+ /// The type a defaultless switch's exhaustiveness may be judged against —
4524
+ /// null when no sound basis exists (the caller then answers false). tsc's
4525
+ /// flow type at the scrutinee is NOT such a basis on its own: tsc never
4526
+ /// widens a local's narrowing for assignments inside callbacks (it types
4527
+ /// `let k: "a" | "b" = "a"; xs.map(() => { k = "b"; }); switch (k)` with
4528
+ /// k still "a"), so a flow-exhaustive switch can be skipped by real
4529
+ /// execution. Sound bases, in order:
4530
+ /// - an identifier local/param never assigned inside any nested
4531
+ /// function of the switch's own enclosing function keeps the flow
4532
+ /// type: locals cannot alias, so a scan over nested-function scopes
4533
+ /// for assignments is exact, and without a capture-site assignment
4534
+ /// the straight-line CFA is;
4535
+ /// - any other narrowable reference (identifier, property read) is
4536
+ /// judged by its DECLARED type — a symbol can hold any member of its
4537
+ /// declared union at runtime whatever the flow claims;
4538
+ /// - a non-reference scrutinee (call result, arithmetic, literal) has
4539
+ /// no flow claims to distrust: its own resolved type stands.
4540
+ private scrutineeCoverageType(expr: ts.Expression): ts.Type | null {
4541
+ const e = unwrapExpr(expr);
4542
+ if (ts.isIdentifier(e)) {
4543
+ if (this.scrutineeFlowTrustable(e)) return this.tast.typeOf(e);
4544
+ return this.declaredTypeOfReference(e);
4545
+ }
4546
+ if (ts.isPropertyAccessExpression(e)) return this.declaredTypeOfReference(e.name);
4547
+ if (ts.isElementAccessExpression(e)) return null;
4548
+ return this.tast.typeOf(e);
4549
+ }
4550
+
4551
+ /// The declared (declaration-site) type of a reference: the annotation
4552
+ /// when the declaration carries one, else the checker's type AT the
4553
+ /// declaration name — the symbol's initial type, which no flow narrowing
4554
+ /// has touched. Null when the declaration shape is not one whose declared
4555
+ /// type is recoverable; callers treat null as "cannot judge".
4556
+ private declaredTypeOfReference(name: ts.Node): ts.Type | null {
4557
+ const decl = this.tast.declarationOf(name);
4558
+ if (!decl) return null;
4559
+ if (
4560
+ (ts.isVariableDeclaration(decl) ||
4561
+ ts.isParameter(decl) ||
4562
+ ts.isPropertySignature(decl) ||
4563
+ ts.isPropertyDeclaration(decl)) &&
4564
+ decl.type
4565
+ ) {
4566
+ return this.tast.typeFromTypeNode(decl.type);
4567
+ }
4568
+ if (ts.isVariableDeclaration(decl) && ts.isIdentifier(decl.name)) {
4569
+ return this.tast.typeOf(decl.name);
4570
+ }
4571
+ return null;
4572
+ }
4573
+
4574
+ /// Whether the flow type of this identifier may be trusted for an
4575
+ /// exhaustiveness claim: it names a local/param declared in the SAME
4576
+ /// enclosing function, and no nested function/callback in that function's
4577
+ /// body assigns it BEFORE the read can execute. Locals cannot alias in
4578
+ /// TypeScript, so the only escape hatch from the straight-line CFA is a
4579
+ /// capture-site assignment — the exact hole tsc's optimistic callback
4580
+ /// model leaves open. Declines when the declaration lives in an outer
4581
+ /// scope (the local IS a capture there) or when any nested function that
4582
+ /// can have RUN before the read (nestedFnRunsBeforeUse: position for
4583
+ /// arrows/function expressions, always for hoisted declarations and
4584
+ /// class members, back edges for shared loops) assigns or ++/--s it.
4585
+ private scrutineeFlowTrustable(id: ts.Identifier): boolean {
4586
+ const decl = this.tast.declarationOf(id);
4587
+ if (!decl || (!ts.isVariableDeclaration(decl) && !ts.isParameter(decl))) return false;
4588
+ const isFnScope = (n: ts.Node): boolean =>
4589
+ ts.isArrowFunction(n) ||
4590
+ ts.isFunctionExpression(n) ||
4591
+ ts.isFunctionDeclaration(n) ||
4592
+ ts.isMethodDeclaration(n) ||
4593
+ ts.isConstructorDeclaration(n) ||
4594
+ ts.isGetAccessorDeclaration(n) ||
4595
+ ts.isSetAccessorDeclaration(n);
4596
+ const enclosing = (n: ts.Node): ts.Node => {
4597
+ let cur: ts.Node | undefined = n.parent;
4598
+ while (cur && !isFnScope(cur)) cur = cur.parent;
4599
+ return cur ?? n.getSourceFile();
4600
+ };
4601
+ const scope = enclosing(id);
4602
+ if (scope !== enclosing(decl)) return false;
4603
+ let assignedInNested = false;
4604
+ // `root` is the OUTERMOST nested function of the current subtree: the
4605
+ // reach-before-use judgment belongs to it (an arrow inside a hoisted
4606
+ // declaration runs whenever the declaration does, so the inner arrow's
4607
+ // own position proves nothing).
4608
+ const visit = (n: ts.Node, root: ts.Node | null): void => {
4609
+ if (assignedInNested) return;
4610
+ const enter = root ?? (n !== scope && isFnScope(n) ? n : null);
4611
+ if (enter) {
4612
+ if (
4613
+ ts.isBinaryExpression(n) &&
4614
+ n.operatorToken.kind >= ts.SyntaxKind.FirstAssignment &&
4615
+ n.operatorToken.kind <= ts.SyntaxKind.LastAssignment
4616
+ ) {
4617
+ const target = unwrapExpr(n.left);
4618
+ if (
4619
+ ts.isIdentifier(target) &&
4620
+ this.tast.declarationOf(target) === decl &&
4621
+ this.nestedFnRunsBeforeUse(enter, id)
4622
+ ) {
4623
+ assignedInNested = true;
4624
+ return;
4625
+ }
4626
+ }
4627
+ if (
4628
+ (ts.isPrefixUnaryExpression(n) || ts.isPostfixUnaryExpression(n)) &&
4629
+ (n.operator === ts.SyntaxKind.PlusPlusToken || n.operator === ts.SyntaxKind.MinusMinusToken)
4630
+ ) {
4631
+ const target = unwrapExpr(n.operand as ts.Expression);
4632
+ if (
4633
+ ts.isIdentifier(target) &&
4634
+ this.tast.declarationOf(target) === decl &&
4635
+ this.nestedFnRunsBeforeUse(enter, id)
4636
+ ) {
4637
+ assignedInNested = true;
4638
+ return;
4639
+ }
4640
+ }
4641
+ }
4642
+ ts.forEachChild(n, (c) => visit(c, enter));
4643
+ };
4644
+ visit(scope, null);
4645
+ return !assignedInNested;
4646
+ }
4647
+
4648
+ /// Whether an assignment inside nested function `fn` can have EXECUTED
4649
+ /// before the flow-trusted read at `use`. Labels the position rule with
4650
+ /// JS evaluation semantics:
4651
+ /// - function DECLARATIONS hoist — they exist from scope start, so an
4652
+ /// earlier call can run them wherever they sit — and class-member
4653
+ /// bodies (methods, accessors, constructors) exist from their
4654
+ /// container's creation: all count regardless of position;
4655
+ /// - arrow functions and function EXPRESSIONS do not exist as values
4656
+ /// before their definition evaluates, so one whose definition sits
4657
+ /// textually after the read cannot have run before it — UNLESS a
4658
+ /// loop encloses both, whose back edge re-enters the read after the
4659
+ /// definition evaluated on an earlier iteration. An arrow defined
4660
+ /// before the read counts even when only a variable holds it
4661
+ /// (conservative-correct: whether anything calls it is not asked).
4662
+ private nestedFnRunsBeforeUse(fn: ts.Node, use: ts.Identifier): boolean {
4663
+ if (!ts.isArrowFunction(fn) && !ts.isFunctionExpression(fn)) return true;
4664
+ if (fn.getStart() < use.getStart()) return true;
4665
+ for (let cur: ts.Node | undefined = fn.parent; cur && !ts.isSourceFile(cur); cur = cur.parent) {
4666
+ if (ts.isFunctionLike(cur)) break;
4667
+ if (
4668
+ ts.isIterationStatement(cur, false) &&
4669
+ cur.getStart() <= use.getStart() &&
4670
+ use.getEnd() <= cur.getEnd()
4671
+ ) {
4672
+ return true;
4673
+ }
4674
+ }
4675
+ return false;
4676
+ }
4677
+
4678
+ private computeValueSwitchCoversScrutineeType(stmt: ts.SwitchStatement): boolean {
4679
+ const type = this.scrutineeCoverageType(stmt.expression);
4680
+ if (type === null) return false;
4681
+ const members = type.isUnion() ? type.types : [type];
4682
+ const wanted = new Set<string>();
4683
+ for (const member of members) {
4684
+ if (member.isStringLiteral()) wanted.add(`s:${member.value}`);
4685
+ else if (member.isNumberLiteral()) wanted.add(`n:${member.value}`);
4686
+ else if (member.flags & ts.TypeFlags.BooleanLiteral) {
4687
+ wanted.add(`b:${this.tast.typeToString(member)}`);
4688
+ } else return false;
4689
+ }
4690
+ for (const clause of stmt.caseBlock.clauses) {
4691
+ if (ts.isDefaultClause(clause)) continue;
4692
+ const label = unwrapExpr(clause.expression);
4693
+ if (ts.isStringLiteral(label)) wanted.delete(`s:${label.text}`);
4694
+ else if (label.kind === ts.SyntaxKind.TrueKeyword) wanted.delete("b:true");
4695
+ else if (label.kind === ts.SyntaxKind.FalseKeyword) wanted.delete("b:false");
4696
+ else {
4697
+ const v = this.tast.constEvalNumber(label);
4698
+ if (v === null) return false;
4699
+ wanted.delete(`n:${v}`);
4700
+ }
4701
+ }
4702
+ return wanted.size === 0;
4703
+ }
4704
+
4705
+ /// Kill-frame drop eligibility: whether EVERY route out of this statement
4706
+ /// list leaves the emitted function. Only then may the list's narrowing
4707
+ /// kills drop (emitBlockStatements) or a catch arm close the exception
4708
+ /// paths over its try body (emitTryCore) — the final statement alone
4709
+ /// cannot answer this, because earlier statements open routes of their
4710
+ /// own. The routes, and when each one resumes in-function instead of
4711
+ /// leaving:
4712
+ /// - fallthrough off the end of the list — always resumes;
4713
+ /// - `return` — resumes where returns lower to labeled breaks (lifted
4714
+ /// callbacks: env.returnLeaves is false);
4715
+ /// - `break`/`continue` at any nesting depth whose target sits at or
4716
+ /// outside the list — always resumes (after the target construct,
4717
+ /// inside the function). One bound to a loop/switch/label WHOLLY
4718
+ /// inside the list stays inside it and is not a route out, so the
4719
+ /// walk tracks locally-bound targets, never spellings;
4720
+ /// - `throw`, or any statement containing a throwing call, whose
4721
+ /// handler can fall back into the function — the handler is the
4722
+ /// nearest catch inside the list, and the route's destination is
4723
+ /// that catch PLUS its continuation: a catch that falls through
4724
+ /// resumes at the statements following its try (transitively out
4725
+ /// through enclosing blocks), so the route leaves iff every route
4726
+ /// out of the catch leaves AND that continuation leaves. Outside
4727
+ /// any local try, whatever env.throwResumes says about the
4728
+ /// surroundings.
4729
+ /// When a route resists classification the answer is false (merge): an
4730
+ /// over-merge costs a narrow tsc would have kept, an under-merge
4731
+ /// resurrects a dead one and emits an unwrap Zig rejects. The
4732
+ /// continuation after a try is known positionally inside statement
4733
+ /// lists (the top list and nested blocks); inside loop bodies, switch
4734
+ /// clauses, and inline callbacks a catch's fallthrough re-enters the
4735
+ /// construct, so the continuation is treated as resuming there.
4736
+ /// `env.edgesLeave` re-asks the question with escaping break/continue
4737
+ /// edges and lowered returns treated as LEAVING: emitBlockStatements uses
4738
+ /// the difference to isolate lists whose only in-function routes are
4739
+ /// non-local edges (their kills stage at the edges' destinations rather
4740
+ /// than merging — see edgeKillRouting). A leaving return's expression
4741
+ /// still walks: throwing calls inside it ride the throw edges, not the
4742
+ /// return edge.
4743
+ private allRoutesLeaveFunction(
4744
+ stmts: readonly ts.Statement[],
4745
+ env: { returnLeaves: boolean; throwResumes: boolean; edgesLeave?: boolean },
4746
+ ): boolean {
4747
+ // `labels` / `breaks` / `continues` carry the targets bound inside the
4748
+ // list so far on this path; `throwResumes` is the handler visibility at
4749
+ // this point (re-derived at every try/catch met on the way down);
4750
+ // `inCallback` marks inline (unlifted) callback bodies, whose returns
4751
+ // are their own but whose throwing calls act at this site.
4752
+ interface State {
4753
+ readonly labels: ReadonlySet<string>;
4754
+ readonly breaks: number;
4755
+ readonly continues: number;
4756
+ readonly throwResumes: boolean;
4757
+ readonly inCallback: boolean;
4758
+ }
4759
+ // `tailLeaves`: whether control falling through past the node (to the
4760
+ // rest of its enclosing list, transitively outward) leaves the
4761
+ // function on every route — the positional continuation a
4762
+ // fallthrough catch hands a caught throw.
4763
+ const resumes = (n: ts.Node, st: State, tailLeaves: boolean): boolean => {
4764
+ const walk = (c: ts.Node): boolean => resumes(c, st, tailLeaves);
4765
+ if (ts.isBreakStatement(n)) {
4766
+ if (env.edgesLeave) return false;
4767
+ return !st.inCallback && (n.label ? !st.labels.has(n.label.text) : st.breaks === 0);
4768
+ }
4769
+ if (ts.isContinueStatement(n)) {
4770
+ if (env.edgesLeave) return false;
4771
+ return !st.inCallback && (n.label ? !st.labels.has(n.label.text) : st.continues === 0);
4772
+ }
4773
+ if (ts.isReturnStatement(n)) {
4774
+ if (!st.inCallback && !env.returnLeaves && !env.edgesLeave) return true;
4775
+ return n.expression !== undefined && walk(n.expression);
4776
+ }
4777
+ if (ts.isThrowStatement(n)) {
4778
+ return st.throwResumes || walk(n.expression);
4779
+ }
4780
+ if ((ts.isCallExpression(n) || ts.isNewExpression(n)) && st.throwResumes) {
4781
+ const target = this.calleeOwnerOf(n);
4782
+ if (target && this.leakingFns.has(target)) return true;
4783
+ }
4784
+ if (ts.isBlock(n)) {
4785
+ // A block's own fallthrough continues wherever the block's does,
4786
+ // so its statements scan positionally against the same tail.
4787
+ return scanList(n.statements, st, tailLeaves).resumes;
4788
+ }
4789
+ if (ts.isTryStatement(n) && n.catchClause !== undefined) {
4790
+ // Throws in the body land in this catch, whose destination is the
4791
+ // catch block plus its continuation: a fallthrough catch resumes
4792
+ // at the statements after this try, so the caught throw leaves
4793
+ // iff the catch-then-rest continuation leaves. The catch itself
4794
+ // runs against the handler visible OUTSIDE this try (its own
4795
+ // throws escape to enclosing handlers, never back into it).
4796
+ const catchScan = scanList(n.catchClause.block.statements, st, tailLeaves);
4797
+ const bodyThrowResumes = !catchScan.leaves;
4798
+ return (
4799
+ resumes(n.tryBlock, { ...st, throwResumes: bodyThrowResumes }, tailLeaves) ||
4800
+ catchScan.resumes ||
4801
+ (n.finallyBlock !== undefined && walk(n.finallyBlock))
4802
+ );
4803
+ }
4804
+ if (ts.isLabeledStatement(n)) {
4805
+ const bound = new Set(st.labels);
4806
+ bound.add(n.label.text);
4807
+ return resumes(n.statement, { ...st, labels: bound }, tailLeaves);
4808
+ }
4809
+ if (
4810
+ ts.isWhileStatement(n) ||
4811
+ ts.isDoStatement(n) ||
4812
+ ts.isForStatement(n) ||
4813
+ ts.isForOfStatement(n) ||
4814
+ ts.isForInStatement(n)
4815
+ ) {
4816
+ // The loop binds unlabeled break/continue for its whole subtree
4817
+ // (heads hold no break/continue — tsc rejects them there). A
4818
+ // fallthrough inside the body resumes at the back edge, in the
4819
+ // function, so the body scans against a resuming tail. A
4820
+ // tsc-excluded body (while (false), for (; false;)) contributes
4821
+ // no routes at all — an edge tsc's CFA cannot take is not a route
4822
+ // (tscExcludedArm; the joins already give such arms no kills).
4823
+ return (
4824
+ ts.forEachChild(n, (c) =>
4825
+ (!this.tscExcludedArm(n, c) &&
4826
+ resumes(c, { ...st, breaks: st.breaks + 1, continues: st.continues + 1 }, false)) ||
4827
+ undefined,
4828
+ ) === true
4829
+ );
4830
+ }
4831
+ if (ts.isSwitchStatement(n)) {
4832
+ // Clause fallthrough resumes at the next clause / after the
4833
+ // switch — in the function — so clauses scan against a resuming
4834
+ // tail too.
4835
+ return (
4836
+ walk(n.expression) ||
4837
+ resumes(n.caseBlock, { ...st, breaks: st.breaks + 1 }, false)
4838
+ );
4839
+ }
4840
+ // Declarations don't run here; lifted callbacks are analyzed at
4841
+ // their own emission (their bodies get a retLabel of their own).
4842
+ if (ts.isFunctionDeclaration(n)) return false;
4843
+ if (ts.isArrowFunction(n) || ts.isFunctionExpression(n)) {
4844
+ if ([...this.hoistedFns.values()].includes(n)) return false;
4845
+ return resumes(n.body, { ...st, inCallback: true }, false);
4846
+ }
4847
+ // tsc-excluded arms (`if (false)` then, `if (true)` else) hold no
4848
+ // routes tsc's CFA can take: a dead `break` must not read as a
4849
+ // loop-escaping edge (tscExcludedArm).
4850
+ return ts.forEachChild(n, (c) => (!this.tscExcludedArm(n, c) && walk(c)) || undefined) === true;
4851
+ };
4852
+ // One right-to-left pass over a statement list: `resumes` is whether
4853
+ // any route out of any statement resumes in-function (each statement
4854
+ // classified against the continuation after ITS position); `leaves`
4855
+ // is whether control entering the list leaves the function on every
4856
+ // route — no route resumes, and fallthrough (which stops at the first
4857
+ // always-exiting statement) bottoms out in an exit or a leaving tail.
4858
+ // The fallthrough chain deliberately ignores in-list resuming routes:
4859
+ // any such route already forces `resumes`, and every consumer of
4860
+ // `leaves` (the verdict below, a caught throw's continuation) sits
4861
+ // under a scan whose `resumes` it feeds.
4862
+ const scanList = (
4863
+ list: readonly ts.Statement[],
4864
+ st: State,
4865
+ tailLeaves: boolean,
4866
+ ): { leaves: boolean; resumes: boolean } => {
4867
+ let cont = tailLeaves;
4868
+ let any = false;
4869
+ for (let i = list.length - 1; i >= 0; i--) {
4870
+ if (resumes(list[i], st, cont)) any = true;
4871
+ cont = this.alwaysExits(list[i]) || cont;
4872
+ }
4873
+ return { leaves: !any && cont, resumes: any };
4874
+ };
4875
+ const start: State = {
4876
+ labels: new Set(),
4877
+ breaks: 0,
4878
+ continues: 0,
4879
+ throwResumes: env.throwResumes,
4880
+ inCallback: false,
4881
+ };
4882
+ // Fallthrough off the end of the whole list always resumes.
4883
+ return scanList(stmts, start, false).leaves;
4884
+ }
4885
+
3096
4886
  private emitOrelseFusion(decl: ts.VariableDeclaration, exit: ts.Statement, inner: ZType, ctx: Ctx): void {
3097
4887
  const name = this.claim(ctx, decl, zigLocalName((decl.name as ts.Identifier).text));
3098
4888
  ctx.localTypes.set(decl, inner);
3099
4889
  const init = orelseOperand(this.emitExpr(decl.initializer!, ctx).code);
3100
4890
  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
- }
4891
+ // A one-statement exit inlines (`orelse return v` / `orelse break` /
4892
+ // `orelse continue`); anything needing statements takes the block form
4893
+ // below — the block never falls through, so Zig types it noreturn.
4894
+ const inline = this.singleExitText(exit, ctx);
4895
+ if (inline !== null) {
4896
+ this.push(ctx, `const ${name} = ${init} orelse ${inline}`);
4897
+ return;
3114
4898
  }
3115
4899
  this.push(ctx, `const ${name} = ${init} orelse {`);
3116
4900
  const sub = this.nestedCtx(ctx);
@@ -3119,6 +4903,23 @@ export class Emitter {
3119
4903
  this.push(ctx, `};`);
3120
4904
  }
3121
4905
 
4906
+ /// Clone a ctx for a probe or a same-indent sub-emission. ISOLATION LAW:
4907
+ /// the clone shares every mutable flow structure with its parent BY
4908
+ /// REFERENCE — memberSubst, stillOptionalSubst, narrowedUnion, the
4909
+ /// narrowKilled frame stack, the edgeKills stages, and pendingCatchKills
4910
+ /// — it isolates only the output lines. A PROBE (an emission whose lines
4911
+ /// may be discarded to pick a lowering shape) must therefore bracket
4912
+ /// itself with withNarrowScope: a probe that processes an assignment to
4913
+ /// an outer narrowed local (an inline map callback inside a ternary arm)
4914
+ /// would otherwise delete the narrowing for everything emitted after it
4915
+ /// — the SIBLING arm then reads the optional raw, invalid Zig. Sibling
4916
+ /// arms of one expression construct follow the statement-level law: each
4917
+ /// arm probes AND emits from the construct's entry state, and the arms'
4918
+ /// real kills join once after the last arm (applyJoinedNarrowKills).
4919
+ /// Kills a discarded probe stages on the shared edge sets (edgeKills,
4920
+ /// pendingCatchKills) are re-staged identically when the arm re-emits,
4921
+ /// so the sharing stays observationally clean — the narrowing maps and
4922
+ /// kill frames are the state a probe MUST NOT touch.
3122
4923
  private childCtx(ctx: Ctx): Ctx {
3123
4924
  return { ...ctx, lines: [], indent: ctx.indent };
3124
4925
  }
@@ -3145,20 +4946,37 @@ export class Emitter {
3145
4946
  this.emitIf(stmt, ctx);
3146
4947
  return;
3147
4948
  }
4949
+ // Loops (and below, labeled statements and switches) bracket their
4950
+ // emission with an edge-kill stage: kills that ride a break edge bound
4951
+ // here apply to the POST-construct state — the destination the break
4952
+ // resumes at — and kills on a continue edge ride the back edge into
4953
+ // the loop-entry join. The emitter realizes both as the post-loop
4954
+ // application below: the loop-entry model delegates in-body
4955
+ // next-iteration reads to tsc (a read relying on a narrow the back
4956
+ // edge kills is a tsc error the checker already rejected), so the
4957
+ // only remaining state a back-edge kill must reach is the loop's
4958
+ // normal-completion exit — the same post-loop point.
3148
4959
  if (ts.isWhileStatement(stmt)) {
3149
- this.emitWhile(stmt, ctx, null);
4960
+ const staged = this.stagedEdgeKills(ctx, "loop", null, () => this.emitWhile(stmt, ctx, null));
4961
+ // A `while (false)` body is tsc-unreachable (tscExcludedArm): kills
4962
+ // its break edges staged here never execute, so they don't apply.
4963
+ this.applyJoinedNarrowKills(ctx, this.tscExcludedArm(stmt, stmt.statement) ? new Set() : staged);
3150
4964
  return;
3151
4965
  }
3152
4966
  if (ts.isDoStatement(stmt)) {
3153
- this.emitDoWhile(stmt, ctx, null);
4967
+ this.applyJoinedNarrowKills(ctx, this.stagedEdgeKills(ctx, "loop", null, () => this.emitDoWhile(stmt, ctx, null)));
3154
4968
  return;
3155
4969
  }
3156
4970
  if (ts.isForStatement(stmt)) {
3157
- this.emitClassicFor(stmt, ctx, null);
4971
+ const staged = this.stagedEdgeKills(ctx, "loop", null, () => this.emitClassicFor(stmt, ctx, null));
4972
+ // A `for (; false;)` body is tsc-unreachable exactly like a
4973
+ // `while (false)` body (tscExcludedArm): kills its break edges
4974
+ // staged here never execute, so they don't apply.
4975
+ this.applyJoinedNarrowKills(ctx, this.tscExcludedArm(stmt, stmt.statement) ? new Set() : staged);
3158
4976
  return;
3159
4977
  }
3160
4978
  if (ts.isForOfStatement(stmt)) {
3161
- this.emitForOf(stmt, ctx, null);
4979
+ this.applyJoinedNarrowKills(ctx, this.stagedEdgeKills(ctx, "loop", null, () => this.emitForOf(stmt, ctx, null)));
3162
4980
  return;
3163
4981
  }
3164
4982
  if (ts.isLabeledStatement(stmt)) {
@@ -3171,43 +4989,86 @@ export class Emitter {
3171
4989
  const label = this.labelReferenced(stmt.statement, stmt.label.text)
3172
4990
  ? loopLabel(stmt.label.text)
3173
4991
  : null;
4992
+ // The stage binds by the SOURCE label: a labeled break/continue's
4993
+ // kills must land at this construct's post-state even from deep
4994
+ // inside nested loops (edgeKillRouting resolves labels innermost-
4995
+ // out, so an inner-targeted unlabeled break never binds here).
4996
+ const jsLabel = stmt.label.text;
3174
4997
  const inner = stmt.statement;
3175
4998
  if (ts.isWhileStatement(inner)) {
3176
- this.emitWhile(inner, ctx, label);
4999
+ const staged = this.stagedEdgeKills(ctx, "loop", jsLabel, () => this.emitWhile(inner, ctx, label));
5000
+ // Same tsc-unreachable exclusion as the unlabeled while dispatch.
5001
+ this.applyJoinedNarrowKills(ctx, this.tscExcludedArm(inner, inner.statement) ? new Set() : staged);
3177
5002
  } else if (ts.isDoStatement(inner)) {
3178
- this.emitDoWhile(inner, ctx, label);
5003
+ this.applyJoinedNarrowKills(ctx, this.stagedEdgeKills(ctx, "loop", jsLabel, () => this.emitDoWhile(inner, ctx, label)));
3179
5004
  } else if (ts.isForStatement(inner)) {
3180
- this.emitClassicFor(inner, ctx, label);
5005
+ const staged = this.stagedEdgeKills(ctx, "loop", jsLabel, () => this.emitClassicFor(inner, ctx, label));
5006
+ // Same tsc-unreachable exclusion as the unlabeled for dispatch.
5007
+ this.applyJoinedNarrowKills(ctx, this.tscExcludedArm(inner, inner.statement) ? new Set() : staged);
3181
5008
  } else if (ts.isForOfStatement(inner)) {
3182
- this.emitForOf(inner, ctx, label);
5009
+ this.applyJoinedNarrowKills(ctx, this.stagedEdgeKills(ctx, "loop", jsLabel, () => this.emitForOf(inner, ctx, label)));
3183
5010
  } else if (label === null) {
3184
5011
  this.emitStatement(inner, ctx);
3185
5012
  } 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, `}`);
5013
+ const kills = this.stagedEdgeKills(ctx, "block", jsLabel, () => {
5014
+ this.push(ctx, `${label}: {`);
5015
+ const sub = this.nestedCtx(ctx);
5016
+ this.emitBlockStatements(ts.isBlock(inner) ? inner.statements : [inner], sub);
5017
+ ctx.lines.push(...sub.lines);
5018
+ this.push(ctx, `}`);
5019
+ });
5020
+ this.applyJoinedNarrowKills(ctx, kills);
3191
5021
  }
3192
5022
  return;
3193
5023
  }
3194
5024
  if (ts.isSwitchStatement(stmt)) {
3195
- this.emitSwitch(stmt, ctx);
5025
+ // Clause-terminating breaks are stripped before their clause's route
5026
+ // analysis, so their kills ride the sibling JOIN (the switch
5027
+ // emitters' joinInto) to the same post-switch point this stage
5028
+ // applies at — one application, nothing dropped between the two
5029
+ // mechanisms. The stage itself keeps unlabeled-break RESOLUTION
5030
+ // faithful (a break under a switch binds the switch, never a loop
5031
+ // outside it; the mid-clause spellings that would stage here stop
5032
+ // the build at their own emission). Labeled exits out of a labeled
5033
+ // switch bind the wrapping labeled BLOCK's stage instead.
5034
+ this.applyJoinedNarrowKills(ctx, this.stagedEdgeKills(ctx, "switch", null, () => this.emitSwitch(stmt, ctx)));
3196
5035
  return;
3197
5036
  }
3198
5037
  if (ts.isExpressionStatement(stmt)) {
3199
5038
  this.emitExpressionStatement(stmt.expression, ctx);
3200
5039
  return;
3201
5040
  }
3202
- 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, `}`);
3208
- return;
3209
- }
5041
+ if (ts.isBlock(stmt)) {
5042
+ // A plain lexical block is NOT a merge boundary: tsc's narrowing is
5043
+ // flow-based, so a narrow (or kill) established inside a fall-through
5044
+ // block survives into the statements after it. Emission FLATTENS the
5045
+ // block's statements into the enclosing list instead of bracketing
5046
+ // them (no withNarrowScope, no Zig braces): name uniquing is already
5047
+ // function-wide (ctx.used and the decl-keyed ctx.names ride every
5048
+ // nested ctx by reference), so Zig block scope is never load-bearing
5049
+ // for shadowing — and flattening is what keeps a narrowing capture
5050
+ // lowered inside the block (an orelse fusion's const, a `.?` subst's
5051
+ // target) in the same Zig scope as the post-block reads that rely on
5052
+ // it. Merge contexts (if/else arms, loop bodies, switch clauses,
5053
+ // callback and try/catch bodies, labeled blocks) never reach this
5054
+ // case — their emitters unwrap the block and bracket its statement
5055
+ // LIST — so control only ever falls straight through here. Nested
5056
+ // plain blocks flatten recursively.
5057
+ this.emitStatementList(stmt.statements, ctx);
5058
+ return;
5059
+ }
3210
5060
  if (ts.isBreakStatement(stmt)) {
5061
+ // An unlabeled JS break binds the nearest loop OR switch; Zig's
5062
+ // `break` binds loops only. A break that reaches statement emission
5063
+ // bound to a switch (the clause-terminating `break;` never gets
5064
+ // here — the switch emitters strip it) would jump past the wrong
5065
+ // construct, so it stops the build instead of miscompiling.
5066
+ if (!stmt.label && this.breakBindsEnclosingSwitch(stmt)) {
5067
+ this.fail(
5068
+ stmt,
5069
+ "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>`)",
5070
+ );
5071
+ }
3211
5072
  this.push(ctx, stmt.label ? `break :${loopLabel(stmt.label.text)};` : `break;`);
3212
5073
  return;
3213
5074
  }
@@ -3289,26 +5150,186 @@ export class Emitter {
3289
5150
  private emitTry(stmt: ts.TryStatement, ctx: Ctx): void {
3290
5151
  const fin = stmt.finallyBlock && stmt.finallyBlock.statements.length > 0 ? stmt.finallyBlock : undefined;
3291
5152
  if (fin) {
5153
+ // The defer's TEXT precedes the try body's, but its FLOW follows it:
5154
+ // the finally runs at the construct's exits, after the body and catch.
5155
+ // So the finally emits in a bracketed scope — its entry state is the
5156
+ // pre-try narrows minus the keys tsc widens for a finally (see
5157
+ // finallyEntryKills: any possibly-null assignment in the try or catch
5158
+ // kills, path-insensitively), and its own kills stage in `finStage`
5159
+ // rather than merging, so the body emitted after this text still
5160
+ // holds every narrow tsc keeps at its program points (the finally
5161
+ // has not run there). The staged kills apply once at the construct's
5162
+ // exit below — the state every fall-through continuation resumes
5163
+ // from — and propagate outward through the enclosing frames exactly
5164
+ // like a merge-class kill applied at that spot.
3292
5165
  this.push(ctx, `{`);
3293
5166
  const wrap = this.nestedCtx(ctx);
3294
5167
  this.push(wrap, `// finally: a scoped defer runs it on every exit of this block.`);
3295
5168
  this.push(wrap, `defer {`);
3296
5169
  const finCtx = this.nestedCtx(wrap);
3297
- this.emitBlockStatements(fin.statements, finCtx);
5170
+ const finStage = new Set<string>();
5171
+ this.withNarrowScope(
5172
+ finCtx,
5173
+ "merge",
5174
+ () => {
5175
+ for (const key of this.finallyEntryKills(stmt, finCtx)) finCtx.memberSubst.delete(key);
5176
+ this.emitBlockStatements(fin.statements, finCtx);
5177
+ },
5178
+ finStage,
5179
+ );
3298
5180
  wrap.lines.push(...finCtx.lines);
3299
5181
  this.push(wrap, `}`);
3300
5182
  this.emitTryCore(stmt, wrap);
3301
5183
  ctx.lines.push(...wrap.lines);
3302
5184
  this.push(ctx, `}`);
5185
+ this.applyJoinedNarrowKills(ctx, finStage);
3303
5186
  return;
3304
5187
  }
3305
5188
  this.emitTryCore(stmt, ctx);
3306
5189
  }
3307
5190
 
5191
+ /// Whether tsc's CFA treats `arm` as statically unreachable inside
5192
+ /// `construct` — the then-arm of `if (false)`, the else-arm of
5193
+ /// `if (true)`, a `while (false)` body, a `for (; false;)` body (and its
5194
+ /// incrementor, which runs only after a body iteration). Such an arm
5195
+ /// contributes NOTHING to the flow bookkeeping: no kills at the branch
5196
+ /// join, no widening of a finally's entry narrows, no ROUTES either —
5197
+ /// a `break`/`continue`/`return`/`throw` under an excluded arm is not an
5198
+ /// edge tsc's CFA can take, so the route walks (allRoutesLeaveFunction,
5199
+ /// escapingEdgesOf) and the terminality binders (bindsBreak,
5200
+ /// breaksToLabel) give it nothing. Zig's comptime-false folding makes the
5201
+ /// same call on the emitted text, so the two terminality judgments stay
5202
+ /// aligned. The arm still EMITS — Zig compiles `if (false)` fine — only
5203
+ /// the flow accounting skips it.
5204
+ ///
5205
+ /// The split among the statement walkers is by QUESTION, not by walker:
5206
+ /// - FLOW-SEMANTICS walks (what can execute) exclude, per the above.
5207
+ /// - EMISSION-SHAPE walks keep counting excluded arms, because the
5208
+ /// arm's TEXT still emits: labelReferenced (a dead `break outer`
5209
+ /// still spells `break :outer` — Zig's unused-label check is
5210
+ /// syntactic, so the label must stay and stays used) and
5211
+ /// bindsContinue (the do-while first-pass-flag form must host any
5212
+ /// `continue` the body emits, dead or not — the plain trailing-test
5213
+ /// lowering has no valid spelling for that text).
5214
+ ///
5215
+ /// Only the bare `true`/`false` keywords qualify, pinned against the
5216
+ /// checker provider: a `const NEVER = false` alias condition WIDENS
5217
+ /// under tsc, so a reference never excludes. A do-while(false) body is
5218
+ /// never excluded either — the test runs AFTER the body, so the body
5219
+ /// executes once and tsc counts its assignments. A `for (;;)` with an
5220
+ /// OMITTED condition is the opposite judgment — an infinite loop
5221
+ /// (alwaysExits) — and never lands here: literal `false` ≠ omitted.
5222
+ private tscExcludedArm(construct: ts.Node, arm: ts.Node | undefined): boolean {
5223
+ if (arm === undefined) return false;
5224
+ if (ts.isIfStatement(construct)) {
5225
+ if (construct.expression.kind === ts.SyntaxKind.FalseKeyword) return arm === construct.thenStatement;
5226
+ if (construct.expression.kind === ts.SyntaxKind.TrueKeyword) return arm === construct.elseStatement;
5227
+ return false;
5228
+ }
5229
+ if (ts.isForStatement(construct)) {
5230
+ return (
5231
+ construct.condition !== undefined &&
5232
+ construct.condition.kind === ts.SyntaxKind.FalseKeyword &&
5233
+ (arm === construct.statement || arm === construct.incrementor)
5234
+ );
5235
+ }
5236
+ return (
5237
+ ts.isWhileStatement(construct) &&
5238
+ construct.expression.kind === ts.SyntaxKind.FalseKeyword &&
5239
+ arm === construct.statement
5240
+ );
5241
+ }
5242
+
5243
+ /// The narrows dead at a finally block's entry: tsc types a finally from
5244
+ /// the pre-try state minus every key the try or catch body may assign
5245
+ /// null/undefined to — path-insensitively, because an exception can hand
5246
+ /// control to the finally from between any two statements, so a later
5247
+ /// non-null re-assignment does not revive the narrow there. A provably
5248
+ /// non-null assignment keeps a live-slot `.?` spelling (it reads the
5249
+ /// variable, never a stale value; valid at every interruption point,
5250
+ /// since the slot holds the guarded value before the write and the
5251
+ /// non-null replacement after it). A capture spelling still drops —
5252
+ /// defensively: every capture-binding construct declines the capture
5253
+ /// form when its scope assigns the target (captureServesBranch and the
5254
+ /// exit-guard's assignsTarget check), so a capture live here never has
5255
+ /// an assignment to survive.
5256
+ ///
5257
+ /// The scan counts exactly the assignments tsc's CFA counts — killing a
5258
+ /// key tsc keeps strips a substitution the finally's reads were typed
5259
+ /// against and emits member access on a raw optional, invalid Zig. Two
5260
+ /// exclusions, both pinned against the checker provider:
5261
+ /// - code under a KEYWORD-LITERAL constant condition tsc treats as
5262
+ /// unreachable never counts (tscExcludedArm — the same judgment the
5263
+ /// branch-join layer applies): `if (false) ...`, the else of
5264
+ /// `if (true) ...`, a `while (false)` body, and the right side of
5265
+ /// `false && ...` / `true || ...` all keep the finally narrowed
5266
+ /// (probed). Only the bare keywords qualify — a `const NEVER = false`
5267
+ /// alias condition WIDENS under tsc (probed), and it still walks here;
5268
+ /// the same keyword-only judgment alwaysExits applies to constant-true
5269
+ /// loops. Anything else (do-while, non-literal conditions) stays on
5270
+ /// the conservative path-insensitive walk.
5271
+ /// - nested function/callback bodies never count (the throwsWithin skip
5272
+ /// idiom): tsc keeps the finally narrowed even when a callback DEFINED
5273
+ /// in the try assigns the target — called there or not (probed) — so
5274
+ /// counting those assignments would kill a narrow tsc typed the
5275
+ /// finally's reads with.
5276
+ /// Real conditional assignments (`if (flag) p = null`) still count: tsc
5277
+ /// widens for any reachable may-assign, whatever the path condition.
5278
+ private finallyEntryKills(stmt: ts.TryStatement, ctx: Ctx): Set<string> {
5279
+ const kills = new Set<string>();
5280
+ const visit = (n: ts.Node): void => {
5281
+ if (ts.isArrowFunction(n) || ts.isFunctionExpression(n) || ts.isFunctionDeclaration(n)) return;
5282
+ if (ts.isIfStatement(n)) {
5283
+ if (this.tscExcludedArm(n, n.thenStatement)) {
5284
+ if (n.elseStatement) visit(n.elseStatement);
5285
+ return;
5286
+ }
5287
+ if (n.elseStatement && this.tscExcludedArm(n, n.elseStatement)) {
5288
+ visit(n.thenStatement);
5289
+ return;
5290
+ }
5291
+ }
5292
+ if (ts.isWhileStatement(n) && this.tscExcludedArm(n, n.statement)) return;
5293
+ if (ts.isForStatement(n) && this.tscExcludedArm(n, n.statement)) {
5294
+ // `for (<init>; false; <inc>) <body>`: the initializer still runs
5295
+ // once (tsc counts its assignments); the bare-false condition holds
5296
+ // nothing to count; the body and the incrementor are excluded — the
5297
+ // incrementor runs only after a body iteration that never happens.
5298
+ if (n.initializer) visit(n.initializer);
5299
+ return;
5300
+ }
5301
+ if (ts.isBinaryExpression(n)) {
5302
+ const op = n.operatorToken.kind;
5303
+ if (op === ts.SyntaxKind.AmpersandAmpersandToken && n.left.kind === ts.SyntaxKind.FalseKeyword) return;
5304
+ if (op === ts.SyntaxKind.BarBarToken && n.left.kind === ts.SyntaxKind.TrueKeyword) return;
5305
+ }
5306
+ if (ts.isBinaryExpression(n) && n.operatorToken.kind === ts.SyntaxKind.EqualsToken) {
5307
+ const key = this.narrowKey(n.left);
5308
+ if (key !== null) {
5309
+ const subst = ctx.memberSubst.get(key);
5310
+ const empties = this.tast.emptiesOf(n.right);
5311
+ const mayBeEmpty = empties.null || empties.undefined;
5312
+ const survives = subst !== undefined && subst.endsWith(".?") && !mayBeEmpty;
5313
+ if (!survives && (subst !== undefined || mayBeEmpty)) kills.add(key);
5314
+ }
5315
+ }
5316
+ ts.forEachChild(n, visit);
5317
+ };
5318
+ visit(stmt.tryBlock);
5319
+ if (stmt.catchClause) visit(stmt.catchClause.block);
5320
+ return kills;
5321
+ }
5322
+
3308
5323
  private emitTryCore(stmt: ts.TryStatement, ctx: Ctx): void {
3309
5324
  const cc = stmt.catchClause;
3310
5325
  if (!cc) {
3311
- // try/finally: throws propagate past this construct (the defer runs).
5326
+ // try/finally: throws propagate past this construct (the defer runs
5327
+ // first) to ctx's handler — the caller when ctx.tryLabel is null, an
5328
+ // enclosing catch otherwise. No catch fallthrough is added HERE, so
5329
+ // kill dropping inherits ctx.tryLabel/ctx.catchResumes unchanged:
5330
+ // the inherited flags already answer for whichever handler a throw
5331
+ // reaches, and a body ending in `return` may still drop its kills
5332
+ // when nothing up the chain can resume past a merge.
3312
5333
  this.push(ctx, `{`);
3313
5334
  const sub = this.nestedCtx(ctx);
3314
5335
  this.emitBlockStatements(stmt.tryBlock.statements, sub);
@@ -3335,10 +5356,46 @@ export class Emitter {
3335
5356
  this.push(outer, `${body}: {`);
3336
5357
  const inner = this.nestedCtx(outer);
3337
5358
  inner.tryLabel = body;
5359
+ // The body's kills may only drop when no exception path can resume
5360
+ // past this try: a catch that falls through re-enters the merge
5361
+ // carrying whatever a mid-body throw killed. A catch closes every such
5362
+ // path only when EVERY route out of it leaves the function — asked
5363
+ // against ctx, not the body label, because the catch's own throws
5364
+ // break to ctx's enclosing handler — and then it also closes paths
5365
+ // from any try nested in this body, so the flag is overwritten rather
5366
+ // than or-ed with the inherited value.
5367
+ inner.catchResumes = !this.allRoutesLeaveFunction(cc.block.statements, {
5368
+ returnLeaves: ctx.retLabel === null,
5369
+ throwResumes: ctx.catchResumes === true,
5370
+ });
5371
+ // Fresh pending set for THIS try: kills routed here rode throw edges
5372
+ // into this catch (popNarrowKillFrame's route form) and apply at
5373
+ // the post-try merge below. A nested try's body re-derives its own set,
5374
+ // so kills always land at the same destination the throw route resolves
5375
+ // to; the catch block itself inherits the ENCLOSING set through ctx
5376
+ // (its throws escape outward, never back into this try).
5377
+ const pendingKills = new Set<string>();
5378
+ inner.pendingCatchKills = pendingKills;
3338
5379
  this.emitBlockStatements(stmt.tryBlock.statements, inner);
3339
5380
  if (done !== null) this.push(inner, `break :${done};`);
3340
5381
  outer.lines.push(...inner.lines);
3341
5382
  this.push(outer, `}`);
5383
+ // Exception-kills handoff: kills travel the same edges control does,
5384
+ // and the routes that fed this set are throws that land in THIS catch
5385
+ // — so they enter as the catch's INPUT state (tsc types the catch from
5386
+ // the state at the throw points: a narrowing an always-throwing arm
5387
+ // killed before throwing is dead inside the catch) and then follow the
5388
+ // catch's own routes out, via the catch list's kill-frame routing. A
5389
+ // catch that falls through carries them to the post-try continuation;
5390
+ // a catch that breaks/continues stages them at that edge's landing
5391
+ // point; a catch whose every route leaves the function drops them —
5392
+ // the post-try continuation is then reached only by clean paths, where
5393
+ // tsc keeps the narrow, so applying them there unconditionally would
5394
+ // poison the normal fallthrough. The body's normal-exit kills already
5395
+ // applied at the body's own merge just above, so the catch also sees
5396
+ // those (tsc-correct too: a mid-body throw can follow any fall-through
5397
+ // assignment). They never touch the intra-try flow already emitted
5398
+ // above.
3342
5399
  const catchCtx: Ctx = { ...outer, lines: [] };
3343
5400
  if (cc.variableDeclaration && ts.isIdentifier(cc.variableDeclaration.name)) {
3344
5401
  if (this.identifierUsed(cc.block, cc.variableDeclaration)) {
@@ -3347,7 +5404,7 @@ export class Emitter {
3347
5404
  this.push(catchCtx, `const ${ename} = thrown_payload;`);
3348
5405
  }
3349
5406
  }
3350
- this.emitBlockStatements(cc.block.statements, catchCtx);
5407
+ this.emitBlockStatements(cc.block.statements, catchCtx, undefined, pendingKills);
3351
5408
  outer.lines.push(...catchCtx.lines);
3352
5409
  ctx.lines.push(...outer.lines);
3353
5410
  this.push(ctx, `}`);
@@ -3394,18 +5451,32 @@ export class Emitter {
3394
5451
  const cond = this.emitExpr(stmt.expression, ctx, { k: "bool" }).code;
3395
5452
  if (ctx.lines.length !== before) this.fail(stmt, "while-condition requiring lowered statements");
3396
5453
  const body = ts.isBlock(stmt.statement) ? stmt.statement.statements : [stmt.statement];
5454
+ // A `while (false)` body is statically unreachable to tsc's CFA
5455
+ // (tscExcludedArm), so its kills never reach the post-loop state —
5456
+ // merging them would strip a narrow tsc typed the fall-through reads
5457
+ // with. The body still emits; only the flow bookkeeping skips.
5458
+ const deadBody = this.tscExcludedArm(stmt, stmt.statement);
3397
5459
  if (label === null && body.length === 1 && this.isSimpleAssignment(body[0])) {
5460
+ // Probe in a flow scope (see childCtx): taken, the assignment's
5461
+ // kills apply below exactly as a merge would; discarded, the full
5462
+ // body re-emission repeats them.
5463
+ const bodyJoin = new Set<string>();
3398
5464
  const sub = this.childCtx(ctx);
3399
5465
  sub.indent = 0;
3400
- this.emitStatement(body[0], sub);
5466
+ this.withNarrowScope(ctx, "merge", () => this.emitStatement(body[0], sub), bodyJoin);
3401
5467
  if (sub.lines.length === 1) {
3402
5468
  this.push(ctx, `while (${cond}) ${sub.lines[0].trim()}`);
5469
+ this.applyJoinedNarrowKills(ctx, deadBody ? new Set() : bodyJoin);
3403
5470
  return;
3404
5471
  }
3405
5472
  }
3406
5473
  this.push(ctx, `${head} (${cond}) {`);
3407
5474
  const sub = this.nestedCtx(ctx);
3408
- this.emitBlockStatements(body, sub);
5475
+ if (deadBody) {
5476
+ this.withNarrowScope(ctx, "drop", () => this.emitBlockStatements(body, sub));
5477
+ } else {
5478
+ this.emitBlockStatements(body, sub);
5479
+ }
3409
5480
  ctx.lines.push(...sub.lines);
3410
5481
  this.push(ctx, `}`);
3411
5482
  }
@@ -3422,15 +5493,26 @@ export class Emitter {
3422
5493
  if (!this.bindsContinue(stmt.statement, label)) {
3423
5494
  this.push(ctx, `${head} (true) {`);
3424
5495
  const sub = this.nestedCtx(ctx);
3425
- this.emitBlockStatements(body, sub);
5496
+ // tsc evaluates the do-while condition AFTER the body and carries the
5497
+ // body's flow state into it — a terminal guard in the body narrows
5498
+ // the trailing test. The body and the lowered `if (!(cond)) break;`
5499
+ // therefore emit inside ONE narrowing scope (the `trailing` hook),
5500
+ // restored only at the loop boundary: a restore between them would
5501
+ // strip the narrow before the read it covers. Iteration-entry state
5502
+ // is not at risk — the test is the last text in the loop body, so
5503
+ // nothing emits under its narrows past the back edge, and the
5504
+ // restore still runs before the post-loop continuation.
3426
5505
  // A body that always exits never reaches the test in JS either; the
3427
5506
  // 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
- }
5507
+ const trailing = this.alwaysExits(stmt.statement)
5508
+ ? undefined
5509
+ : (): void => {
5510
+ const before = sub.lines.length;
5511
+ const cond = this.emitExpr(stmt.expression, sub, { k: "bool" }).code;
5512
+ if (sub.lines.length !== before) this.fail(stmt, "do-while condition requiring lowered statements");
5513
+ this.push(sub, `if (!(${cond})) break;`);
5514
+ };
5515
+ this.emitBlockStatements(body, sub, undefined, undefined, trailing);
3434
5516
  ctx.lines.push(...sub.lines);
3435
5517
  this.push(ctx, `}`);
3436
5518
  return;
@@ -3450,7 +5532,17 @@ export class Emitter {
3450
5532
 
3451
5533
  /// Whether any `break`/`continue` under `body` names this label (JS
3452
5534
  /// allows an unreferenced label; Zig rejects one, so it must drop).
3453
- /// Duplicate nested labels cannot shadow — tsc rejects them.
5535
+ /// Duplicate nested labels cannot shadow on one nesting path — tsc
5536
+ /// rejects them — but labels are FUNCTION-scoped: a nested function may
5537
+ /// legally reuse the name for a label of its own, and its `break`/
5538
+ /// `continue` binds that inner label, never this one. The walk stops at
5539
+ /// function boundaries (the breaksToLabel rule), or a reuse would keep a
5540
+ /// Zig label emitted that nothing in THIS function consumes — an
5541
+ /// unused-label error.
5542
+ /// An EMISSION-SHAPE walk: tsc-excluded arms deliberately COUNT here
5543
+ /// (contrast the flow walks — see tscExcludedArm). A dead `break outer`
5544
+ /// still emits as `break :outer`, and Zig's unused-label check is
5545
+ /// syntactic, so the label must stay emitted and stays used.
3454
5546
  private labelReferenced(body: ts.Node, name: string): boolean {
3455
5547
  let found = false;
3456
5548
  const visit = (n: ts.Node): void => {
@@ -3459,6 +5551,7 @@ export class Emitter {
3459
5551
  found = true;
3460
5552
  return;
3461
5553
  }
5554
+ if (ts.isFunctionLike(n)) return;
3462
5555
  ts.forEachChild(n, visit);
3463
5556
  };
3464
5557
  visit(body);
@@ -3467,7 +5560,15 @@ export class Emitter {
3467
5560
 
3468
5561
  /// Whether a loop body contains a `continue` that binds to THIS loop: an
3469
5562
  /// unlabeled one outside any nested loop, or a labeled one naming this
3470
- /// loop's label.
5563
+ /// loop's label. Labels are function-scoped, so the walk stops at
5564
+ /// function boundaries (the breaksToLabel rule): a nested function may
5565
+ /// legally reuse the label name for a labeled loop of its own, and its
5566
+ /// `continue` binds that inner loop, never this one.
5567
+ /// An EMISSION-SHAPE walk: tsc-excluded arms deliberately COUNT here
5568
+ /// (contrast the flow walks — see tscExcludedArm). Both consumers pick
5569
+ /// the do-while lowering form, and a dead `continue` still EMITS — only
5570
+ /// the first-pass-flag form gives that text a spelling whose jump
5571
+ /// semantics match JS.
3471
5572
  private bindsContinue(body: ts.Node, label: string | null): boolean {
3472
5573
  let found = false;
3473
5574
  const visit = (n: ts.Node, insideNested: boolean): void => {
@@ -3480,6 +5581,7 @@ export class Emitter {
3480
5581
  }
3481
5582
  return;
3482
5583
  }
5584
+ if (ts.isFunctionLike(n)) return;
3483
5585
  const nested =
3484
5586
  insideNested ||
3485
5587
  ts.isWhileStatement(n) ||
@@ -3487,14 +5589,117 @@ export class Emitter {
3487
5589
  ts.isForStatement(n) ||
3488
5590
  ts.isForOfStatement(n) ||
3489
5591
  ts.isForInStatement(n);
3490
- // Callbacks cannot `continue` an outer loop (tsc rejects it), so
3491
- // function boundaries need no special casing here.
3492
5592
  ts.forEachChild(n, (c) => visit(c, nested));
3493
5593
  };
3494
5594
  visit(body, false);
3495
5595
  return found;
3496
5596
  }
3497
5597
 
5598
+ /// Whether an unlabeled `break` statement binds a `switch` rather than a
5599
+ /// loop: the nearest enclosing loop-or-switch, walking out of the break,
5600
+ /// is a switch. (tsc already rejects a break with neither.)
5601
+ private breakBindsEnclosingSwitch(stmt: ts.BreakStatement): boolean {
5602
+ let cur: ts.Node | undefined = stmt.parent;
5603
+ while (cur) {
5604
+ if (
5605
+ ts.isWhileStatement(cur) ||
5606
+ ts.isDoStatement(cur) ||
5607
+ ts.isForStatement(cur) ||
5608
+ ts.isForOfStatement(cur) ||
5609
+ ts.isForInStatement(cur) ||
5610
+ ts.isFunctionLike(cur)
5611
+ ) {
5612
+ return false;
5613
+ }
5614
+ if (ts.isSwitchStatement(cur)) return true;
5615
+ cur = cur.parent;
5616
+ }
5617
+ return false;
5618
+ }
5619
+
5620
+ /// Whether a `break` inside this switch's clauses (or this loop's body)
5621
+ /// binds the switch/loop itself: an unlabeled one outside any nested
5622
+ /// loop or switch, or a labeled one naming a label wrapped directly
5623
+ /// around this statement. Such a break resumes right AFTER the
5624
+ /// statement — the switch/loop falls through.
5625
+ /// Labels are function-scoped in JS, so the walk stops at function
5626
+ /// boundaries (the breaksToLabel rule): a nested helper may legally
5627
+ /// reuse a wrapping label's name for a label of its own, and its `break`
5628
+ /// binds the helper's label, never this construct — counting it read a
5629
+ /// constant-true loop as fallible and merged branch kills tsc keeps.
5630
+ /// This is a FLOW-SEMANTICS walk (it feeds alwaysExits' terminality,
5631
+ /// which mirrors tsc's CFA): a break under a tsc-excluded arm is not an
5632
+ /// edge the CFA can take, so it never counts (tscExcludedArm — Zig's
5633
+ /// comptime-false folding reads the emitted text the same way).
5634
+ private bindsBreak(
5635
+ stmt: ts.SwitchStatement | ts.WhileStatement | ts.DoStatement | ts.ForStatement,
5636
+ ): boolean {
5637
+ const wrappingLabels = new Set<string>();
5638
+ let p: ts.Node | undefined = stmt.parent;
5639
+ while (p && ts.isLabeledStatement(p)) {
5640
+ wrappingLabels.add(p.label.text);
5641
+ p = p.parent;
5642
+ }
5643
+ let found = false;
5644
+ const visit = (n: ts.Node, insideNested: boolean): void => {
5645
+ if (found) return;
5646
+ if (ts.isBreakStatement(n)) {
5647
+ if (n.label) {
5648
+ if (wrappingLabels.has(n.label.text)) found = true;
5649
+ } else if (!insideNested) {
5650
+ found = true;
5651
+ }
5652
+ return;
5653
+ }
5654
+ if (ts.isFunctionLike(n)) return;
5655
+ const nested =
5656
+ insideNested ||
5657
+ ts.isWhileStatement(n) ||
5658
+ ts.isDoStatement(n) ||
5659
+ ts.isForStatement(n) ||
5660
+ ts.isForOfStatement(n) ||
5661
+ ts.isForInStatement(n) ||
5662
+ ts.isSwitchStatement(n);
5663
+ ts.forEachChild(n, (c) => {
5664
+ if (!this.tscExcludedArm(n, c)) visit(c, nested);
5665
+ });
5666
+ };
5667
+ if (ts.isSwitchStatement(stmt)) {
5668
+ ts.forEachChild(stmt.caseBlock, (c) => visit(c, false));
5669
+ } else {
5670
+ // Loop heads hold no break (tsc rejects one there); only the body
5671
+ // can bind this loop.
5672
+ visit(stmt.statement, false);
5673
+ }
5674
+ return found;
5675
+ }
5676
+
5677
+ /// Whether any `break` naming `label` sits inside `node`. Function
5678
+ /// boundaries stop the walk: a labeled break cannot cross one (tsc
5679
+ /// rejects it), and a nested function may legally reuse the label name
5680
+ /// for a labeled statement of its own. tsc rejects duplicate labels on
5681
+ /// the same nesting path, so no inner rebinding can shadow `label`.
5682
+ /// A FLOW-SEMANTICS walk like bindsBreak (it feeds alwaysExits' labeled
5683
+ /// terminality): a labeled break under a tsc-excluded arm never counts
5684
+ /// (tscExcludedArm). Contrast labelReferenced, the EMISSION-SHAPE twin
5685
+ /// that must keep counting.
5686
+ private breaksToLabel(node: ts.Node, label: string): boolean {
5687
+ let found = false;
5688
+ const visit = (n: ts.Node): void => {
5689
+ if (found) return;
5690
+ if (ts.isBreakStatement(n)) {
5691
+ if (n.label !== undefined && n.label.text === label) found = true;
5692
+ return;
5693
+ }
5694
+ if (ts.isFunctionLike(n)) return;
5695
+ ts.forEachChild(n, (c) => {
5696
+ if (!this.tscExcludedArm(n, c)) visit(c);
5697
+ });
5698
+ };
5699
+ visit(node);
5700
+ return found;
5701
+ }
5702
+
3498
5703
  private isSimpleAssignment(stmt: ts.Statement): boolean {
3499
5704
  if (!ts.isExpressionStatement(stmt)) return false;
3500
5705
  const e = stmt.expression;
@@ -3596,8 +5801,11 @@ export class Emitter {
3596
5801
  this.push(ctx, `${varKw} ${name} = ${seed.code};`);
3597
5802
  this.push(ctx, `var ${lenVar}: usize = ${name}.len;`);
3598
5803
  }
3599
- ctx.memberSubst.set(decl.name.text, `${name}[0..${lenVar}]`);
3600
- ctx.memberSubst.set(`${decl.name.text}.length`, `@as(i64, @intCast(${lenVar}))`);
5804
+ const declKey = this.narrowKey(decl.name);
5805
+ if (declKey !== null) {
5806
+ ctx.memberSubst.set(declKey, `${name}[0..${lenVar}]`);
5807
+ ctx.memberSubst.set(`${declKey}.length`, `@as(i64, @intCast(${lenVar}))`);
5808
+ }
3601
5809
  return;
3602
5810
  }
3603
5811
  if (sliceT.k === "slice" && ts.isArrayLiteralExpression(init) && init.elements.length === 0) {
@@ -3625,7 +5833,10 @@ export class Emitter {
3625
5833
  if (v.code === name) return; // lowered directly into a named temp
3626
5834
  const annotation = this.varAnnotation(decl, t, reassigned, ctx);
3627
5835
  this.push(ctx, `${kw} ${name}${annotation} = ${v.code};`);
3628
- if (v.filterLen) ctx.memberSubst.set(`${decl.name.text}.length`, `@as(i64, @intCast(${v.filterLen}))`);
5836
+ if (v.filterLen) {
5837
+ const declKey = this.narrowKey(decl.name);
5838
+ if (declKey !== null) ctx.memberSubst.set(`${declKey}.length`, `@as(i64, @intCast(${v.filterLen}))`);
5839
+ }
3629
5840
  }
3630
5841
 
3631
5842
  /// R6b: `const { total, done: doneCount } = stats;` — record-field
@@ -3765,10 +5976,19 @@ export class Emitter {
3765
5976
  const exit = this.singleExitText(stmt.thenStatement, ctx);
3766
5977
  if (exit !== null) {
3767
5978
  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;
5979
+ } else {
5980
+ // Multi-statement exits (a throw is always two emitted statements)
5981
+ // keep the guard's narrowing through the block form.
5982
+ this.push(ctx, `if (${base} != .${zigId(tag)}) {`);
5983
+ const sub = this.nestedCtx(ctx);
5984
+ const exitStmts = ts.isBlock(stmt.thenStatement) ? stmt.thenStatement.statements : [stmt.thenStatement];
5985
+ this.emitBlockStatements(exitStmts, sub);
5986
+ ctx.lines.push(...sub.lines);
5987
+ this.push(ctx, `}`);
3771
5988
  }
5989
+ const t = this.zTypeOfExpr(cond.left.expression, ctx);
5990
+ if (t.k === "union") this.narrowUnion(cond.left.expression, t.name, tag, ctx);
5991
+ return;
3772
5992
  }
3773
5993
 
3774
5994
  // R7: `if (x === null) <exit>` -> `const v = x orelse <exit>;` for
@@ -3784,19 +6004,56 @@ export class Emitter {
3784
6004
  const t = this.zTypeOfExpr(exitTest.target, ctx);
3785
6005
  if (t.k === "optional") {
3786
6006
  const exit = this.singleExitText(stmt.thenStatement, ctx);
3787
- if (exit !== null) {
6007
+ // A guard whose narrowed value the rest of the scope never reads
6008
+ // must not bind a capture — an unused Zig const is a compile
6009
+ // error — so it stays a plain null test (one-statement exits
6010
+ // here; multi-statement unread exits ride the generic arm below).
6011
+ if (!this.followingReadsTarget(stmt, exitTest.target)) {
6012
+ if (exit !== null) {
6013
+ this.requireFaithfulEmptyTest(exitTest.target, exitTest.flavor, cond);
6014
+ const prop = this.emitExpr(exitTest.target, ctx).code;
6015
+ this.push(ctx, `if (${prop} == null) ${exit}`);
6016
+ return;
6017
+ }
6018
+ } else {
3788
6019
  this.requireFaithfulEmptyTest(exitTest.target, exitTest.flavor, cond);
3789
6020
  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}`);
6021
+ // A reassigned target cannot narrow through a capture (the capture
6022
+ // goes stale at the assignment): keep the plain null test and
6023
+ // install the `.?` spelling, whose reads see the live variable and
6024
+ // which the assignment path keeps alive across provably non-null
6025
+ // writes.
6026
+ if (this.assignsTarget([...this.followingStatementsOf(stmt)], exitTest.target)) {
6027
+ if (exit !== null) {
6028
+ this.push(ctx, `if (${prop} == null) ${exit}`);
6029
+ } else {
6030
+ this.push(ctx, `if (${prop} == null) {`);
6031
+ const sub = this.nestedCtx(ctx);
6032
+ const exitStmts = ts.isBlock(stmt.thenStatement) ? stmt.thenStatement.statements : [stmt.thenStatement];
6033
+ this.emitBlockStatements(exitStmts, sub);
6034
+ ctx.lines.push(...sub.lines);
6035
+ this.push(ctx, `}`);
6036
+ }
6037
+ const exitKey = this.narrowKey(exitTest.target);
6038
+ if (exitKey !== null) ctx.memberSubst.set(exitKey, `${prop}.?`);
3795
6039
  return;
3796
6040
  }
3797
6041
  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);
6042
+ if (exit !== null) {
6043
+ this.push(ctx, `const ${name} = ${prop} orelse ${exit}`);
6044
+ } else {
6045
+ // Multi-statement exits (a throw is always two emitted
6046
+ // statements) take the block form; the block never falls
6047
+ // through, so Zig types it noreturn and the unwrap holds.
6048
+ this.push(ctx, `const ${name} = ${prop} orelse {`);
6049
+ const sub = this.nestedCtx(ctx);
6050
+ const exitStmts = ts.isBlock(stmt.thenStatement) ? stmt.thenStatement.statements : [stmt.thenStatement];
6051
+ this.emitBlockStatements(exitStmts, sub);
6052
+ ctx.lines.push(...sub.lines);
6053
+ this.push(ctx, `};`);
6054
+ }
6055
+ const exitKey = this.narrowKey(exitTest.target);
6056
+ if (exitKey !== null) ctx.memberSubst.set(exitKey, name);
3800
6057
  return;
3801
6058
  }
3802
6059
  }
@@ -3813,30 +6070,59 @@ export class Emitter {
3813
6070
  this.branchReadsTarget(stmt.elseStatement, exitTest.target)
3814
6071
  ) {
3815
6072
  const t = this.zTypeOfExpr(exitTest.target, ctx);
3816
- if (t.k === "optional") {
6073
+ const key = this.narrowKey(exitTest.target);
6074
+ if (t.k === "optional" && key !== null) {
3817
6075
  this.requireFaithfulEmptyTest(exitTest.target, exitTest.flavor, cond);
3818
- const key = normalize(exitTest.target);
3819
6076
  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);
6077
+ const join = new Set<string>();
3825
6078
  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
6079
  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, `}`);
6080
+ // A branch that reassigns the target before any read could
6081
+ // consume a capture takes the plain-test `.?` spelling instead
6082
+ // (see captureServesBranch) — a capture would bind unused or go
6083
+ // stale behind a join.
6084
+ if (this.captureServesBranch(stmt.elseStatement, exitTest.target)) {
6085
+ const name = this.freshName(ctx, this.narrowHint(exitTest.target));
6086
+ this.push(ctx, `if (${prop}) |${name}| {`);
6087
+ const saved = ctx.memberSubst.get(key);
6088
+ ctx.memberSubst.set(key, name);
6089
+ const sub = this.nestedCtx(ctx);
6090
+ this.emitBlockStatements(hitBody, sub, join);
6091
+ ctx.lines.push(...sub.lines);
6092
+ ctx.memberSubst.delete(key);
6093
+ if (saved !== undefined) ctx.memberSubst.set(key, saved);
6094
+ this.push(ctx, `} else {`);
6095
+ const esub = this.nestedCtx(ctx);
6096
+ this.emitBlockStatements(missBody, esub, join);
6097
+ ctx.lines.push(...esub.lines);
6098
+ this.push(ctx, `}`);
6099
+ } else {
6100
+ this.push(ctx, `if (${prop} == null) {`);
6101
+ const esub = this.nestedCtx(ctx);
6102
+ this.emitBlockStatements(missBody, esub, join);
6103
+ ctx.lines.push(...esub.lines);
6104
+ this.push(ctx, `} else {`);
6105
+ const saved = ctx.memberSubst.get(key);
6106
+ ctx.memberSubst.set(key, `${prop}.?`);
6107
+ const sub = this.nestedCtx(ctx);
6108
+ this.emitBlockStatements(hitBody, sub, join);
6109
+ ctx.lines.push(...sub.lines);
6110
+ ctx.memberSubst.delete(key);
6111
+ if (saved !== undefined) ctx.memberSubst.set(key, saved);
6112
+ this.push(ctx, `}`);
6113
+ }
6114
+ this.applyJoinedNarrowKills(ctx, join);
3836
6115
  // A miss branch that always exits narrows everything AFTER the if
3837
6116
  // too (TS's control-flow narrowing): reads there unwrap through the
3838
6117
  // safety-checked `.?` — provably non-null, the miss path returned.
3839
- if (this.alwaysExits(stmt.thenStatement) && this.followingReadsTarget(stmt, exitTest.target)) {
6118
+ // UNLESS the surviving arm killed the target: tsc's post-if state
6119
+ // is the guard-implied narrow MINUS the joined kills, so a killed
6120
+ // key stays dead and the code after re-checks instead.
6121
+ if (
6122
+ !join.has(key) &&
6123
+ this.alwaysExits(stmt.thenStatement) &&
6124
+ this.followingReadsTarget(stmt, exitTest.target)
6125
+ ) {
3840
6126
  ctx.memberSubst.set(key, `${prop}.?`);
3841
6127
  }
3842
6128
  return;
@@ -3853,17 +6139,27 @@ export class Emitter {
3853
6139
  this.branchReadsTarget(stmt.thenStatement, presentTest.target)
3854
6140
  ) {
3855
6141
  const t = this.zTypeOfExpr(presentTest.target, ctx);
3856
- if (t.k === "optional") {
6142
+ const key = this.narrowKey(presentTest.target);
6143
+ if (t.k === "optional" && key !== null) {
3857
6144
  this.requireFaithfulEmptyTest(presentTest.target, presentTest.flavor, cond);
3858
- const key = normalize(presentTest.target);
3859
6145
  const prop = this.emitExpr(presentTest.target, ctx).code;
3860
- const name = this.freshName(ctx, this.narrowHint(presentTest.target));
6146
+ // A branch that reassigns the target before any read could
6147
+ // consume a capture takes the plain-test `.?` spelling instead
6148
+ // (see captureServesBranch) — a capture would bind unused or go
6149
+ // stale behind a join; `.?` reads always see the live slot.
6150
+ const liveCapture = this.captureServesBranch(stmt.thenStatement, presentTest.target);
6151
+ const name = liveCapture ? this.freshName(ctx, this.narrowHint(presentTest.target)) : `${prop}.?`;
3861
6152
  const single = unwrapSingle(stmt.thenStatement);
3862
- if (!stmt.elseStatement && single && ts.isReturnStatement(single)) {
6153
+ if (liveCapture && !stmt.elseStatement && single && ts.isReturnStatement(single)) {
3863
6154
  const saved = ctx.memberSubst.get(key);
3864
6155
  ctx.memberSubst.set(key, name);
6156
+ // Probe in a flow scope (see childCtx). Its kills discard both
6157
+ // ways: a lines-free probe processed no statements (nothing can
6158
+ // kill without lowering lines), and the discarded case re-emits
6159
+ // the branch below under the block path's own scope.
3865
6160
  const sub = this.childCtx(ctx);
3866
- const v = single.expression ? this.emitReturn(single.expression, sub) : null;
6161
+ const v = this.withNarrowScope(ctx, "merge", () =>
6162
+ single.expression ? this.emitReturn(single.expression, sub) : null, new Set());
3867
6163
  ctx.memberSubst.delete(key);
3868
6164
  if (saved !== undefined) ctx.memberSubst.set(key, saved);
3869
6165
  if (sub.lines.length === 0 && v) {
@@ -3871,12 +6167,13 @@ export class Emitter {
3871
6167
  return;
3872
6168
  }
3873
6169
  }
3874
- this.push(ctx, `if (${prop}) |${name}| {`);
6170
+ const join = new Set<string>();
6171
+ this.push(ctx, liveCapture ? `if (${prop}) |${name}| {` : `if (${prop} != null) {`);
3875
6172
  const saved = ctx.memberSubst.get(key);
3876
6173
  ctx.memberSubst.set(key, name);
3877
6174
  const sub = this.nestedCtx(ctx);
3878
6175
  const thenBody = ts.isBlock(stmt.thenStatement) ? stmt.thenStatement.statements : [stmt.thenStatement];
3879
- this.emitBlockStatements(thenBody, sub);
6176
+ this.emitBlockStatements(thenBody, sub, join);
3880
6177
  ctx.lines.push(...sub.lines);
3881
6178
  ctx.memberSubst.delete(key);
3882
6179
  if (saved !== undefined) ctx.memberSubst.set(key, saved);
@@ -3884,10 +6181,24 @@ export class Emitter {
3884
6181
  this.push(ctx, `} else {`);
3885
6182
  const esub = this.nestedCtx(ctx);
3886
6183
  const elseBody = ts.isBlock(stmt.elseStatement) ? stmt.elseStatement.statements : [stmt.elseStatement];
3887
- this.emitBlockStatements(elseBody, esub);
6184
+ this.emitBlockStatements(elseBody, esub, join);
3888
6185
  ctx.lines.push(...esub.lines);
3889
6186
  }
3890
6187
  this.push(ctx, `}`);
6188
+ this.applyJoinedNarrowKills(ctx, join);
6189
+ // An else branch that always exits narrows everything AFTER the if
6190
+ // too (the mirror of the R7-dual rule above): only the hit path
6191
+ // falls through, so reads there unwrap via the safety-checked `.?`
6192
+ // — unless that hit path killed the target (post-if state is the
6193
+ // narrow minus the joined kills; a killed key re-checks instead).
6194
+ if (
6195
+ !join.has(key) &&
6196
+ stmt.elseStatement &&
6197
+ this.alwaysExits(stmt.elseStatement) &&
6198
+ this.followingReadsTarget(stmt, presentTest.target)
6199
+ ) {
6200
+ ctx.memberSubst.set(key, `${prop}.?`);
6201
+ }
3891
6202
  return;
3892
6203
  }
3893
6204
  }
@@ -3909,20 +6220,31 @@ export class Emitter {
3909
6220
  const thenStmts = ts.isBlock(stmt.thenStatement) ? stmt.thenStatement.statements : [stmt.thenStatement];
3910
6221
  // Single-return then-branch without else stays on one line when short.
3911
6222
  if (!stmt.elseStatement && thenStmts.length === 1 && ts.isReturnStatement(thenStmts[0])) {
6223
+ // Probe in a flow scope (see childCtx). Its kills discard both ways:
6224
+ // a lines-free probe processed no statements, and the discarded case
6225
+ // re-emits the branch below under the block path's own scope.
3912
6226
  const sub = this.childCtx(ctx);
3913
6227
  const r = thenStmts[0];
3914
- const v = this.withKindNarrow(posGuard, ctx, () =>
6228
+ const v = this.withNarrowScope(ctx, "merge", () => this.withKindNarrow(posGuard, ctx, () =>
3915
6229
  r.expression ? this.emitReturn(r.expression, sub) : null,
3916
- );
6230
+ ), new Set());
3917
6231
  const text = this.returnText(ctx, v, r);
3918
6232
  if (sub.lines.length === 0 && condText.length + text.length <= 80) {
3919
6233
  this.push(ctx, `if (${condText}) ${text}`);
3920
6234
  return;
3921
6235
  }
3922
6236
  }
6237
+ const join = new Set<string>();
6238
+ // A tsc-unreachable arm (bare keyword-literal condition — see
6239
+ // tscExcludedArm) still emits, but contributes no kills to the join:
6240
+ // tsc's CFA excludes the arm, so a kill from it would strip a narrow
6241
+ // tsc typed the fall-through reads with (a raw optional read, invalid
6242
+ // Zig). Its kills feed a discarded set instead of the join.
6243
+ const discard = new Set<string>();
3923
6244
  this.push(ctx, `if (${condText}) {`);
3924
6245
  const sub = this.nestedCtx(ctx);
3925
- this.withKindNarrow(posGuard, ctx, () => this.emitBlockStatements(thenStmts, sub));
6246
+ const thenJoin = this.tscExcludedArm(stmt, stmt.thenStatement) ? discard : join;
6247
+ this.withKindNarrow(posGuard, ctx, () => this.emitBlockStatements(thenStmts, sub, thenJoin));
3926
6248
  ctx.lines.push(...sub.lines);
3927
6249
  if (stmt.elseStatement) {
3928
6250
  if (ts.isIfStatement(stmt.elseStatement)) {
@@ -3930,16 +6252,66 @@ export class Emitter {
3930
6252
  this.push(ctx, `} else ${""}`.trimEnd());
3931
6253
  // Rewrite: emit as `} else if (...) {` by recursing with a marker.
3932
6254
  ctx.lines.pop();
3933
- this.emitElseIf(stmt.elseStatement, ctx);
6255
+ this.emitElseIf(stmt.elseStatement, ctx, join);
6256
+ this.applyJoinedNarrowKills(ctx, join);
6257
+ // This exit path narrows like the common tail below: an exiting
6258
+ // empty-test arm at the HEAD of a chain still narrows everything
6259
+ // after the whole statement (the else-if arms ride the non-empty
6260
+ // path), and skipping it here left fall-through reads optional.
6261
+ this.applyPostIfNarrow(stmt, exitTest, presentTest, ctx, join);
3934
6262
  return;
3935
6263
  }
3936
6264
  this.push(ctx, `} else {`);
3937
6265
  const esub = this.nestedCtx(ctx);
3938
6266
  const elseStmts = ts.isBlock(stmt.elseStatement) ? stmt.elseStatement.statements : [stmt.elseStatement];
3939
- this.withKindNarrow(negGuard, ctx, () => this.emitBlockStatements(elseStmts, esub));
6267
+ const elseJoin = this.tscExcludedArm(stmt, stmt.elseStatement) ? discard : join;
6268
+ this.withKindNarrow(negGuard, ctx, () => this.emitBlockStatements(elseStmts, esub, elseJoin));
3940
6269
  ctx.lines.push(...esub.lines);
3941
6270
  }
3942
6271
  this.push(ctx, `}`);
6272
+ this.applyJoinedNarrowKills(ctx, join);
6273
+ this.applyPostIfNarrow(stmt, exitTest, presentTest, ctx, join);
6274
+ }
6275
+
6276
+ /// tsc narrows AFTER an if whose empty-testing arm always exits — only
6277
+ /// the non-empty path falls through. The tailored R7 paths in emitIf
6278
+ /// return for the shapes where an arm READS the target; these are the
6279
+ /// generic leftovers (the miss arm has an else — possibly a whole
6280
+ /// else-if chain — or no arm reads the target), so fall-through reads
6281
+ /// unwrap via the safety-checked `.?`. Every exit path from emitIf that
6282
+ /// finished emitting the statement must apply this — with the
6283
+ /// statement's just-joined kill set: tsc's post-if state is the
6284
+ /// guard-implied narrow MINUS the arms' kills, so a target a surviving
6285
+ /// arm killed stays dead (installing it anyway would resurrect the
6286
+ /// narrow the join buried, emitting a `.?` read or test against a slot
6287
+ /// that can be null again).
6288
+ private applyPostIfNarrow(
6289
+ stmt: ts.IfStatement,
6290
+ exitTest: { target: ts.Expression; flavor: "null" | "undefined" } | null,
6291
+ presentTest: { target: ts.Expression; flavor: "null" | "undefined" } | null,
6292
+ ctx: Ctx,
6293
+ join: ReadonlySet<string>,
6294
+ ): void {
6295
+ const postNarrow =
6296
+ (exitTest && this.alwaysExits(stmt.thenStatement) ? exitTest : null) ??
6297
+ (presentTest && stmt.elseStatement && this.alwaysExits(stmt.elseStatement) ? presentTest : null);
6298
+ if (
6299
+ postNarrow &&
6300
+ (ts.isPropertyAccessExpression(postNarrow.target) || ts.isIdentifier(postNarrow.target)) &&
6301
+ this.followingReadsTarget(stmt, postNarrow.target)
6302
+ ) {
6303
+ const key = this.narrowKey(postNarrow.target);
6304
+ if (key === null || join.has(key)) return;
6305
+ const t = this.zTypeOfExpr(postNarrow.target, ctx);
6306
+ const empties = this.tast.emptiesOf(postNarrow.target);
6307
+ // The unfaithful-empty spellings keep their R7c teaching on the
6308
+ // paths that emit tests; here the narrow just quietly declines.
6309
+ const faithful = postNarrow.flavor === "null" ? !empties.undefined : !empties.null;
6310
+ if (t.k === "optional" && faithful) {
6311
+ const code = this.emitExpr(postNarrow.target, ctx).code;
6312
+ ctx.memberSubst.set(key, `${code}.?`);
6313
+ }
6314
+ }
3943
6315
  }
3944
6316
 
3945
6317
  /// Capture-name hint for a narrowed optional target.
@@ -3949,50 +6321,143 @@ export class Emitter {
3949
6321
  return "opt";
3950
6322
  }
3951
6323
 
3952
- /// Whether a guarded branch reads its narrowed target — a Zig capture the
6324
+ /// Whether a guarded branch READS its narrowed target — a Zig capture the
3953
6325
  /// branch never uses would be an unused-capture error, so unread guards
3954
- /// keep the plain `!= null` comparison instead.
6326
+ /// keep the plain `!= null` comparison instead. A plain assignment's
6327
+ /// TARGET is not a read: the write goes to the raw slot, never the
6328
+ /// capture, so a write-only arm (a pure kill) must decline the capture
6329
+ /// form or the capture binds unused.
3955
6330
  private branchReadsTarget(branch: ts.Statement, target: ts.Expression): boolean {
3956
6331
  if (ts.isIdentifier(target)) {
3957
6332
  const decl = this.tast.declarationOf(target);
3958
- if (decl) return this.identifierUsed(branch, decl);
6333
+ if (decl) return this.identifierRead(branch, decl);
3959
6334
  }
3960
- return branch.getText().includes(target.getText());
6335
+ // Property chains compare by declaration-qualified key, never text —
6336
+ // a shadowed spelling in a nested callback is not a read (anyReadsKey).
6337
+ return this.anyReadsKey([branch], this.narrowKey(target));
6338
+ }
6339
+
6340
+ /// identifierUsed, minus references that are the bare TARGET of a plain
6341
+ /// `=` assignment (compound assignments and `++`/`--` read the slot and
6342
+ /// still count).
6343
+ private identifierRead(body: ts.Node, decl: ts.Node): boolean {
6344
+ let found = false;
6345
+ const visit = (n: ts.Node): void => {
6346
+ if (found) return;
6347
+ if (
6348
+ ts.isIdentifier(n) &&
6349
+ this.tast.declarationOf(n) === decl &&
6350
+ n.parent !== decl &&
6351
+ !(
6352
+ ts.isBinaryExpression(n.parent) &&
6353
+ n.parent.operatorToken.kind === ts.SyntaxKind.EqualsToken &&
6354
+ n.parent.left === n
6355
+ )
6356
+ ) {
6357
+ found = true;
6358
+ return;
6359
+ }
6360
+ ts.forEachChild(n, visit);
6361
+ };
6362
+ visit(body);
6363
+ return found;
3961
6364
  }
3962
6365
 
3963
6366
  /// Whether any statement AFTER an early-exit guard reads the guarded
3964
6367
  /// 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`.
6368
+ /// unread capture would be an unused Zig const, a compile error.
6369
+ /// Property chains compare by declaration-qualified key (anyReadsKey),
6370
+ /// which is inherently boundary-aware — `model.now` is a different key
6371
+ /// from `model.nowDurationMs`, and a shadowed spelling in a nested
6372
+ /// callback is a different declaration.
3968
6373
  private followingReadsTarget(stmt: ts.IfStatement, target: ts.Expression): boolean {
6374
+ const following: ts.Node[] = [...this.followingStatementsOf(stmt)];
6375
+ // Flow off the end of a do-while body continues INTO the trailing
6376
+ // test (tsc evaluates the condition after the body), and the lowered
6377
+ // `if (!(cond)) break;` emits inside the body's narrowing scope — a
6378
+ // condition read is a read the guard's capture serves.
6379
+ const trailingTest = this.trailingDoWhileTestOf(stmt);
6380
+ if (trailingTest !== null) following.push(trailingTest);
6381
+ if (following.length === 0) return false;
6382
+ if (ts.isIdentifier(target)) {
6383
+ const decl = this.tast.declarationOf(target);
6384
+ if (decl) return following.some((s) => this.identifierUsed(s, decl));
6385
+ }
6386
+ return this.anyReadsKey(following, this.narrowKey(target));
6387
+ }
6388
+
6389
+ /// The statements after `stmt` in its own list — the scope an early-exit
6390
+ /// guard's narrowing serves. A plain lexical block is no flow boundary
6391
+ /// (emitStatement flattens it), so the walk continues past it: a guard at
6392
+ /// the end of such a block narrows the statements after the BLOCK,
6393
+ /// transitively out through enclosing plain blocks.
6394
+ private followingStatementsOf(stmt: ts.Statement): readonly ts.Statement[] {
3969
6395
  const parent = stmt.parent;
3970
- let following: readonly ts.Statement[] = [];
3971
6396
  if (ts.isBlock(parent) || ts.isSourceFile(parent) || ts.isCaseClause(parent) || ts.isDefaultClause(parent)) {
3972
6397
  const statements = parent.statements;
3973
6398
  const at = statements.indexOf(stmt);
3974
- if (at >= 0) following = statements.slice(at + 1);
6399
+ if (at >= 0) {
6400
+ const rest = statements.slice(at + 1);
6401
+ if (ts.isBlock(parent) && isPlainLexicalBlock(parent)) {
6402
+ return [...rest, ...this.followingStatementsOf(parent)];
6403
+ }
6404
+ return rest;
6405
+ }
3975
6406
  }
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));
6407
+ return [];
6408
+ }
6409
+
6410
+ /// The do-while trailing test the flow after `stmt` runs into, when that
6411
+ /// test actually emits inside the body's narrowing scope — i.e. `stmt`
6412
+ /// sits in the body list (transitively through plain lexical blocks) of
6413
+ /// a do-while lowered to the `while (true)` + trailing-exit-test form.
6414
+ /// The first-pass-flag form (a body binding `continue`) hoists the test
6415
+ /// ahead of the body, where a body narrow's capture is out of scope, and
6416
+ /// an always-exiting body emits no test at all — both return null, so a
6417
+ /// guard read only by the condition binds no capture there (an unused
6418
+ /// Zig const is a compile error).
6419
+ private trailingDoWhileTestOf(stmt: ts.Statement): ts.Expression | null {
6420
+ let cur: ts.Statement = stmt;
6421
+ for (;;) {
6422
+ const parent: ts.Node = cur.parent;
6423
+ if (ts.isBlock(parent) && isPlainLexicalBlock(parent)) {
6424
+ cur = parent;
6425
+ continue;
6426
+ }
6427
+ const holder = ts.isBlock(parent) ? parent.parent : parent;
6428
+ if (!ts.isDoStatement(holder)) return null;
6429
+ // Mirror emitStatement's label derivation: the loop's Zig label
6430
+ // exists only when a labeled break/continue references it.
6431
+ const label =
6432
+ ts.isLabeledStatement(holder.parent) && this.labelReferenced(holder, holder.parent.label.text)
6433
+ ? loopLabel(holder.parent.label.text)
6434
+ : null;
6435
+ if (this.bindsContinue(holder.statement, label)) return null;
6436
+ if (this.alwaysExits(holder.statement)) return null;
6437
+ return holder.expression;
3980
6438
  }
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
6439
  }
3985
6440
 
3986
- private emitElseIf(stmt: ts.IfStatement, ctx: Ctx): void {
6441
+ /// Every arm of the chain — each else-if body and the final else — is a
6442
+ /// SIBLING of the head if's then arm: its merge-class kills collect into
6443
+ /// the chain-wide `join` the head applies after the whole statement, so
6444
+ /// no arm emits against a preceding arm's kills (they are alternatives,
6445
+ /// not a sequence).
6446
+ private emitElseIf(stmt: ts.IfStatement, ctx: Ctx, join: Set<string>): void {
3987
6447
  // A chained condition that needs lowered statements cannot sit between
3988
6448
  // `}` 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.
6449
+ // The probe works on a copied name set so it burns no real names, and
6450
+ // brackets in a flow scope (see childCtx) — both routes below re-emit
6451
+ // the condition for real.
3990
6452
  const probe: Ctx = { ...ctx, lines: [], used: new Set(ctx.used) };
3991
- this.emitExpr(stmt.expression, probe, { k: "bool" });
6453
+ this.withNarrowScope(ctx, "merge", () => this.emitExpr(stmt.expression, probe, { k: "bool" }), new Set());
3992
6454
  if (probe.lines.length > 0) {
3993
6455
  this.push(ctx, `} else {`);
3994
6456
  const inner = this.nestedCtx(ctx);
3995
- this.emitIf(stmt, inner);
6457
+ // The nested if is one arm of the enclosing chain: bracket it in a
6458
+ // flow scope so its narrows stay contained and its kills join with
6459
+ // its siblings' instead of applying mid-chain.
6460
+ this.withNarrowScope(ctx, "merge", () => this.emitIf(stmt, inner), join);
3996
6461
  ctx.lines.push(...inner.lines);
3997
6462
  this.push(ctx, `}`);
3998
6463
  return;
@@ -4001,17 +6466,19 @@ export class Emitter {
4001
6466
  this.push(ctx, `} else if (${condText}) {`);
4002
6467
  const sub = this.nestedCtx(ctx);
4003
6468
  const thenStmts = ts.isBlock(stmt.thenStatement) ? stmt.thenStatement.statements : [stmt.thenStatement];
4004
- this.emitBlockStatements(thenStmts, sub);
6469
+ // tsc-unreachable arms contribute no kills to the chain's join (see
6470
+ // emitIf's discard note; tscExcludedArm).
6471
+ this.emitBlockStatements(thenStmts, sub, this.tscExcludedArm(stmt, stmt.thenStatement) ? new Set() : join);
4005
6472
  ctx.lines.push(...sub.lines);
4006
6473
  if (stmt.elseStatement) {
4007
6474
  if (ts.isIfStatement(stmt.elseStatement)) {
4008
- this.emitElseIf(stmt.elseStatement, ctx);
6475
+ this.emitElseIf(stmt.elseStatement, ctx, join);
4009
6476
  return;
4010
6477
  }
4011
6478
  this.push(ctx, `} else {`);
4012
6479
  const esub = this.nestedCtx(ctx);
4013
6480
  const elseStmts = ts.isBlock(stmt.elseStatement) ? stmt.elseStatement.statements : [stmt.elseStatement];
4014
- this.emitBlockStatements(elseStmts, esub);
6481
+ this.emitBlockStatements(elseStmts, esub, this.tscExcludedArm(stmt, stmt.elseStatement) ? new Set() : join);
4015
6482
  ctx.lines.push(...esub.lines);
4016
6483
  }
4017
6484
  this.push(ctx, `}`);
@@ -4024,15 +6491,31 @@ export class Emitter {
4024
6491
  return text;
4025
6492
  }
4026
6493
 
6494
+ /// A guard's exit branch as ONE Zig statement (`return v;`, `break;`,
6495
+ /// `continue;`, labeled forms included), or null when it needs a block
6496
+ /// (multi-statement bodies; a throw always emits two statements).
4027
6497
  private singleExitText(stmt: ts.Statement, ctx: Ctx): string | null {
4028
6498
  const single = unwrapSingle(stmt);
4029
6499
  if (single && ts.isReturnStatement(single)) {
4030
6500
  if (!single.expression) return this.returnText(ctx, null, single);
6501
+ // Probe in a flow scope (see childCtx): a lines-free probe processed
6502
+ // no statements, so the discarded kill set is empty; a lines-bearing
6503
+ // probe is declined and the caller re-emits under its own scope.
4031
6504
  const sub = this.childCtx(ctx);
4032
- const v = this.emitReturn(single.expression, sub);
6505
+ const v = this.withNarrowScope(ctx, "merge", () => this.emitReturn(single.expression!, sub), new Set());
4033
6506
  if (sub.lines.length === 0) return this.returnText(ctx, v, single);
4034
6507
  return null;
4035
6508
  }
6509
+ if (single && (ts.isBreakStatement(single) || ts.isContinueStatement(single))) {
6510
+ // A break bound to a switch has no one-statement Zig spelling (Zig
6511
+ // `break` binds loops); declining here routes it through statement
6512
+ // emission, where it stops the build with its teaching.
6513
+ if (ts.isBreakStatement(single) && !single.label && this.breakBindsEnclosingSwitch(single)) {
6514
+ return null;
6515
+ }
6516
+ const kw = ts.isBreakStatement(single) ? "break" : "continue";
6517
+ return single.label ? `${kw} :${loopLabel(single.label.text)};` : `${kw};`;
6518
+ }
4036
6519
  return null;
4037
6520
  }
4038
6521
 
@@ -4041,10 +6524,14 @@ export class Emitter {
4041
6524
  cond: ts.Expression,
4042
6525
  op: ts.SyntaxKind = ts.SyntaxKind.EqualsEqualsEqualsToken,
4043
6526
  ): { base: ts.Expression; tag: string } | null {
4044
- if (!ts.isBinaryExpression(cond) || cond.operatorToken.kind !== op) return null;
6527
+ // Wrappers strip exactly as in emptyTestOf: a parenthesized, asserted,
6528
+ // or `as`/`satisfies`-cast guard or operand must narrow the same arm
6529
+ // the bare spelling does (emission erases every one of them).
6530
+ const c = unwrapExpr(cond);
6531
+ if (!ts.isBinaryExpression(c) || c.operatorToken.kind !== op) return null;
4045
6532
  const sides: Array<[ts.Expression, ts.Expression]> = [
4046
- [cond.left, cond.right],
4047
- [cond.right, cond.left],
6533
+ [unwrapExpr(c.left), unwrapExpr(c.right)],
6534
+ [unwrapExpr(c.right), unwrapExpr(c.left)],
4048
6535
  ];
4049
6536
  for (const [kindSide, litSide] of sides) {
4050
6537
  if (
@@ -4072,15 +6559,28 @@ export class Emitter {
4072
6559
  const t = unwrapOptional(this.zTypeOfExpr(guard.base, ctx));
4073
6560
  if (t.k !== "union") return emitBranch();
4074
6561
  const savedSubst = new Map(ctx.memberSubst);
6562
+ // stillOptionalSubst rides along: narrowUnion overwrites an optional
6563
+ // payload's marker with ITS access spelling, and a marker left out of
6564
+ // sync with the restored memberSubst breaks the identity check
6565
+ // zTypeOfExpr keys on — a redundant kind guard inside a payload
6566
+ // capture would leave the capture looking non-null for the rest of
6567
+ // the arm, routing reads around the null-narrowing lowerings.
6568
+ const savedStillOptional = new Map(ctx.stillOptionalSubst);
4075
6569
  const savedNarrow = new Map(ctx.narrowedUnion);
6570
+ this.pushNarrowKillFrame(ctx);
4076
6571
  this.narrowUnion(guard.base, t.name, guard.tag, ctx);
4077
6572
  try {
4078
6573
  return emitBranch();
4079
6574
  } finally {
4080
6575
  ctx.memberSubst.clear();
4081
6576
  for (const [k, v] of savedSubst) ctx.memberSubst.set(k, v);
6577
+ ctx.stillOptionalSubst.clear();
6578
+ for (const [k, v] of savedStillOptional) ctx.stillOptionalSubst.set(k, v);
4082
6579
  ctx.narrowedUnion.clear();
4083
6580
  for (const [k, v] of savedNarrow) ctx.narrowedUnion.set(k, v);
6581
+ // Assignment kills inside the branch stay dead past this restore
6582
+ // (the snapshot would resurrect them; see popNarrowKillFrame).
6583
+ this.popNarrowKillFrame(ctx);
4084
6584
  }
4085
6585
  }
4086
6586
 
@@ -4090,12 +6590,16 @@ export class Emitter {
4090
6590
  const arm = info.arms.find((a) => a.tag === tag);
4091
6591
  if (!arm) return;
4092
6592
  const baseText = this.emitExpr(expr, ctx).code;
4093
- const key = normalize(expr);
6593
+ const key = this.narrowKey(expr);
6594
+ if (key === null) return;
4094
6595
  ctx.narrowedUnion.set(key, tag);
4095
6596
  for (const f of arm.fields) {
4096
6597
  const access =
4097
6598
  arm.fields.length === 1 ? `${baseText}.${zigId(tag)}` : `${baseText}.${zigId(tag)}.${fieldName(f)}`;
4098
6599
  ctx.memberSubst.set(`${key}.${f.tsName}`, access);
6600
+ // Kind-narrowing selects the arm; it proves nothing about a field
6601
+ // that is itself optional — the payload access keeps the optional.
6602
+ if (this.fieldZType(f).k === "optional") ctx.stillOptionalSubst.set(`${key}.${f.tsName}`, access);
4099
6603
  }
4100
6604
  }
4101
6605
 
@@ -4139,16 +6643,53 @@ export class Emitter {
4139
6643
  return test;
4140
6644
  }
4141
6645
 
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).
6646
+ /// Whether any of the nodes READS the guarded target — declaration
6647
+ /// identity for identifiers, declaration-QUALIFIED narrowKeys for
6648
+ /// property chains (anyReadsKey). Never source text: a shadowed spelling
6649
+ /// inside a nested callback (`xs.map((box) => box.q)`) is not a read of
6650
+ /// the outer `box.q`, and matching it by text binds a capture the
6651
+ /// declaration-keyed substitution (correctly) never rewrites — a Zig
6652
+ /// unused-capture error.
6653
+ ///
6654
+ /// Reads, not uses (identifierRead, the same judgment branchReadsTarget
6655
+ /// and captureServesBranch apply): the bare TARGET of a plain `=`
6656
+ /// assignment writes the raw slot, never the capture, so a write-only
6657
+ /// occurrence cannot consume a binding — gating a capture on it binds
6658
+ /// the capture unused, a Zig error. Compound assignments and `++`/`--`
6659
+ /// read the slot and still count. Property-chain targets are immutable
6660
+ /// model data, so their key walk needs no write exclusion.
4145
6661
  private anyReadsTarget(nodes: readonly ts.Node[], target: ts.Expression): boolean {
4146
6662
  if (ts.isIdentifier(target)) {
4147
6663
  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));
6664
+ if (decl) return nodes.some((n) => this.identifierRead(n, decl));
6665
+ }
6666
+ return this.anyReadsKey(nodes, this.narrowKey(target));
6667
+ }
6668
+
6669
+ /// The property-chain read walk every capture/substitution GATE in the
6670
+ /// narrowing machinery uses: visit the nodes' property accesses (and
6671
+ /// identifiers, for the no-declaration corner), canonicalize each
6672
+ /// through narrowKey, and compare against the target's key — the same
6673
+ /// identity the installed substitutions are looked up by, so a gate that
6674
+ /// fires here is a gate whose capture WILL be consumed. Wrapper
6675
+ /// spellings (`(box.q)`, `box.q!`) match through the key's own
6676
+ /// canonicalization; a longer chain (`box.q.name`) matches via its
6677
+ /// inner access on the recursive walk.
6678
+ private anyReadsKey(nodes: readonly ts.Node[], key: string | null): boolean {
6679
+ // A keyless target (see narrowKey) has no reads to serve: nothing can
6680
+ // be substituted for it, so every gate over it declines.
6681
+ if (key === null) return false;
6682
+ let found = false;
6683
+ const visit = (n: ts.Node): void => {
6684
+ if (found) return;
6685
+ if ((ts.isPropertyAccessExpression(n) || ts.isIdentifier(n)) && this.narrowKey(n) === key) {
6686
+ found = true;
6687
+ return;
6688
+ }
6689
+ ts.forEachChild(n, visit);
6690
+ };
6691
+ for (const n of nodes) visit(n);
6692
+ return found;
4152
6693
  }
4153
6694
 
4154
6695
  /// Whether the nodes ASSIGN the guarded local (only identifiers are
@@ -4186,6 +6727,49 @@ export class Emitter {
4186
6727
  return found;
4187
6728
  }
4188
6729
 
6730
+ /// Whether a guarded branch can bind a Zig CAPTURE for its narrowed
6731
+ /// target. tsc keeps the narrow through a provably non-null
6732
+ /// reassignment, but a capture goes stale there — the assignment
6733
+ /// emitter transitions the substitution to the live-slot `.?` spelling
6734
+ /// — so the capture form only holds when every plain `=` assignment to
6735
+ /// the target sits at the branch's top statement level (straight-line
6736
+ /// flow the transition covers) AND some read precedes the first
6737
+ /// assignment to consume the binding. An assignment inside a nested
6738
+ /// construct (an if arm, a loop body — whose back edge reaches even
6739
+ /// the reads spelled above it) hands the branch to the `.?` spelling
6740
+ /// up front, which is valid for every read the guard dominates. A
6741
+ /// branch that never assigns the target keeps the capture; property
6742
+ /// targets are never assignable.
6743
+ private captureServesBranch(branch: ts.Statement, target: ts.Expression): boolean {
6744
+ if (!ts.isIdentifier(target)) return true;
6745
+ const decl = this.tast.declarationOf(target);
6746
+ if (!decl) return true;
6747
+ const stmts = ts.isBlock(branch) ? branch.statements : [branch];
6748
+ const plainAssignOf = (s: ts.Statement): ts.BinaryExpression | null =>
6749
+ ts.isExpressionStatement(s) &&
6750
+ ts.isBinaryExpression(s.expression) &&
6751
+ s.expression.operatorToken.kind === ts.SyntaxKind.EqualsToken &&
6752
+ ts.isIdentifier(s.expression.left) &&
6753
+ this.tast.declarationOf(s.expression.left) === decl
6754
+ ? s.expression
6755
+ : null;
6756
+ let anyAssign = false;
6757
+ let readBeforeAssign = false;
6758
+ for (const s of stmts) {
6759
+ const assign = plainAssignOf(s);
6760
+ if (assign) {
6761
+ // The RHS evaluates before the write, so its reads still consume
6762
+ // the capture.
6763
+ if (!anyAssign && this.identifierRead(assign.right, decl)) readBeforeAssign = true;
6764
+ anyAssign = true;
6765
+ continue;
6766
+ }
6767
+ if (this.assignsTarget([s], target)) return false;
6768
+ if (!anyAssign && this.identifierRead(s, decl)) readBeforeAssign = true;
6769
+ }
6770
+ return anyAssign ? readBeforeAssign : true;
6771
+ }
6772
+
4189
6773
  /// True when some conjunct null-guards a target a LATER conjunct reads —
4190
6774
  /// the chain needs one of the R7d lowerings to stay valid Zig.
4191
6775
  private chainHasNullGuard(conjuncts: readonly ts.Expression[], op: ts.SyntaxKind, ctx: Ctx): boolean {
@@ -4211,9 +6795,10 @@ export class Emitter {
4211
6795
  const rest = conjuncts.slice(1);
4212
6796
  if (rest.length === 0) return emitOne(c0);
4213
6797
  const guard = this.nullGuardOf(c0, op, ctx);
4214
- if (guard && this.anyReadsTarget(rest, guard.target)) {
6798
+ const guardKey = guard === null ? null : this.narrowKey(guard.target);
6799
+ if (guard && guardKey !== null && this.anyReadsTarget(rest, guard.target)) {
4215
6800
  this.requireFaithfulEmptyTest(guard.target, guard.flavor, c0);
4216
- const key = normalize(guard.target);
6801
+ const key = guardKey;
4217
6802
  const prop = this.emitExpr(guard.target, ctx).code;
4218
6803
  const cap = this.freshName(ctx, this.narrowHint(guard.target));
4219
6804
  const saved = ctx.memberSubst.get(key);
@@ -4246,18 +6831,21 @@ export class Emitter {
4246
6831
  const isAnd = op === ts.SyntaxKind.AmpersandAmpersandToken;
4247
6832
  const zop = isAnd ? "and" : "or";
4248
6833
  const saved = new Map(ctx.memberSubst);
6834
+ this.pushNarrowKillFrame(ctx);
4249
6835
  const emitChain = (conjs: readonly ts.Expression[]): string => {
4250
6836
  const c0 = conjs[0];
4251
6837
  const rest = conjs.slice(1);
4252
6838
  const guard = this.nullGuardOf(c0, op, ctx);
4253
6839
  if (guard) {
4254
6840
  this.requireFaithfulEmptyTest(guard.target, guard.flavor, c0);
4255
- const key = normalize(guard.target);
6841
+ const key = this.narrowKey(guard.target);
4256
6842
  const prop = this.emitExpr(guard.target, ctx).code;
4257
6843
  const head = `${prop} ${isAnd ? "!=" : "=="} null`;
4258
6844
  if (rest.length === 0) return head;
4259
- ctx.memberSubst.set(key, `${prop}.?`);
4260
- guards.set(key, `${prop}.?`);
6845
+ if (key !== null) {
6846
+ ctx.memberSubst.set(key, `${prop}.?`);
6847
+ guards.set(key, `${prop}.?`);
6848
+ }
4261
6849
  return `${head} ${zop} ${emitChain(rest)}`;
4262
6850
  }
4263
6851
  const head = precedenceParen(c0, zop, this.emitExpr(c0, ctx, { k: "bool" }).code);
@@ -4271,6 +6859,10 @@ export class Emitter {
4271
6859
  const code = emitChain(conjuncts);
4272
6860
  ctx.memberSubst.clear();
4273
6861
  for (const [k, v] of saved) ctx.memberSubst.set(k, v);
6862
+ // A conjunct can smuggle statements in (a block-bodied callback, an
6863
+ // R10b value-position step); an assignment kill made there must stay
6864
+ // dead past this restore (see popNarrowKillFrame).
6865
+ this.popNarrowKillFrame(ctx);
4274
6866
  return code;
4275
6867
  }
4276
6868
 
@@ -4278,11 +6870,15 @@ export class Emitter {
4278
6870
  private withSubsts<T>(guards: ReadonlyMap<string, string>, ctx: Ctx, emit: () => T): T {
4279
6871
  const saved = new Map(ctx.memberSubst);
4280
6872
  for (const [k, v] of guards) ctx.memberSubst.set(k, v);
6873
+ this.pushNarrowKillFrame(ctx);
4281
6874
  try {
4282
6875
  return emit();
4283
6876
  } finally {
4284
6877
  ctx.memberSubst.clear();
4285
6878
  for (const [k, v] of saved) ctx.memberSubst.set(k, v);
6879
+ // Assignment kills inside the scope stay dead past this restore
6880
+ // (the snapshot would resurrect them; see popNarrowKillFrame).
6881
+ this.popNarrowKillFrame(ctx);
4286
6882
  }
4287
6883
  }
4288
6884
 
@@ -4351,8 +6947,9 @@ export class Emitter {
4351
6947
  // A reassigned local cannot narrow through a capture (the capture
4352
6948
  // goes stale); the unwrap spelling below reads the live variable.
4353
6949
  if (this.assignsTarget(readers, g.target)) break;
6950
+ const key = this.narrowKey(g.target);
6951
+ if (key === null) break;
4354
6952
  this.requireFaithfulEmptyTest(g.target, g.flavor, conjuncts[gi]);
4355
- const key = normalize(g.target);
4356
6953
  const prop = this.emitExpr(g.target, ctx).code;
4357
6954
  const cap = this.freshName(ctx, this.narrowHint(g.target));
4358
6955
  caps.push({ key, saved: ctx.memberSubst.get(key) });
@@ -4404,14 +7001,15 @@ export class Emitter {
4404
7001
  const condText = this.emitNullGuardChainUnwrap(conjuncts, op, ctx, guards);
4405
7002
  const kindGuards = this.chainKindGuards(conjuncts, op);
4406
7003
  const thenStmts = ts.isBlock(stmt.thenStatement) ? stmt.thenStatement.statements : [stmt.thenStatement];
7004
+ const join = new Set<string>();
4407
7005
  this.push(ctx, `if (${condText}) {`);
4408
7006
  const tSub = this.nestedCtx(ctx);
4409
7007
  if (isAnd) {
4410
7008
  this.withSubsts(guards, ctx, () =>
4411
- this.withKindNarrows(kindGuards, ctx, () => this.emitBlockStatements(thenStmts, tSub)),
7009
+ this.withKindNarrows(kindGuards, ctx, () => this.emitBlockStatements(thenStmts, tSub, join)),
4412
7010
  );
4413
7011
  } else {
4414
- this.emitBlockStatements(thenStmts, tSub);
7012
+ this.emitBlockStatements(thenStmts, tSub, join);
4415
7013
  }
4416
7014
  ctx.lines.push(...tSub.lines);
4417
7015
  if (stmt.elseStatement) {
@@ -4420,18 +7018,23 @@ export class Emitter {
4420
7018
  const elseStmts = ts.isBlock(stmt.elseStatement) ? stmt.elseStatement.statements : [stmt.elseStatement];
4421
7019
  if (!isAnd) {
4422
7020
  this.withSubsts(guards, ctx, () =>
4423
- this.withKindNarrows(kindGuards, ctx, () => this.emitBlockStatements(elseStmts, eSub)),
7021
+ this.withKindNarrows(kindGuards, ctx, () => this.emitBlockStatements(elseStmts, eSub, join)),
4424
7022
  );
4425
7023
  } else {
4426
- this.emitBlockStatements(elseStmts, eSub);
7024
+ this.emitBlockStatements(elseStmts, eSub, join);
4427
7025
  }
4428
7026
  ctx.lines.push(...eSub.lines);
4429
7027
  }
4430
7028
  this.push(ctx, `}`);
7029
+ this.applyJoinedNarrowKills(ctx, join);
4431
7030
  if (exitDual) {
4432
7031
  // `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);
7032
+ // with x present, so the unwrap substitutions stay active — minus
7033
+ // any target the arm killed on a non-leaving exit (a break/continue
7034
+ // route merges its kills; the post-statement state subtracts them).
7035
+ for (const [k, v] of guards) {
7036
+ if (!join.has(k)) ctx.memberSubst.set(k, v);
7037
+ }
4435
7038
  }
4436
7039
  return true;
4437
7040
  }
@@ -4463,7 +7066,15 @@ export class Emitter {
4463
7066
  this.push(ctx, `${head} (${cond}) : (${inc}) {`);
4464
7067
  const sub = this.nestedCtx(ctx);
4465
7068
  const body = ts.isBlock(stmt.statement) ? stmt.statement.statements : [stmt.statement];
4466
- this.emitBlockStatements(body, sub);
7069
+ // A `for (; false;)` body is statically unreachable to tsc's CFA
7070
+ // (tscExcludedArm), so its kills never reach the post-loop state —
7071
+ // the same drop emitWhile applies to a `while (false)` body. The
7072
+ // body still emits; only the flow bookkeeping skips.
7073
+ if (this.tscExcludedArm(stmt, stmt.statement)) {
7074
+ this.withNarrowScope(ctx, "drop", () => this.emitBlockStatements(body, sub));
7075
+ } else {
7076
+ this.emitBlockStatements(body, sub);
7077
+ }
4467
7078
  ctx.lines.push(...sub.lines);
4468
7079
  this.push(ctx, `}`);
4469
7080
  }
@@ -4682,10 +7293,18 @@ export class Emitter {
4682
7293
  const info = this.table.unions.get(baseType.name);
4683
7294
  if (!info) this.fail(stmt, `unknown union ${baseType.name}`);
4684
7295
  const base = this.emitExpr(scrutinee.expression, ctx).code;
4685
- const baseKey = normalize(scrutinee.expression);
7296
+ const baseKey = this.narrowKey(scrutinee.expression);
4686
7297
  this.push(ctx, `switch (${base}) {`);
4687
7298
  const armCtx = { ...ctx, indent: ctx.indent + 1 };
4688
7299
  const covered = new Set<string>();
7300
+ // Clauses are pure siblings — alternatives from the switch's entry
7301
+ // state, never a sequence: tsc's noFallthroughCasesInSwitch (on in the
7302
+ // subset's program options) rejects a non-empty clause that falls into
7303
+ // the next, and label stacking shares ONE body. So each clause's
7304
+ // merge-class kills join here and apply only after every clause has
7305
+ // emitted (see applyJoinedNarrowKills) — applying them per clause
7306
+ // would strip a later clause of a narrowing tsc keeps there.
7307
+ const join = new Set<string>();
4689
7308
  let sawDefault = false;
4690
7309
  // Label stacking (`case "a": case "b": body`): JS runs the next body
4691
7310
  // for every stacked label, so the labels coalesce into one Zig arm.
@@ -4717,7 +7336,7 @@ export class Emitter {
4717
7336
  continue;
4718
7337
  }
4719
7338
  const sub = this.nestedCtx(armCtx);
4720
- this.emitBlockStatements(stmts, sub);
7339
+ this.emitBlockStatements(stmts, sub, join);
4721
7340
  const single = sub.lines.length === 1 ? sub.lines[0].trim() : null;
4722
7341
  if (single && (single.startsWith("return ") || single.startsWith("break :")) && single.endsWith(";")) {
4723
7342
  const armText = `else => ${single.slice(0, -1)},`;
@@ -4747,11 +7366,16 @@ export class Emitter {
4747
7366
  if (last && ts.isBreakStatement(last) && !last.label) stmts = stmts.slice(0, -1);
4748
7367
 
4749
7368
  const sub = this.nestedCtx(armCtx);
4750
- // Payload capture + member substitution for this arm's fields.
7369
+ // Payload capture + member substitution for this arm's fields. Field
7370
+ // use is judged by the declaration-qualified key the substitutions
7371
+ // are installed under — a same-named field of some OTHER value in
7372
+ // the body (`box.v` beside payload field `v`) is not a payload read,
7373
+ // and binding the capture for it would leave it unused.
4751
7374
  const savedSubst = new Map(ctx.memberSubst);
7375
+ const savedStillOptional = new Map(ctx.stillOptionalSubst);
4752
7376
  let capture = "";
4753
- const payloadUsed = arm.fields.some((f) =>
4754
- stmts.some((s) => s.getText().includes(`.${f.tsName}`)),
7377
+ const payloadUsed = baseKey !== null && arm.fields.some((f) =>
7378
+ this.anyReadsKey(stmts, `${baseKey}.${f.tsName}`),
4755
7379
  );
4756
7380
  if (pending.length > 0 && payloadUsed) {
4757
7381
  // The shared body would need one capture per differently-shaped
@@ -4762,14 +7386,37 @@ export class Emitter {
4762
7386
  const cap = this.freshName(sub, zigLocalName(arm.fields[0].tsName));
4763
7387
  capture = `|${cap}| `;
4764
7388
  sub.memberSubst.set(`${baseKey}.${arm.fields[0].tsName}`, cap);
7389
+ // The capture holds the payload AS-IS: an optional field stays
7390
+ // optional through it (this is a rename, not a null-narrowing).
7391
+ if (this.fieldZType(arm.fields[0]).k === "optional") {
7392
+ sub.stillOptionalSubst.set(`${baseKey}.${arm.fields[0].tsName}`, cap);
7393
+ }
4765
7394
  } else if (arm.fields.length > 1 && payloadUsed) {
4766
7395
  const cap = this.freshName(sub, zigId(arm.tag));
4767
7396
  capture = `|${cap}| `;
4768
- for (const f of arm.fields) sub.memberSubst.set(`${baseKey}.${f.tsName}`, `${cap}.${fieldName(f)}`);
7397
+ for (const f of arm.fields) {
7398
+ sub.memberSubst.set(`${baseKey}.${f.tsName}`, `${cap}.${fieldName(f)}`);
7399
+ if (this.fieldZType(f).k === "optional") {
7400
+ sub.stillOptionalSubst.set(`${baseKey}.${f.tsName}`, `${cap}.${fieldName(f)}`);
7401
+ }
7402
+ }
4769
7403
  }
7404
+ this.pushNarrowKillFrame(ctx);
4770
7405
  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);
7406
+ // Restore: captures are arm-scoped, and the still-optional markers
7407
+ // stay paired with the substitutions they annotate. Repopulate from
7408
+ // the snapshot rather than deleting the arm's additions — a nested
7409
+ // switch on the same subject OVERWRITES entries the snapshot already
7410
+ // held (its capture shadows the outer one), and a delete-only sweep
7411
+ // would leave the inner capture name active after its block closed.
7412
+ ctx.memberSubst.clear();
7413
+ for (const [k, v] of savedSubst) ctx.memberSubst.set(k, v);
7414
+ ctx.stillOptionalSubst.clear();
7415
+ for (const [k, v] of savedStillOptional) ctx.stillOptionalSubst.set(k, v);
7416
+ // Assignment kills inside the arm join with the sibling clauses'
7417
+ // and apply after the last clause (the snapshot above must not
7418
+ // resurrect them; see applyJoinedNarrowKills).
7419
+ for (const key of this.popNarrowKillFrame(ctx, "drop")) join.add(key);
4773
7420
 
4774
7421
  const labels = [...pending, tag].map((t) => `.${zigId(t)}`).join(", ");
4775
7422
  pending = [];
@@ -4795,6 +7442,7 @@ export class Emitter {
4795
7442
  }
4796
7443
  }
4797
7444
  this.push(ctx, `}`);
7445
+ this.applyJoinedNarrowKills(ctx, join);
4798
7446
  }
4799
7447
 
4800
7448
  /// R13d: a switch over a literal-union VALUE. Member labels become enum or
@@ -4812,6 +7460,9 @@ export class Emitter {
4812
7460
  this.push(ctx, `switch (${base}) {`);
4813
7461
  const armCtx = { ...ctx, indent: ctx.indent + 1 };
4814
7462
  const covered = new Set<string>();
7463
+ // Clauses are siblings (noFallthroughCasesInSwitch; stacked labels
7464
+ // share one body): kills join and apply after the last clause.
7465
+ const join = new Set<string>();
4815
7466
  let pending: string[] = [];
4816
7467
  let sawDefault = false;
4817
7468
  let allExit = true;
@@ -4860,7 +7511,7 @@ export class Emitter {
4860
7511
  const armLabel = label ? [...pending, label].join(", ") : "else";
4861
7512
  pending = [];
4862
7513
  const sub = this.nestedCtx(armCtx);
4863
- this.emitBlockStatements(stmts, sub);
7514
+ this.emitBlockStatements(stmts, sub, join);
4864
7515
  const single = sub.lines.length === 1 ? sub.lines[0].trim() : null;
4865
7516
  if (single && (single.startsWith("return ") || single.startsWith("break :")) && single.endsWith(";")) {
4866
7517
  const armText = `${armLabel} => ${single.slice(0, -1)},`;
@@ -4876,17 +7527,37 @@ export class Emitter {
4876
7527
  if (pending.length > 0) this.push(armCtx, `${pending.join(", ")} => {},`);
4877
7528
  if (!sawDefault) {
4878
7529
  const total = t.k === "enum" ? t.members.length : t.values.length;
7530
+ // Coverage of the declared members, or of the scrutinee's sound
7531
+ // coverage type (valueSwitchCoversScrutineeType — declared-type based,
7532
+ // never the raw flow type): either proves the fallthrough arm never
7533
+ // runs, and alwaysExits claims terminality off the second, so the
7534
+ // emitted shape must close exactly the path the claim closed. When
7535
+ // the judgment declines, the else completes (`else => {}`) and the
7536
+ // terminality claim declines with it — a reached `unreachable` is
7537
+ // never acceptable.
7538
+ const coveredByType = covered.size === total || this.valueSwitchCoversScrutineeType(stmt);
7539
+ // AGREEMENT: alwaysExits claims terminality off this same coverage
7540
+ // judgment, and a claimed-terminal switch must never lower to a
7541
+ // completable shape (`else => {}`). The claim's conditions imply
7542
+ // coveredByType && allExit, so the disagreement cannot arise; if a
7543
+ // future edit splits the two judgments, stop the build rather than
7544
+ // emit an arm that completes where the claim said it cannot.
7545
+ if (!(coveredByType && allExit) && this.alwaysExits(stmt)) {
7546
+ this.fail(stmt, "a switch claimed always-exiting whose lowering left a completable fallthrough arm (terminality/lowering disagreement)");
7547
+ }
4879
7548
  if (t.k === "numAlias") {
4880
7549
  // The Zig scrutinee is an integer type, so an else arm is always
4881
7550
  // required. With every member covered by an exiting arm the else is
4882
7551
  // unreachable by the TypeScript types.
4883
- this.push(armCtx, covered.size === total && allExit ? `else => unreachable,` : `else => {},`);
7552
+ this.push(armCtx, coveredByType && allExit ? `else => unreachable,` : `else => {},`);
4884
7553
  } else if (covered.size < total) {
4885
- // JS: an uncovered member skips the switch.
4886
- this.push(armCtx, `else => {},`);
7554
+ // JS: an uncovered member skips the switch; one the TypeScript
7555
+ // types rule out never reaches it.
7556
+ this.push(armCtx, coveredByType && allExit ? `else => unreachable,` : `else => {},`);
4887
7557
  }
4888
7558
  }
4889
7559
  this.push(ctx, `}`);
7560
+ this.applyJoinedNarrowKills(ctx, join);
4890
7561
  }
4891
7562
 
4892
7563
  /// R13f: a switch over a PLAIN number/string value lowers to an if/else
@@ -4964,30 +7635,61 @@ export class Emitter {
4964
7635
  }
4965
7636
  // Trailing label-only clauses (and a trailing empty default): JS no-ops.
4966
7637
  const defaultArm = arms.find((a) => a.alsoDefault) ?? null;
7638
+ // AGREEMENT: alwaysExits may claim this switch terminal (defaultless,
7639
+ // no bound break, case labels covering the scrutinee's SOUND coverage
7640
+ // type, every clause group exiting — the same memoized
7641
+ // valueSwitchCoversScrutineeType judgment emitValueSwitch closes its
7642
+ // `else => unreachable` off). The lowered chain must then close too:
7643
+ // left open, the claim suppresses the trailing completion a value
7644
+ // block or a returning function needs, and the chain's end — which
7645
+ // the claim just promised is unreachable — completes into invalid
7646
+ // Zig. The coverage judgment is sound by construction (declared type,
7647
+ // or a flow type no nested assigner can have run against), so the
7648
+ // closing arm is an `else` real execution never reaches.
7649
+ const claimsTerminal = this.alwaysExits(stmt);
7650
+ // The lowered if/else chain's arms are the switch's clauses — siblings
7651
+ // (noFallthroughCasesInSwitch): kills join and apply after the chain.
7652
+ const join = new Set<string>();
4967
7653
  let opened = false;
4968
7654
  for (const arm of arms) {
4969
7655
  if (arm.conds.length === 0) continue; // a pure default arm emits as the else below
4970
7656
  const cond = arm.conds.join(" or ");
4971
7657
  this.push(ctx, `${opened ? "} else " : ""}if (${cond}) {`);
4972
7658
  const sub = this.nestedCtx(ctx);
4973
- this.emitBlockStatements(arm.stmts, sub);
7659
+ this.emitBlockStatements(arm.stmts, sub, join);
4974
7660
  ctx.lines.push(...sub.lines);
4975
7661
  opened = true;
4976
7662
  }
4977
7663
  if (defaultArm && opened) {
4978
7664
  this.push(ctx, `} else {`);
4979
7665
  const sub = this.nestedCtx(ctx);
4980
- this.emitBlockStatements(defaultArm.stmts, sub);
7666
+ this.emitBlockStatements(defaultArm.stmts, sub, join);
4981
7667
  ctx.lines.push(...sub.lines);
4982
7668
  } else if (defaultArm) {
4983
7669
  // Every case label was empty-trailing (or none existed): the default
4984
- // body runs unconditionally.
7670
+ // body runs unconditionally — straight-line flow, so its kills merge
7671
+ // as usual rather than joining with the (nonexistent) other arms.
4985
7672
  const sub = this.childCtx(ctx);
4986
7673
  this.emitBlockStatements(defaultArm.stmts, sub);
4987
7674
  ctx.lines.push(...sub.lines);
7675
+ this.applyJoinedNarrowKills(ctx, join);
4988
7676
  return;
7677
+ } else if (opened && claimsTerminal) {
7678
+ // The claimed-terminal defaultless chain closes its never-reached
7679
+ // fallthrough (see the AGREEMENT note above).
7680
+ this.push(ctx, `} else {`);
7681
+ const sub = this.nestedCtx(ctx);
7682
+ this.push(sub, `unreachable;`);
7683
+ ctx.lines.push(...sub.lines);
7684
+ } else if (claimsTerminal) {
7685
+ // Terminal without any emitted arm cannot happen (a terminality
7686
+ // claim needs an exiting, statement-bearing clause); if a future
7687
+ // edit breaks that, stop the build rather than emit a shape that
7688
+ // completes where the claim said it cannot.
7689
+ this.fail(stmt, "a switch claimed always-exiting whose lowering emitted no arms (terminality/lowering disagreement)");
4989
7690
  }
4990
7691
  if (opened) this.push(ctx, `}`);
7692
+ this.applyJoinedNarrowKills(ctx, join);
4991
7693
  if (sawDefault && !defaultArm && clauses.length > 0) {
4992
7694
  // A trailing empty default is a JS no-op; nothing to emit.
4993
7695
  }
@@ -5015,6 +7717,9 @@ export class Emitter {
5015
7717
  ) {
5016
7718
  return; // breaks inside these target them, not the switch
5017
7719
  }
7720
+ // A nested function's breaks bind inside the function (the
7721
+ // breaksToLabel boundary rule), never this switch.
7722
+ if (ts.isFunctionLike(n)) return;
5018
7723
  if (ts.isBreakStatement(n) && !n.label) {
5019
7724
  this.fail(n, "an early `break` inside a plain-value switch clause (end the clause with a single trailing `break` or a `return`)");
5020
7725
  }
@@ -5143,16 +7848,42 @@ export class Emitter {
5143
7848
  // narrowing dies with the assignment, exactly like TS.
5144
7849
  const t = this.zTypeOfExprClassed(expr.left, ctx);
5145
7850
  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);
7851
+ const key = this.narrowKey(expr.left);
7852
+ const hadSubst = key === null ? undefined : ctx.memberSubst.get(key);
7853
+ if (key !== null && hadSubst !== undefined) ctx.memberSubst.delete(key);
5149
7854
  const target = this.emitExpr(expr.left, ctx).code;
5150
- if (hadSubst !== undefined && hadSubst.endsWith(".?")) {
7855
+ const empties = this.tast.emptiesOf(expr.right);
7856
+ const mayBeEmpty = empties.null || empties.undefined;
7857
+ if (key !== null && hadSubst !== undefined && hadSubst.endsWith(".?") && !mayBeEmpty) {
5151
7858
  // `.?` 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);
7859
+ // assignment of a provably non-null value.
7860
+ ctx.memberSubst.set(key, hadSubst);
7861
+ } else if (
7862
+ key !== null &&
7863
+ hadSubst !== undefined &&
7864
+ !mayBeEmpty &&
7865
+ hadSubst !== ctx.stillOptionalSubst.get(key) &&
7866
+ this.zTypeOfExpr(expr.left, ctx).k === "optional"
7867
+ ) {
7868
+ // A capture substitution would read the stale capture, but tsc
7869
+ // keeps the target narrowed through a provably non-null
7870
+ // assignment — so the substitution TRANSITIONS to the live-slot
7871
+ // `.?` spelling from this point onward: still narrowed, reads go
7872
+ // through the reassigned slot. (The still-optional renames are
7873
+ // payload aliases, not null-narrows; they have no `.?` form.)
7874
+ ctx.memberSubst.set(key, `${target}.?`);
7875
+ }
7876
+ if (key !== null && !ctx.memberSubst.has(key) && (hadSubst !== undefined || mayBeEmpty)) {
7877
+ // The narrowing died with this assignment (the value may be null
7878
+ // again, or the substitution has no live-slot form to transition
7879
+ // to). Record the kill so scope
7880
+ // exits, whose snapshot restores give containment, do not
7881
+ // resurrect it past the merge — and record it even when NO
7882
+ // substitution was live: a construct's post-exit narrow
7883
+ // (applyPostIfNarrow and kin) subtracts the joined kills, and
7884
+ // tsc buries the guard-implied narrow for every possibly-null
7885
+ // assignment an arm makes, active substitution or not.
7886
+ ctx.narrowKilled[ctx.narrowKilled.length - 1]?.add(key);
5156
7887
  }
5157
7888
  this.push(ctx, `${target} = ${this.byteStoreNarrowed(expr, v.code, ctx)};`);
5158
7889
  return;
@@ -5930,7 +8661,8 @@ export class Emitter {
5930
8661
  }
5931
8662
 
5932
8663
  private emitExprValue(expr: ts.Expression, ctx: Ctx, expected?: ZType, nameHint?: string): Emitted {
5933
- const subst = ctx.memberSubst.get(normalize(expr));
8664
+ const substKey = this.narrowKey(expr);
8665
+ const subst = substKey === null ? undefined : ctx.memberSubst.get(substKey);
5934
8666
  if (subst !== undefined) return { code: subst };
5935
8667
 
5936
8668
  if (ts.isParenthesizedExpression(expr)) {
@@ -6021,8 +8753,10 @@ export class Emitter {
6021
8753
  }
6022
8754
  const baseCode = this.emitExpr(expr.expression, ctx).code;
6023
8755
  const cap = this.freshName(ctx, nameHint ?? "elems");
8756
+ // Probe in a flow scope (see childCtx): a lines-free index probe
8757
+ // processed no statements, and a lines-bearing one stops the build.
6024
8758
  const idxCtx = this.childCtx(ctx);
6025
- const idx = this.emitIndex(expr.argumentExpression, idxCtx);
8759
+ const idx = this.withNarrowScope(ctx, "merge", () => this.emitIndex(expr.argumentExpression, idxCtx), new Set());
6026
8760
  if (idxCtx.lines.length > 0) {
6027
8761
  // JS only evaluates the index when the base is non-null; an index
6028
8762
  // needing its own statements cannot ride the inline capture.
@@ -6059,8 +8793,8 @@ export class Emitter {
6059
8793
  }
6060
8794
 
6061
8795
  private emitPropertyAccess(expr: ts.PropertyAccessExpression, ctx: Ctx): Emitted {
6062
- const key = normalize(expr);
6063
- const subst = ctx.memberSubst.get(key);
8796
+ const key = this.narrowKey(expr);
8797
+ const subst = key === null ? undefined : ctx.memberSubst.get(key);
6064
8798
  if (subst !== undefined) return { code: subst };
6065
8799
  // Layer-3 re-derivation of NS1017 (`Cmd.none` outside the return slot)
6066
8800
  // and NS1025 (its Sub mirror).
@@ -6100,8 +8834,8 @@ export class Emitter {
6100
8834
  if (ts.isOptionalChain(expr)) return this.emitOptionalChain(expr, ctx);
6101
8835
  const prop = expr.name.text;
6102
8836
  if (prop === "length") {
6103
- const lenKey = `${expr.expression.getText()}.length`;
6104
- const lenSubst = ctx.memberSubst.get(lenKey.replace(/\s+/g, ""));
8837
+ const baseLenKey = this.narrowKey(expr.expression);
8838
+ const lenSubst = baseLenKey === null ? undefined : ctx.memberSubst.get(`${baseLenKey}.length`);
6105
8839
  if (lenSubst !== undefined) return { code: lenSubst };
6106
8840
  const baseT = this.zTypeOfExpr(expr.expression, ctx);
6107
8841
  const base = this.emitExpr(expr.expression, ctx);
@@ -6213,6 +8947,20 @@ export class Emitter {
6213
8947
  // names — the overlap of the two string sets, resolved at compile time.
6214
8948
  const lt = unwrapOptional(this.zTypeOfExpr(expr.left, ctx));
6215
8949
  const rt = unwrapOptional(this.zTypeOfExpr(expr.right, ctx));
8950
+ // Layer-3 re-derivation of NS1061: identity over a by-value record
8951
+ // has no reference to compare (a pointer-stored record's `==` IS
8952
+ // its identity). This is the emission-time authority, so operands
8953
+ // that reached here through generic instantiation or erased
8954
+ // assertions stop the same way the checker teaches directly.
8955
+ for (const t of [lt, rt]) {
8956
+ if (t.k === "struct" && !this.table.isPointerStruct(t.name)) {
8957
+ this.fail(
8958
+ expr,
8959
+ `\`${op === ts.SyntaxKind.EqualsEqualsEqualsToken ? "===" : "!=="}\` compares \`${t.name}\` values by identity, which value storage does not carry — compare fields, or store the record by reference for identity`,
8960
+ "NS1061",
8961
+ );
8962
+ }
8963
+ }
6216
8964
  if (lt.k === "enum" && rt.k === "enum" && lt.name !== rt.name) {
6217
8965
  const l = this.emitExpr(expr.left, ctx).code;
6218
8966
  const r = this.emitExpr(expr.right, ctx).code;
@@ -6274,8 +9022,10 @@ export class Emitter {
6274
9022
  if (op === ts.SyntaxKind.QuestionQuestionToken) {
6275
9023
  // `x ?? null` folds JS undefined and null into one empty value — which
6276
9024
  // 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) {
9025
+ // the result (this is also how a `?.` chain value normalizes). The
9026
+ // wrapped spellings (`x ?? (null)`) and the `x ?? undefined` flavor
9027
+ // fold identically.
9028
+ if (this.isEmptyLiteral(expr.right)) {
6279
9029
  return this.emitExpr(expr.left, ctx, expected);
6280
9030
  }
6281
9031
  // Both sides see the expected type: either may need an enum re-tag.
@@ -6480,11 +9230,33 @@ export class Emitter {
6480
9230
  // `x === null ? A : x` -> `x orelse A` (the `=== undefined` spelling on
6481
9231
  // undefined-flavored values maps the same way, per R7c).
6482
9232
  const missTest = this.emptyTestOf(cond);
6483
- if (missTest && normalize(expr.whenFalse) === normalize(missTest.target)) {
9233
+ const missArmKey = this.narrowKey(expr.whenFalse);
9234
+ if (missTest && missArmKey !== null && missArmKey === this.narrowKey(missTest.target)) {
6484
9235
  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}` };
9236
+ // Probe both sides in throwaway child ctxs: the fusion only holds
9237
+ // when the miss arm is statement-free. An arm that lowers statements
9238
+ // (a spread literal builds its copy line by line) must not ride the
9239
+ // orelse — those lines would land ABOVE it and run even on the
9240
+ // non-empty path — so it falls through to the narrowed-ternary
9241
+ // lowering below, which scopes them to the branch that runs.
9242
+ const tT = this.zTypeOfExpr(missTest.target, ctx);
9243
+ const armWant =
9244
+ expected ? unwrapOptional(expected) : tT.k === "optional" ? tT.inner : undefined;
9245
+ // Both probes bracket in a flow scope (see childCtx): discarded, they
9246
+ // must leave no trace; taken, the miss arm's real kills join onto the
9247
+ // post-expression state below.
9248
+ const fuseJoin = new Set<string>();
9249
+ const targetSub = this.childCtx(ctx);
9250
+ const target = this.withNarrowScope(ctx, "merge", () => this.emitExpr(missTest.target, targetSub).code, fuseJoin);
9251
+ const altSub = this.childCtx(ctx);
9252
+ const alt = this.withNarrowScope(ctx, "merge", () => this.emitExpr(expr.whenTrue, altSub, armWant).code, fuseJoin);
9253
+ if (altSub.lines.length === 0) {
9254
+ // The target is evaluated exactly once; its lowered lines (if any)
9255
+ // ride ahead of the orelse like any condition's.
9256
+ ctx.lines.push(...targetSub.lines);
9257
+ this.applyJoinedNarrowKills(ctx, fuseJoin);
9258
+ return { code: `${target} orelse ${alt}` };
9259
+ }
6488
9260
  }
6489
9261
  // `x === null ? A : <uses x>` (and the `=== undefined` find-miss
6490
9262
  // spelling) — the narrowing dual of the `!==` case below: TS narrows
@@ -6495,22 +9267,14 @@ export class Emitter {
6495
9267
  missTest &&
6496
9268
  (ts.isPropertyAccessExpression(missTest.target) || ts.isIdentifier(missTest.target)) &&
6497
9269
  // 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())
9270
+ // guards keep the plain comparison. Declaration identity for
9271
+ // identifier targets: a wrapped read (`q!`) is still a read of q.
9272
+ this.anyReadsTarget([expr.whenFalse], missTest.target)
6500
9273
  ) {
6501
9274
  const t = this.zTypeOfExpr(missTest.target, ctx);
6502
9275
  if (t.k === "optional") {
6503
9276
  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}` };
9277
+ return this.emitNarrowedTernary(expr, missTest.target, expr.whenFalse, expr.whenTrue, ctx, expected, nameHint);
6514
9278
  }
6515
9279
  }
6516
9280
  // `x !== null ? <uses x> : B` -> `if (x) |v| ... else B`.
@@ -6519,22 +9283,14 @@ export class Emitter {
6519
9283
  hitTest &&
6520
9284
  (ts.isPropertyAccessExpression(hitTest.target) || ts.isIdentifier(hitTest.target)) &&
6521
9285
  // 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())
9286
+ // keep the plain comparison. Declaration identity for identifier
9287
+ // targets: a wrapped read (`q!`) is still a read of q.
9288
+ this.anyReadsTarget([expr.whenTrue], hitTest.target)
6524
9289
  ) {
6525
9290
  const t = this.zTypeOfExpr(hitTest.target, ctx);
6526
9291
  if (t.k === "optional") {
6527
9292
  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}` };
9293
+ return this.emitNarrowedTernary(expr, hitTest.target, expr.whenTrue, expr.whenFalse, ctx, expected, nameHint);
6538
9294
  }
6539
9295
  }
6540
9296
  // R7d: a null-guarded chain condition — `x !== null && x.a > 0 ? x.a :
@@ -6564,38 +9320,46 @@ export class Emitter {
6564
9320
  this.withSubsts(guards, ctx, () =>
6565
9321
  this.withKindNarrows(kindGuards, ctx, () => this.emitExpr(e, sub, want).code),
6566
9322
  );
9323
+ // Each arm probes and emits from the ENTRY state, kills joining
9324
+ // after the last arm (see childCtx's isolation law).
9325
+ const probeJoin = new Set<string>();
6567
9326
  const thenSub2 = this.childCtx(ctx);
6568
- const thenCode = isAnd
9327
+ const thenCode = this.withNarrowScope(ctx, "merge", () => isAnd
6569
9328
  ? emitNarrowed(thenSub2, expr.whenTrue, narrowedExpected)
6570
- : this.emitExpr(expr.whenTrue, thenSub2, expected ? unwrapOptional(expected) : expected).code;
9329
+ : this.emitExpr(expr.whenTrue, thenSub2, expected ? unwrapOptional(expected) : expected).code, probeJoin);
6571
9330
  const elseSub2 = this.childCtx(ctx);
6572
- const elseCode = isAnd
9331
+ const elseCode = this.withNarrowScope(ctx, "merge", () => isAnd
6573
9332
  ? this.emitExpr(expr.whenFalse, elseSub2, expected).code
6574
- : emitNarrowed(elseSub2, expr.whenFalse, expected);
9333
+ : emitNarrowed(elseSub2, expr.whenFalse, expected), probeJoin);
6575
9334
  if (thenSub2.lines.length === 0 && elseSub2.lines.length === 0) {
9335
+ // The probes ARE the emission here: their kills are the join.
9336
+ this.applyJoinedNarrowKills(ctx, probeJoin);
6576
9337
  return { code: `if (${condText}) ${thenCode} else ${elseCode}` };
6577
9338
  }
6578
9339
  // A branch needing lowered statements: re-emit each into a nested
6579
9340
  // block assigning a named temp (the R17b lowering the plain
6580
- // conditional path uses).
9341
+ // conditional path uses). probeJoin is discarded with the probe
9342
+ // lines — the re-emissions below record the real kills.
9343
+ const chainJoin = new Set<string>();
6581
9344
  const t2 = expected ?? this.zTypeOfExpr(expr, ctx);
6582
9345
  const name = this.freshName(ctx, nameHint ?? "value");
6583
9346
  this.push(ctx, `var ${name}: ${this.table.zigTypeRef(t2)} = undefined;`);
6584
9347
  this.push(ctx, `if (${condText}) {`);
6585
9348
  const nt = this.nestedCtx(ctx);
6586
- const ntCode = isAnd
9349
+ const ntCode = this.withNarrowScope(ctx, "merge", () => isAnd
6587
9350
  ? emitNarrowed(nt, expr.whenTrue, narrowedExpected)
6588
- : this.emitExpr(expr.whenTrue, nt, expected ? unwrapOptional(expected) : expected).code;
9351
+ : this.emitExpr(expr.whenTrue, nt, expected ? unwrapOptional(expected) : expected).code, chainJoin);
6589
9352
  nt.lines.push(" ".repeat(nt.indent) + `${name} = ${ntCode};`);
6590
9353
  ctx.lines.push(...nt.lines);
6591
9354
  this.push(ctx, `} else {`);
6592
9355
  const ne = this.nestedCtx(ctx);
6593
- const neCode = isAnd
9356
+ const neCode = this.withNarrowScope(ctx, "merge", () => isAnd
6594
9357
  ? this.emitExpr(expr.whenFalse, ne, expected).code
6595
- : emitNarrowed(ne, expr.whenFalse, expected);
9358
+ : emitNarrowed(ne, expr.whenFalse, expected), chainJoin);
6596
9359
  ne.lines.push(" ".repeat(ne.indent) + `${name} = ${neCode};`);
6597
9360
  ctx.lines.push(...ne.lines);
6598
9361
  this.push(ctx, `}`);
9362
+ this.applyJoinedNarrowKills(ctx, chainJoin);
6599
9363
  return { code: name };
6600
9364
  }
6601
9365
  }
@@ -6604,36 +9368,115 @@ export class Emitter {
6604
9368
  // R13c: kind guards narrow the branch TS narrows, in ternaries too.
6605
9369
  const posGuard = this.kindGuardOf(cond);
6606
9370
  const negGuard = this.kindGuardOf(cond, ts.SyntaxKind.ExclamationEqualsEqualsToken);
6607
- // Branches that need lowered statements (spreads): lower via a named temp.
9371
+ // Branches that need lowered statements (spreads): lower via a named
9372
+ // temp. Each arm probes and emits from the ENTRY state, kills joining
9373
+ // after the last arm (see childCtx's isolation law).
9374
+ const probeJoin = new Set<string>();
6608
9375
  const thenSub = this.childCtx(ctx);
6609
- const thenV = this.withKindNarrow(posGuard, ctx, () =>
9376
+ const thenV = this.withNarrowScope(ctx, "merge", () => this.withKindNarrow(posGuard, ctx, () =>
6610
9377
  this.emitExpr(expr.whenTrue, thenSub, expected ? unwrapOptional(expected) : expected),
6611
- );
9378
+ ), probeJoin);
6612
9379
  const elseSub = this.childCtx(ctx);
6613
- const elseV = this.withKindNarrow(negGuard, ctx, () => this.emitExpr(expr.whenFalse, elseSub, expected));
9380
+ const elseV = this.withNarrowScope(ctx, "merge", () =>
9381
+ this.withKindNarrow(negGuard, ctx, () => this.emitExpr(expr.whenFalse, elseSub, expected)), probeJoin);
6614
9382
  // The condition is evaluated exactly once, so it may lower statements
6615
9383
  // (array-method scans) into the surrounding ctx ahead of the branch.
6616
9384
  const condText = this.emitExpr(cond, ctx, { k: "bool" }).code;
6617
9385
  if (thenSub.lines.length === 0 && elseSub.lines.length === 0) {
9386
+ // The probes ARE the emission here: their kills are the join.
9387
+ this.applyJoinedNarrowKills(ctx, probeJoin);
6618
9388
  return { code: `if (${condText}) ${thenV.code} else ${elseV.code}` };
6619
9389
  }
6620
- // R17b-style lowering into an assignment target.
9390
+ // R17b-style lowering into an assignment target. probeJoin is discarded
9391
+ // with the probe lines — the re-emissions record the real kills.
9392
+ const join = new Set<string>();
6621
9393
  const t = expected ?? this.zTypeOfExpr(expr, ctx);
6622
9394
  const name = this.freshName(ctx, nameHint ?? "value");
6623
9395
  this.push(ctx, `var ${name}: ${this.table.zigTypeRef(t)} = undefined;`);
6624
9396
  this.push(ctx, `if (${condText}) {`);
6625
9397
  const ts1 = this.nestedCtx(ctx);
6626
- const v1 = this.withKindNarrow(posGuard, ctx, () =>
9398
+ const v1 = this.withNarrowScope(ctx, "merge", () => this.withKindNarrow(posGuard, ctx, () =>
6627
9399
  this.emitExpr(expr.whenTrue, ts1, expected ? unwrapOptional(expected) : expected),
6628
- );
9400
+ ), join);
6629
9401
  ts1.lines.push(" ".repeat(ts1.indent) + `${name} = ${v1.code};`);
6630
9402
  ctx.lines.push(...ts1.lines);
6631
9403
  this.push(ctx, `} else {`);
6632
9404
  const ts2 = this.nestedCtx(ctx);
6633
- const v2 = this.withKindNarrow(negGuard, ctx, () => this.emitExpr(expr.whenFalse, ts2, expected));
9405
+ const v2 = this.withNarrowScope(ctx, "merge", () =>
9406
+ this.withKindNarrow(negGuard, ctx, () => this.emitExpr(expr.whenFalse, ts2, expected)), join);
6634
9407
  ts2.lines.push(" ".repeat(ts2.indent) + `${name} = ${v2.code};`);
6635
9408
  ctx.lines.push(...ts2.lines);
6636
9409
  this.push(ctx, `}`);
9410
+ this.applyJoinedNarrowKills(ctx, join);
9411
+ return { code: name };
9412
+ }
9413
+
9414
+ /// R7-narrowed ternary: `if (target) |cap| <narrowed> else <other>`, with
9415
+ /// the capture substitution active over the arm TS narrows. Arms whose
9416
+ /// emission lowers statements (a spread literal builds its arena copy
9417
+ /// line by line; a nested lowered ternary needs its temp) cannot ride an
9418
+ /// if-EXPRESSION arm — the pushed lines would land above the conditional,
9419
+ /// running BOTH arms unconditionally and reading the capture before it
9420
+ /// binds. Those take the R17b statement lowering instead: a typed temp
9421
+ /// assigned under a statement if/else, so exactly the taken arm's
9422
+ /// statements run, once.
9423
+ private emitNarrowedTernary(
9424
+ expr: ts.ConditionalExpression,
9425
+ targetExpr: ts.Expression,
9426
+ narrowedArm: ts.Expression,
9427
+ otherArm: ts.Expression,
9428
+ ctx: Ctx,
9429
+ expected: ZType | undefined,
9430
+ nameHint: string | undefined,
9431
+ ): Emitted {
9432
+ // The callers gate on a read of the target (anyReadsTarget), which a
9433
+ // keyless target can never satisfy — the key is present here.
9434
+ const key = this.narrowKey(targetExpr)!;
9435
+ const target = this.emitExpr(targetExpr, ctx).code;
9436
+ const cap = this.freshName(ctx, this.narrowHint(targetExpr));
9437
+ const emitNarrowedArm = (sub: Ctx): string => {
9438
+ const saved = ctx.memberSubst.get(key);
9439
+ ctx.memberSubst.set(key, cap);
9440
+ const code = this.emitExpr(narrowedArm, sub, expected ? unwrapOptional(expected) : undefined).code;
9441
+ ctx.memberSubst.delete(key);
9442
+ if (saved !== undefined) ctx.memberSubst.set(key, saved);
9443
+ return code;
9444
+ };
9445
+ // Probe both arms in throwaway child ctxs: statement-free arms keep
9446
+ // the tight expression form (the common case — numbers, tags, field
9447
+ // reads — stays exactly as before). Each arm probes and emits from the
9448
+ // ENTRY state, kills joining after the last arm (see childCtx's
9449
+ // isolation law).
9450
+ const probeJoin = new Set<string>();
9451
+ const narrowedSub = this.childCtx(ctx);
9452
+ const narrowedV = this.withNarrowScope(ctx, "merge", () => emitNarrowedArm(narrowedSub), probeJoin);
9453
+ const otherSub = this.childCtx(ctx);
9454
+ const otherV = this.withNarrowScope(ctx, "merge", () => this.emitExpr(otherArm, otherSub, expected).code, probeJoin);
9455
+ if (narrowedSub.lines.length === 0 && otherSub.lines.length === 0) {
9456
+ // The probes ARE the emission here: their kills are the join.
9457
+ this.applyJoinedNarrowKills(ctx, probeJoin);
9458
+ return { code: `if (${target}) |${cap}| ${narrowedV} else ${otherV}` };
9459
+ }
9460
+ // R17b-style lowering: re-emit each arm into its own scoped block
9461
+ // feeding the temp (the probe lines are discarded — they were never
9462
+ // pushed to ctx, and probeJoin drops with them; the re-emissions
9463
+ // record the real kills).
9464
+ const join = new Set<string>();
9465
+ const t = expected ?? this.zTypeOfExpr(expr, ctx);
9466
+ const name = this.freshName(ctx, nameHint ?? "value");
9467
+ this.push(ctx, `var ${name}: ${this.table.zigTypeRef(t)} = undefined;`);
9468
+ this.push(ctx, `if (${target}) |${cap}| {`);
9469
+ const ts1 = this.nestedCtx(ctx);
9470
+ const v1 = this.withNarrowScope(ctx, "merge", () => emitNarrowedArm(ts1), join);
9471
+ ts1.lines.push(" ".repeat(ts1.indent) + `${name} = ${v1};`);
9472
+ ctx.lines.push(...ts1.lines);
9473
+ this.push(ctx, `} else {`);
9474
+ const ts2 = this.nestedCtx(ctx);
9475
+ const v2 = this.withNarrowScope(ctx, "merge", () => this.emitExpr(otherArm, ts2, expected).code, join);
9476
+ ts2.lines.push(" ".repeat(ts2.indent) + `${name} = ${v2};`);
9477
+ ctx.lines.push(...ts2.lines);
9478
+ this.push(ctx, `}`);
9479
+ this.applyJoinedNarrowKills(ctx, join);
6637
9480
  return { code: name };
6638
9481
  }
6639
9482
 
@@ -7277,7 +10120,16 @@ export class Emitter {
7277
10120
  const cap = this.freshName(ctx, hint);
7278
10121
  const sub = this.nestedCtx(ctx);
7279
10122
  sub.memberSubst = new Map(ctx.memberSubst);
7280
- sub.memberSubst.set(normalize(recv), cap);
10123
+ // The rewrite targets exactly this receiver NODE (emitCall re-emits
10124
+ // it under the capture). A receiver without a canonical narrowing key
10125
+ // still needs the rewrite, so it gets a node-scoped key — unique to
10126
+ // the node, never a narrowing fact another occurrence could match.
10127
+ let recvKey = this.narrowKey(recv);
10128
+ if (recvKey === null) {
10129
+ recvKey = `@recv#${this.narrowKeyNextId++}`;
10130
+ this.nodeNarrowKeys.set(recv, recvKey);
10131
+ }
10132
+ sub.memberSubst.set(recvKey, cap);
7281
10133
  const inner = this.emitCall(expr, sub, undefined, nameHint);
7282
10134
  const resT = this.zTypeOfExprClassed(expr, sub);
7283
10135
  if (resT.k === "void") this.fail(expr, `optional-chain call .${callee.name.text} without a mapped value type`);
@@ -7309,11 +10161,27 @@ export class Emitter {
7309
10161
  );
7310
10162
  }
7311
10163
  const body = cb.body.statements;
10164
+ // Every exit is terminal (a constant-true loop, or throws) with no
10165
+ // `return v` anywhere: tsc types the body `never`, but the labeled
10166
+ // value block below would carry a label no `break` uses — a Zig
10167
+ // compile error — and a callback that can never produce its value has
10168
+ // no useful emission anyway.
10169
+ if (!body.some((s) => containsReturn(s))) {
10170
+ this.fail(cb, "a callback none of whose paths returns a value (every path loops forever or throws)");
10171
+ }
7312
10172
  const last = body[body.length - 1];
7313
10173
  const earlyReturns = body.slice(0, -1).some((s) => containsReturn(s));
7314
10174
  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;
10175
+ // The prefix's guards narrow the trailing return's expression, so both
10176
+ // emit inside ONE flow scope — a scope around the prefix alone would
10177
+ // restore the maps before the expression they guard. The restore still
10178
+ // runs before the caller continues, so the callback's narrowing never
10179
+ // reaches its siblings in the emitted loop body.
10180
+ const trailing = last.expression;
10181
+ return this.withNarrowScope(sub, "merge", () => {
10182
+ this.emitStatementList(body.slice(0, -1), sub);
10183
+ return this.emitExpr(trailing, sub, expected).code;
10184
+ });
7317
10185
  }
7318
10186
  const label = this.freshName(sub, "cb");
7319
10187
  const name = this.freshName(sub, hint);
@@ -7323,9 +10191,15 @@ export class Emitter {
7323
10191
  inner.cmdReturn = null;
7324
10192
  inner.subReturn = null;
7325
10193
  inner.returnType = expected;
7326
- this.emitBlockStatements(body, inner);
10194
+ // The callback edge-kill stage: an arm that kills a narrow and then
10195
+ // `return`s exits along the lowered `break :label` edge, whose
10196
+ // destination is the continuation AFTER this value block — so its
10197
+ // kills apply here, once the block closes, and the arm's siblings and
10198
+ // the trailing in-callback flow keep the narrows tsc keeps there.
10199
+ const kills = this.stagedEdgeKills(sub, "callback", null, () => this.emitBlockStatements(body, inner));
7327
10200
  sub.lines.push(...inner.lines);
7328
10201
  this.push(sub, `};`);
10202
+ this.applyJoinedNarrowKills(sub, kills);
7329
10203
  return name;
7330
10204
  }
7331
10205
 
@@ -8111,8 +10985,15 @@ export class Emitter {
8111
10985
  const t = this.zTypeOfExprRaw(expr, ctx);
8112
10986
  // A narrowing substitution (null-guard capture or `.?` unwrap) proves
8113
10987
  // 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;
10988
+ // effective type is the inner one. A RENAMING substitution — a union
10989
+ // payload capture whose field is itself optional — holds the payload
10990
+ // as-is and must keep the optional (stillOptionalSubst records those
10991
+ // by their exact replacement).
10992
+ if (t.k === "optional") {
10993
+ const key = this.narrowKey(expr);
10994
+ const rep = key === null ? undefined : ctx.memberSubst.get(key);
10995
+ if (key !== null && rep !== undefined && rep !== ctx.stillOptionalSubst.get(key)) return t.inner;
10996
+ }
8116
10997
  return t;
8117
10998
  }
8118
10999
 
@@ -8275,19 +11156,41 @@ export class Emitter {
8275
11156
  return ctx.thisType ?? { k: "void" };
8276
11157
  }
8277
11158
  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);
11159
+ // An empty branch — `null` or the global `undefined` — makes the
11160
+ // ternary's VALUE optional (`hit === undefined ? null : hit.at` is
11161
+ // `?i64`, not `i64`; `q === null ? undefined : q` stays `?P`) —
11162
+ // dropping it here would type locals non-optional and break every
11163
+ // later null test on them.
11164
+ const trueEmpty = this.isEmptyLiteral(expr.whenTrue);
11165
+ const falseEmpty = this.isEmptyLiteral(expr.whenFalse);
11166
+ if (trueEmpty && falseEmpty) return { k: "void" };
11167
+ if (trueEmpty || falseEmpty) {
11168
+ const t = this.zTypeOfExpr(trueEmpty ? expr.whenFalse : expr.whenTrue, ctx);
8286
11169
  return t.k === "optional" || t.k === "void" ? t : { k: "optional", inner: t };
8287
11170
  }
11171
+ // The condition's own null test narrows the arm that reuses the
11172
+ // tested value, exactly as tsc types it: `q === null ? {...f} : q`
11173
+ // and `q !== null ? q : {...f}` both VALUE as the non-optional Quote,
11174
+ // never `?Quote` — keeping the raw optional here types an inferred
11175
+ // local `?Quote` and its first non-optional use fails to compile.
11176
+ // The unwrap only holds when the OTHER arm cannot contribute null:
11177
+ // a known-optional other arm keeps the optional (its null flows
11178
+ // through), and the empty-literal arms (`null`/`undefined`, wrapped
11179
+ // or bare, in either position) were handled above.
11180
+ const missTest = this.emptyTestOf(expr.condition);
11181
+ const hitTest = this.emptyTestOf(expr.condition, ts.SyntaxKind.ExclamationEqualsEqualsToken);
11182
+ const narrowedByCond = (arm: ts.Expression, t: ZType, other: ts.Expression): ZType => {
11183
+ const test = arm === expr.whenFalse ? missTest : hitTest;
11184
+ if (test === null || t.k !== "optional") return t;
11185
+ const armKey = this.narrowKey(arm);
11186
+ if (armKey === null || armKey !== this.narrowKey(test.target)) return t;
11187
+ const otherT = this.zTypeOfExpr(other, ctx);
11188
+ return otherT.k === "optional" ? t : t.inner;
11189
+ };
8288
11190
  const t = this.zTypeOfExpr(expr.whenTrue, ctx);
8289
- if (t.k !== "void") return t;
8290
- return this.zTypeOfExpr(expr.whenFalse, ctx);
11191
+ if (t.k !== "void") return narrowedByCond(expr.whenTrue, t, expr.whenFalse);
11192
+ const f = this.zTypeOfExpr(expr.whenFalse, ctx);
11193
+ return narrowedByCond(expr.whenFalse, f, expr.whenTrue);
8291
11194
  }
8292
11195
  if (ts.isBinaryExpression(expr)) {
8293
11196
  const op = expr.operatorToken.kind;
@@ -8747,6 +11650,16 @@ function f64Literal(v: number): string {
8747
11650
  return /[.eE]/.test(s) ? s : `${s}.0`;
8748
11651
  }
8749
11652
 
11653
+ /// The UTF-8 byte length of literal text. The wire's length prefixes
11654
+ /// count BYTES, and the emitted Zig string literal carries the text as
11655
+ /// UTF-8, so every gate on a literal must count bytes too: `.length`
11656
+ /// counts UTF-16 code units and would pass a 200-character CJK name
11657
+ /// that arrives as 600 bytes, straight past the teaching and into the
11658
+ /// runtime's 255-byte length prefix.
11659
+ function utf8ByteLength(s: string): number {
11660
+ return Buffer.byteLength(s, "utf8");
11661
+ }
11662
+
8750
11663
  function escapeZigString(s: string): string {
8751
11664
  let out = "";
8752
11665
  for (const ch of s) {
@@ -8760,8 +11673,18 @@ function escapeZigString(s: string): string {
8760
11673
  return out;
8761
11674
  }
8762
11675
 
8763
- function normalize(expr: ts.Node): string {
8764
- return expr.getText().replace(/\s+/g, "");
11676
+ /// A block statement sitting directly in a statement list — a plain lexical
11677
+ /// block, where control always falls straight through. Everything else a
11678
+ /// Block can be (an if/else arm, a loop or callback body, a try/catch
11679
+ /// block, a labeled statement's body) is a merge context: control JOINS at
11680
+ /// its exit, so narrowing must bracket it there.
11681
+ function isPlainLexicalBlock(b: ts.Block): boolean {
11682
+ return (
11683
+ ts.isBlock(b.parent) ||
11684
+ ts.isSourceFile(b.parent) ||
11685
+ ts.isCaseClause(b.parent) ||
11686
+ ts.isDefaultClause(b.parent)
11687
+ );
8765
11688
  }
8766
11689
 
8767
11690
  function unwrapOptional(t: ZType): ZType {