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