@native-sdk/cli 0.4.4 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/build/app.zig +187 -6
  2. package/build/ts_run.mjs +63 -0
  3. package/build.zig +213 -1
  4. package/build.zig.zon +1 -0
  5. package/package.json +15 -10
  6. package/packages/core/package-lock.json +43 -0
  7. package/packages/core/package.json +37 -0
  8. package/packages/core/rt/rt.zig +1579 -0
  9. package/packages/core/sdk/bytes_text_methods.d.ts +88 -0
  10. package/packages/core/sdk/core.ts +694 -0
  11. package/packages/core/sdk/events.ts +137 -0
  12. package/packages/core/sdk/text.ts +519 -0
  13. package/packages/core/src/checker.ts +1869 -0
  14. package/packages/core/src/cli.ts +68 -0
  15. package/packages/core/src/devhost.ts +291 -0
  16. package/packages/core/src/devhost_resolver.mjs +22 -0
  17. package/packages/core/src/diagnostics.ts +417 -0
  18. package/packages/core/src/emitter.ts +8815 -0
  19. package/packages/core/src/infer.ts +1515 -0
  20. package/packages/core/src/modules.ts +173 -0
  21. package/packages/core/src/ownership.ts +740 -0
  22. package/packages/core/src/text_polyfill.ts +337 -0
  23. package/packages/core/src/text_tables.ts +408 -0
  24. package/packages/core/src/transpile.ts +146 -0
  25. package/packages/core/src/typed_ast.ts +536 -0
  26. package/packages/core/src/types.ts +815 -0
  27. package/skill-data/native-ui/SKILL.md +14 -0
  28. package/skill-data/ts-core/SKILL.md +493 -0
  29. package/skill-data/zig/SKILL.md +10 -0
  30. package/src/app_runner/root.zig +24 -0
  31. package/src/app_runner/ts_core_main.zig +231 -0
  32. package/src/primitives/app_manifest/comptime_scene.zig +341 -0
  33. package/src/primitives/app_manifest/root.zig +5 -0
  34. package/src/primitives/canvas/commands.zig +14 -7
  35. package/src/primitives/canvas/lazy_tls.zig +73 -0
  36. package/src/primitives/canvas/render_generic_resources.zig +22 -15
  37. package/src/primitives/canvas/root.zig +6 -0
  38. package/src/primitives/canvas/tests.zig +1 -0
  39. package/src/primitives/canvas/text_atlas.zig +40 -32
  40. package/src/primitives/canvas/text_layout_cache.zig +29 -22
  41. package/src/primitives/canvas/text_measure_cache.zig +56 -41
  42. package/src/primitives/canvas/text_spans.zig +39 -26
  43. package/src/primitives/canvas/tokens.zig +54 -0
  44. package/src/primitives/canvas/ui.zig +125 -0
  45. package/src/primitives/canvas/ui_markup.zig +22 -3
  46. package/src/primitives/canvas/ui_markup_compiled.zig +97 -7
  47. package/src/primitives/canvas/ui_markup_compiled_tests.zig +275 -0
  48. package/src/primitives/canvas/ui_markup_contract.zig +68 -14
  49. package/src/primitives/canvas/ui_markup_contract_tests.zig +257 -2
  50. package/src/primitives/canvas/ui_markup_reflect.zig +214 -0
  51. package/src/primitives/canvas/ui_markup_view.zig +105 -1
  52. package/src/primitives/canvas/ui_markup_view_tests.zig +336 -0
  53. package/src/primitives/canvas/ui_schema.zig +8 -0
  54. package/src/primitives/canvas/ui_schema_tests.zig +5 -4
  55. package/src/primitives/canvas/widget_invalidation.zig +14 -7
  56. package/src/primitives/canvas/widget_render.zig +25 -15
  57. package/src/primitives/canvas/widget_render_controls.zig +15 -9
  58. package/src/primitives/canvas/widget_runtime_tests.zig +44 -0
  59. package/src/root.zig +7 -0
  60. package/src/runtime/canvas_frame.zig +57 -36
  61. package/src/runtime/canvas_images.zig +9 -3
  62. package/src/runtime/canvas_widget_control_tests.zig +5 -6
  63. package/src/runtime/canvas_widget_runtime.zig +7 -4
  64. package/src/runtime/effects.zig +490 -2
  65. package/src/runtime/effects_host_tests.zig +594 -0
  66. package/src/runtime/root.zig +18 -0
  67. package/src/runtime/session_replay.zig +7 -1
  68. package/src/runtime/tests.zig +2 -0
  69. package/src/runtime/ts_core_host.zig +1505 -0
  70. package/src/runtime/ts_core_host_tests.zig +1408 -0
  71. package/src/runtime/ts_ui_app.zig +469 -0
  72. package/src/runtime/ui_app.zig +58 -0
  73. package/src/runtime/view_canvas.zig +24 -17
  74. package/src/runtime/view_widget_tree.zig +2 -2
  75. package/src/tooling/codesign.zig +212 -105
  76. package/src/tooling/doctor.zig +78 -0
  77. package/src/tooling/manifest.zig +47 -0
  78. package/src/tooling/package.zig +124 -12
  79. package/src/tooling/raw_manifest.zig +15 -0
  80. package/src/tooling/root.zig +1 -0
  81. package/src/tooling/templates.zig +683 -28
  82. package/src/tooling/ts_core.zig +486 -0
  83. package/src/tooling/verbs.zig +17 -0
@@ -0,0 +1,1515 @@
1
+ // R2 integer inference: JS semantics are f64 everywhere, but the emitter may
2
+ // use i64 wherever that is unobservable. A `number` slot (const, local, param,
3
+ // field, return) is emitted as i64 when:
4
+ //
5
+ // - it is PROVEN integer: every value flowing in is integer-valued
6
+ // (integer literals, lengths, byte reads, integer arithmetic), and the
7
+ // slot is not externally constructible; or
8
+ // - it is DEMANDED integer: some use requires an integer (memory index,
9
+ // bitwise op, equality with a proven-integer value), which is sound
10
+ // because f64 holds every integer the demand sites can produce exactly.
11
+ //
12
+ // Everything else stays f64, matching JS bit-for-bit. External slots are the
13
+ // app boundary: fields reachable from `Msg` and parameters of exported
14
+ // functions — the host may pass any f64 there, so proof never starts from
15
+ // them, only demand can claim them.
16
+ //
17
+ // A final demotion pass resolves mixed sites (e.g. `Math.max(K, x)` with x
18
+ // f64) by pushing undemanded integer slots to f64 so emitted arithmetic
19
+ // type-checks without casts. The same pass keeps every assignment edge
20
+ // same-typed by construction: a float-tainted slot demotes the undecided
21
+ // slots that flow into it, and a slot fed by a resolved-integer slot is
22
+ // demanded to match. When neither side can move — a fractional value flows
23
+ // into a slot some use forces to be an integer — that is a conflict reported
24
+ // as a teaching error (NS1016), never a downstream Zig type error.
25
+
26
+ import { ts, TypedAst } from "./typed_ast.ts";
27
+ import { constFunctionValue } from "./ownership.ts";
28
+ import { thrownShapeOf } from "./checker.ts";
29
+ import type { TypeTable } from "./types.ts";
30
+
31
+ /// The `return` expressions of a callback body, nested functions excluded —
32
+ /// the values a block-body callback can produce.
33
+ export function returnExpressionsOf(body: ts.Node): ts.Expression[] {
34
+ const out: ts.Expression[] = [];
35
+ const visit = (n: ts.Node): void => {
36
+ if (ts.isFunctionDeclaration(n) || ts.isArrowFunction(n) || ts.isFunctionExpression(n)) return;
37
+ if (ts.isReturnStatement(n) && n.expression) out.push(n.expression);
38
+ ts.forEachChild(n, visit);
39
+ };
40
+ visit(body);
41
+ return out;
42
+ }
43
+
44
+ /// Array methods whose callback carries the element index as its second
45
+ /// parameter in v1 (reduce's index is its third and stays unmapped).
46
+ export const indexCarryingMethods = new Set(["map", "filter", "find", "findIndex", "some", "every"]);
47
+
48
+ /// Array methods that accept a function-valued callback argument at all —
49
+ /// the positions where a bare reference to a module-level function inlines
50
+ /// like an arrow (`xs.map(encodeTurn)`).
51
+ export const callbackTakingMethods = new Set([
52
+ ...indexCarryingMethods,
53
+ "reduce",
54
+ "sort",
55
+ "toSorted",
56
+ "forEach",
57
+ "flatMap",
58
+ ]);
59
+
60
+ /// The receiver of `for (const [i, x] of xs.entries())` when the binding
61
+ /// element belongs to that loop form, else null.
62
+ function entriesLoopReceiver(el: ts.BindingElement): ts.Expression | null {
63
+ const pattern = el.parent;
64
+ if (!ts.isArrayBindingPattern(pattern)) return null;
65
+ const decl = pattern.parent;
66
+ if (!ts.isVariableDeclaration(decl) || !ts.isVariableDeclarationList(decl.parent)) return null;
67
+ const loop = decl.parent.parent;
68
+ if (!ts.isForOfStatement(loop)) return null;
69
+ let iter = loop.expression;
70
+ while (ts.isParenthesizedExpression(iter)) iter = iter.expression;
71
+ if (
72
+ !ts.isCallExpression(iter) ||
73
+ !ts.isPropertyAccessExpression(iter.expression) ||
74
+ iter.expression.name.text !== "entries"
75
+ ) {
76
+ return null;
77
+ }
78
+ return iter.expression.expression;
79
+ }
80
+
81
+ export interface Slot {
82
+ readonly decl: ts.Node;
83
+ readonly label: string;
84
+ external: boolean;
85
+ /// A number parameter of an exported function — the ABI boundary the host
86
+ /// calls across. Genuine integer demand (index/bitwise chains) may still
87
+ /// claim it to i64 (the emitted signature IS the contract type), but a
88
+ /// mere comparison must not: the host may pass any f64, and an i64-claimed
89
+ /// signature would truncate what node would compare exactly.
90
+ hostBoundary: boolean;
91
+ float: boolean;
92
+ proven: boolean;
93
+ demanded: boolean;
94
+ /// The demand is TENTATIVE — claimed only so a comparison's two sides
95
+ /// land same-typed, never by a genuine integer requirement (index,
96
+ /// bitwise, size). A tentative claim yields when float later reaches the
97
+ /// slot: it demotes to f64 and the comparison widens, instead of
98
+ /// reporting a manufactured NS1016 conflict. Hard demand (`demandSlot`
99
+ /// with viaComparison=false) upgrades and clears this.
100
+ comparisonDemanded: boolean;
101
+ readonly inflows: Contribution[];
102
+ }
103
+
104
+ export interface Contribution {
105
+ readonly slots: Slot[];
106
+ /// A fractional literal, division, or other definitely-float source.
107
+ float: boolean;
108
+ /// A source the analysis cannot classify (kills proof, not demand).
109
+ unknown: boolean;
110
+ /// At least one definitely-integer source (literal, length, byte read).
111
+ intSource: boolean;
112
+ /// The expression the contribution was read from (conflict reporting).
113
+ readonly site: ts.Expression;
114
+ }
115
+
116
+ interface CompareSite {
117
+ readonly left: Contribution;
118
+ readonly right: Contribution;
119
+ }
120
+
121
+ /// An assignment or mix the fixed point could not make same-typed: a
122
+ /// fractional value meets a slot that some use forces to stay an integer.
123
+ export interface IntFloatConflict {
124
+ readonly node: ts.Node;
125
+ /// The integer-forced slot's source name, for the teaching message.
126
+ readonly slotLabel: string;
127
+ }
128
+
129
+ export class IntInference {
130
+ private readonly slots = new Map<ts.Node, Slot>();
131
+ private readonly compareSites: CompareSite[] = [];
132
+ private readonly mixSites: CompareSite[] = [];
133
+ private readonly demandSeeds: Contribution[] = [];
134
+ readonly conflicts: IntFloatConflict[] = [];
135
+
136
+ private readonly tast: TypedAst;
137
+ private readonly table: TypeTable;
138
+ /// The core's modules in canonical order; files[0] is the entry. Slots
139
+ /// and flows span all of them — declarationOf resolves across files, so
140
+ /// a call from core.ts into parsers.ts wires argument flows into the
141
+ /// callee's parameter slots exactly like a same-file call.
142
+ private readonly files: readonly ts.SourceFile[];
143
+ private readonly fileSet: Set<ts.SourceFile>;
144
+
145
+ constructor(tast: TypedAst, table: TypeTable, files: readonly ts.SourceFile[] | ts.SourceFile) {
146
+ this.tast = tast;
147
+ this.table = table;
148
+ this.files = Array.isArray(files) ? files : [files as ts.SourceFile];
149
+ this.fileSet = new Set(this.files);
150
+ this.collectCallbackReferencedFns();
151
+ this.collectSlots();
152
+ this.markExternal();
153
+ this.collectFlows();
154
+ this.resolve();
155
+ }
156
+
157
+ // ------------------------------------------------------------- slot setup
158
+
159
+ /// Module-level function declarations referenced BARE as an array-method
160
+ /// callback (`xs.map(encodeTurn)`). Their bodies inline at the use site
161
+ /// like arrows, so their number parameters read number-array elements —
162
+ /// always f64 (R2 covers slots, not elements) — and must classify like
163
+ /// arrow captures, not like ordinary called parameters.
164
+ private readonly callbackReferencedFns = new Set<ts.FunctionDeclaration>();
165
+
166
+ private collectCallbackReferencedFns(): void {
167
+ const visit = (node: ts.Node): void => {
168
+ if (
169
+ ts.isCallExpression(node) &&
170
+ ts.isPropertyAccessExpression(node.expression) &&
171
+ callbackTakingMethods.has(node.expression.name.text)
172
+ ) {
173
+ for (const arg of node.arguments) {
174
+ if (!ts.isIdentifier(arg)) continue;
175
+ const decl = this.tast.declarationOf(arg);
176
+ if (decl && ts.isFunctionDeclaration(decl)) this.callbackReferencedFns.add(decl);
177
+ }
178
+ }
179
+ ts.forEachChild(node, visit);
180
+ };
181
+ for (const f of this.files) visit(f);
182
+ }
183
+
184
+ private numberish(node: ts.TypeNode | undefined): boolean {
185
+ if (!node) return false;
186
+ const t = this.table.resolveTypeNode(node);
187
+ return t.k === "number" || (t.k === "optional" && t.inner.k === "number");
188
+ }
189
+
190
+ private addSlot(decl: ts.Node, label: string): void {
191
+ if (!this.slots.has(decl)) {
192
+ this.slots.set(decl, {
193
+ decl,
194
+ label,
195
+ external: false,
196
+ hostBoundary: false,
197
+ float: false,
198
+ proven: true,
199
+ demanded: false,
200
+ comparisonDemanded: false,
201
+ inflows: [],
202
+ });
203
+ }
204
+ }
205
+
206
+ /// A slot that starts float: array-callback captures read number-array
207
+ /// elements, which are always emitted f64 (R2 covers slots, not elements).
208
+ /// A body that demands an integer from one is an NS1016 conflict.
209
+ private addFloatSlot(decl: ts.Node, label: string): void {
210
+ if (!this.slots.has(decl)) {
211
+ this.slots.set(decl, {
212
+ decl,
213
+ label,
214
+ external: false,
215
+ hostBoundary: false,
216
+ float: true,
217
+ proven: false,
218
+ demanded: false,
219
+ comparisonDemanded: false,
220
+ inflows: [],
221
+ });
222
+ }
223
+ }
224
+
225
+ private collectSlots(): void {
226
+ // Untyped `const x = <numeric expr>` locals detect numeric-ness by
227
+ // READING other slots (numericInit), so they resolve on a second,
228
+ // fixpoint pass: with multiple files a referenced field or function
229
+ // slot may be declared in a file visited later.
230
+ const untypedLocals: ts.VariableDeclaration[] = [];
231
+ const visit = (node: ts.Node): void => {
232
+ if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name)) {
233
+ const list = node.parent;
234
+ if (ts.isVariableDeclarationList(list) && ts.isForOfStatement(list.parent)) {
235
+ // for...of bindings: byte elements are integer reads, number-array
236
+ // elements are f64 (R2 covers slots, not elements) — the same split
237
+ // as array-callback captures below.
238
+ const numberTyped = (this.tast.typeOf(node.name).flags & ts.TypeFlags.Number) !== 0;
239
+ if (numberTyped) {
240
+ if (this.tast.isBytesTyped(list.parent.expression)) this.addSlot(node, node.name.text);
241
+ else this.addFloatSlot(node, node.name.text);
242
+ }
243
+ } else if (this.numberish(node.type)) {
244
+ this.addSlot(node, node.name.text);
245
+ } else if (!node.type && node.initializer) {
246
+ untypedLocals.push(node);
247
+ }
248
+ } else if (ts.isParameter(node) && ts.isIdentifier(node.name)) {
249
+ if (ts.isArrowFunction(node.parent)) {
250
+ const numberTyped = node.type
251
+ ? this.numberish(node.type)
252
+ : (this.tast.typeOf(node.name).flags & ts.TypeFlags.Number) !== 0;
253
+ if (numberTyped) {
254
+ // A reduce accumulator is a real slot — it receives the initial
255
+ // value and the body result (flows wired in collectFlows), so R2
256
+ // resolves its class like any local. An array-callback index
257
+ // parameter is the loop index, a proven integer. Element
258
+ // captures stay f64.
259
+ if (this.isReduceAccumulator(node.parent, node) || this.isCallbackIndexParam(node.parent, node)) {
260
+ this.addSlot(node, node.name.text);
261
+ } else {
262
+ this.addFloatSlot(node, node.name.text);
263
+ }
264
+ }
265
+ } else if (ts.isFunctionExpression(node.parent)) {
266
+ // A hoisted function-expression helper's number params are
267
+ // f64 like arrow captures — call flows are not wired, so the
268
+ // conservative JS-faithful class is the sound one.
269
+ if (this.numberish(node.type)) this.addFloatSlot(node, node.name.text);
270
+ } else if (ts.isFunctionDeclaration(node.parent) && this.callbackReferencedFns.has(node.parent)) {
271
+ // A module fn referenced bare as a callback inlines at that use
272
+ // site: its number params read array elements, which are f64.
273
+ if (this.numberish(node.type)) this.addFloatSlot(node, node.name.text);
274
+ } else if (this.numberish(node.type)) {
275
+ this.addSlot(node, node.name.text);
276
+ }
277
+ } else if (ts.isPropertySignature(node) && node.name && ts.isIdentifier(node.name)) {
278
+ if (this.numberish(node.type)) this.addSlot(node, node.name.text);
279
+ } else if (ts.isPropertyDeclaration(node) && node.name && ts.isIdentifier(node.name)) {
280
+ // R19: a class field is a slot like a record field, fed by its
281
+ // initializer and by `this.x = ...` writes (wired in collectFlows).
282
+ // An UNTYPED `static readonly K = 9` is a module const in class
283
+ // clothing: numeric-ness comes from its foldable initializer, like
284
+ // untyped module-const locals.
285
+ if (this.numberish(node.type)) this.addSlot(node, node.name.text);
286
+ else if (!node.type && node.initializer && this.tast.constEvalNumber(node.initializer) !== null) {
287
+ this.addSlot(node, node.name.text);
288
+ }
289
+ } else if (ts.isMethodDeclaration(node) && node.name && ts.isIdentifier(node.name)) {
290
+ if (this.numberish(node.type)) this.addSlot(node, `${node.name.text}()`);
291
+ } else if (ts.isFunctionDeclaration(node) && node.name) {
292
+ if (this.numberish(node.type)) this.addSlot(node, `${node.name.text}()`);
293
+ } else if (ts.isBindingElement(node) && ts.isIdentifier(node.name)) {
294
+ // `for (const [i, x] of xs.entries())`: the index is a proven
295
+ // integer (the loop index); the element splits like the plain
296
+ // for...of — byte reads are integers, number-array elements stay
297
+ // f64 (R2 covers slots, not elements).
298
+ const entriesRecv = entriesLoopReceiver(node);
299
+ if (entriesRecv !== null) {
300
+ const pattern = node.parent as ts.ArrayBindingPattern;
301
+ if (pattern.elements[0] === node) {
302
+ this.addSlot(node, node.name.text);
303
+ } else if ((this.tast.typeOf(node.name).flags & ts.TypeFlags.Number) !== 0) {
304
+ if (this.tast.isBytesTyped(entriesRecv)) this.addSlot(node, node.name.text);
305
+ else this.addFloatSlot(node, node.name.text);
306
+ }
307
+ ts.forEachChild(node, visit);
308
+ return;
309
+ }
310
+ // `const { total } = stats;` — a number-fielded binding is a real
311
+ // slot, classed by the field that feeds it (wired in collectFlows).
312
+ const f = this.destructuredField(node);
313
+ const ft = f?.type;
314
+ if (ft && (ft.k === "number" || (ft.k === "optional" && ft.inner.k === "number"))) {
315
+ this.addSlot(node, node.name.text);
316
+ }
317
+ }
318
+ ts.forEachChild(node, visit);
319
+ };
320
+ for (const file of this.files) visit(file);
321
+ // Fixpoint over the untyped locals: `const a = LIMIT` may reference a
322
+ // slot another untyped local (or a later file) introduces.
323
+ let added = true;
324
+ while (added) {
325
+ added = false;
326
+ for (const node of untypedLocals) {
327
+ if (this.slots.has(node)) continue;
328
+ if (this.numericInit(node.initializer!)) {
329
+ this.addSlot(node, (node.name as ts.Identifier).text);
330
+ added = true;
331
+ }
332
+ }
333
+ }
334
+ }
335
+
336
+ /// Untyped `const x = <numeric expr>` locals also get slots.
337
+ private numericInit(expr: ts.Expression): boolean {
338
+ if (ts.isParenthesizedExpression(expr)) return this.numericInit(expr.expression);
339
+ if (ts.isNumericLiteral(expr)) return true;
340
+ // `const z = (y = 5)`: the assignment's value is the number target's.
341
+ if (
342
+ ts.isBinaryExpression(expr) &&
343
+ ts.isIdentifier(expr.left) &&
344
+ (expr.operatorToken.kind === ts.SyntaxKind.EqualsToken ||
345
+ expr.operatorToken.kind === ts.SyntaxKind.PlusEqualsToken ||
346
+ expr.operatorToken.kind === ts.SyntaxKind.MinusEqualsToken ||
347
+ expr.operatorToken.kind === ts.SyntaxKind.AsteriskEqualsToken ||
348
+ expr.operatorToken.kind === ts.SyntaxKind.SlashEqualsToken ||
349
+ expr.operatorToken.kind === ts.SyntaxKind.PercentEqualsToken ||
350
+ expr.operatorToken.kind === ts.SyntaxKind.AsteriskAsteriskEqualsToken)
351
+ ) {
352
+ const decl = this.tast.declarationOf(expr.left);
353
+ return decl !== undefined && this.slots.has(decl);
354
+ }
355
+ // `const n = ++count` / `count++` value positions read a number slot.
356
+ if (
357
+ ts.isPostfixUnaryExpression(expr) ||
358
+ (ts.isPrefixUnaryExpression(expr) &&
359
+ (expr.operator === ts.SyntaxKind.PlusPlusToken || expr.operator === ts.SyntaxKind.MinusMinusToken))
360
+ ) {
361
+ return true;
362
+ }
363
+ if (
364
+ ts.isPrefixUnaryExpression(expr) &&
365
+ (expr.operator === ts.SyntaxKind.MinusToken ||
366
+ expr.operator === ts.SyntaxKind.PlusToken ||
367
+ expr.operator === ts.SyntaxKind.TildeToken)
368
+ ) {
369
+ return expr.operator === ts.SyntaxKind.TildeToken || this.numericInit(expr.operand);
370
+ }
371
+ if (ts.isBinaryExpression(expr)) {
372
+ switch (expr.operatorToken.kind) {
373
+ case ts.SyntaxKind.PlusToken:
374
+ case ts.SyntaxKind.MinusToken:
375
+ case ts.SyntaxKind.AsteriskToken:
376
+ case ts.SyntaxKind.SlashToken:
377
+ case ts.SyntaxKind.PercentToken:
378
+ case ts.SyntaxKind.AsteriskAsteriskToken:
379
+ case ts.SyntaxKind.AmpersandToken:
380
+ case ts.SyntaxKind.BarToken:
381
+ case ts.SyntaxKind.CaretToken:
382
+ case ts.SyntaxKind.LessThanLessThanToken:
383
+ case ts.SyntaxKind.GreaterThanGreaterThanToken:
384
+ case ts.SyntaxKind.GreaterThanGreaterThanGreaterThanToken:
385
+ return true;
386
+ case ts.SyntaxKind.QuestionQuestionToken:
387
+ // `model.cursor ?? 0` is a number when a branch is numeric.
388
+ return this.numericInit(expr.left) || this.numericInit(expr.right);
389
+ default:
390
+ return false;
391
+ }
392
+ }
393
+ if (ts.isCallExpression(expr)) {
394
+ // A reduce value is numeric when its initial value is (slot collection
395
+ // has not reached the accumulator parameter yet at this point).
396
+ if (
397
+ ts.isPropertyAccessExpression(expr.expression) &&
398
+ expr.expression.name.text === "reduce" &&
399
+ expr.arguments[1]
400
+ ) {
401
+ return this.numericInit(expr.arguments[1]);
402
+ }
403
+ const c = this.contribution(expr);
404
+ return c.slots.length > 0 || c.intSource || c.float;
405
+ }
406
+ if (ts.isPropertyAccessExpression(expr)) {
407
+ if (expr.name.text === "length") return true;
408
+ return this.slotOfName(expr.name) !== undefined;
409
+ }
410
+ if (ts.isIdentifier(expr)) {
411
+ const decl = this.tast.declarationOf(expr);
412
+ return decl !== undefined && this.slots.has(decl);
413
+ }
414
+ if (ts.isElementAccessExpression(expr)) return true;
415
+ if (ts.isConditionalExpression(expr)) {
416
+ return this.numericInit(expr.whenTrue) || this.numericInit(expr.whenFalse);
417
+ }
418
+ return false;
419
+ }
420
+
421
+ /// The record field a `const { a } = expr;` binding element reads,
422
+ /// resolved through the initializer's declared type — the table is keyed
423
+ /// by name, and NS1038 keeps type names unique across the core's files.
424
+ private destructuredField(el: ts.BindingElement): import("./types.ts").ZField | null {
425
+ const pattern = el.parent;
426
+ if (!ts.isObjectBindingPattern(pattern)) return null;
427
+ const varDecl = pattern.parent;
428
+ if (!ts.isVariableDeclaration(varDecl) || !varDecl.initializer) return null;
429
+ const t = this.tast.typeOf(varDecl.initializer);
430
+ const typeName = t.aliasSymbol?.name ?? t.symbol?.name;
431
+ const struct = typeName ? this.table.structs.get(typeName) : undefined;
432
+ const prop =
433
+ el.propertyName && ts.isIdentifier(el.propertyName)
434
+ ? el.propertyName.text
435
+ : ts.isIdentifier(el.name)
436
+ ? el.name.text
437
+ : null;
438
+ return struct?.fields.find((x) => x.tsName === prop) ?? null;
439
+ }
440
+
441
+ /// The second parameter of an arrow handed to an index-carrying array
442
+ /// method — the JS element index, a proven integer (the emitted loop
443
+ /// index widened to i64).
444
+ private isCallbackIndexParam(arrow: ts.ArrowFunction, param: ts.ParameterDeclaration): boolean {
445
+ if (arrow.parameters.length < 2 || arrow.parameters[1] !== param) return false;
446
+ const call = arrow.parent;
447
+ return (
448
+ ts.isCallExpression(call) &&
449
+ call.arguments[0] === arrow &&
450
+ ts.isPropertyAccessExpression(call.expression) &&
451
+ indexCarryingMethods.has(call.expression.name.text)
452
+ );
453
+ }
454
+
455
+ /// The first parameter of a two-parameter arrow handed to `.reduce`.
456
+ private isReduceAccumulator(arrow: ts.ArrowFunction, param: ts.ParameterDeclaration): boolean {
457
+ if (arrow.parameters.length !== 2 || arrow.parameters[0] !== param) return false;
458
+ const call = arrow.parent;
459
+ return (
460
+ ts.isCallExpression(call) &&
461
+ call.arguments[0] === arrow &&
462
+ ts.isPropertyAccessExpression(call.expression) &&
463
+ call.expression.name.text === "reduce"
464
+ );
465
+ }
466
+
467
+ /// External slots: the host constructs these — Msg-reachable number fields
468
+ /// and number parameters of exported functions.
469
+ private markExternal(): void {
470
+ const seen = new Set<string>();
471
+ const markType = (name: string): void => {
472
+ if (seen.has(name)) return;
473
+ seen.add(name);
474
+ const union = this.table.unions.get(name);
475
+ if (union) {
476
+ for (const arm of union.arms) {
477
+ for (const f of arm.fields) {
478
+ this.markField(f.decl, f.type.k);
479
+ this.markNested(f.type, markType);
480
+ }
481
+ }
482
+ }
483
+ const struct = this.table.structs.get(name);
484
+ if (struct) {
485
+ for (const f of struct.fields) {
486
+ this.markField(f.decl, f.type.k);
487
+ this.markNested(f.type, markType);
488
+ }
489
+ }
490
+ };
491
+ markType("Msg");
492
+ // Only the ENTRY module's exports face the host ABI (the wiring and
493
+ // markup bind through the entry). An exported function in an imported
494
+ // module is an ordinary cross-module call, so proof still applies.
495
+ for (const stmt of this.files[0].statements) {
496
+ if (ts.isFunctionDeclaration(stmt) && stmt.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword)) {
497
+ for (const p of stmt.parameters) {
498
+ const slot = this.slots.get(p);
499
+ if (slot) {
500
+ slot.external = true;
501
+ slot.hostBoundary = true;
502
+ slot.proven = false;
503
+ }
504
+ }
505
+ }
506
+ }
507
+ }
508
+
509
+ private markField(decl: ts.Node, _kind: string): void {
510
+ const slot = this.slots.get(decl);
511
+ if (slot) {
512
+ slot.external = true;
513
+ slot.proven = false;
514
+ }
515
+ }
516
+
517
+ private markNested(t: import("./types.ts").ZType, markType: (n: string) => void): void {
518
+ switch (t.k) {
519
+ case "struct":
520
+ case "union":
521
+ markType(t.name);
522
+ break;
523
+ case "slice":
524
+ this.markNested(t.elem, markType);
525
+ break;
526
+ case "optional":
527
+ this.markNested(t.inner, markType);
528
+ break;
529
+ default:
530
+ break;
531
+ }
532
+ }
533
+
534
+ // ---------------------------------------------------------- flow analysis
535
+
536
+ private slotOfNode(node: ts.Node): Slot | undefined {
537
+ return this.slots.get(node);
538
+ }
539
+
540
+ /// Whether an expression is an `import * as ns` alias (by its own symbol,
541
+ /// so shadowing locals do not count).
542
+ private isNamespaceAliasBase(e: ts.Expression): boolean {
543
+ if (!ts.isIdentifier(e)) return false;
544
+ const sym = this.tast.symbolOf(e);
545
+ const d = sym?.declarations?.[0];
546
+ return d !== undefined && ts.isNamespaceImport(d);
547
+ }
548
+
549
+ /// The class MethodDeclaration a property-access callee resolves to,
550
+ /// else null (R19 dispatch, shared by flows and contributions).
551
+ private methodDeclOf(callee: ts.PropertyAccessExpression): ts.MethodDeclaration | null {
552
+ const decl = this.tast.declarationOf(callee.name);
553
+ return decl && ts.isMethodDeclaration(decl) && ts.isClassDeclaration(decl.parent) ? decl : null;
554
+ }
555
+
556
+ private slotOfName(name: ts.Node): Slot | undefined {
557
+ const decl = this.tast.declarationOf(name);
558
+ if (decl) return this.slots.get(decl);
559
+ // A catch binding's field read (`e.at`): tsc types the binding as `any`
560
+ // here (no symbol resolves), but the subset types it as the core's
561
+ // thrown shape — resolve the field's declaration through it so payload
562
+ // reads share the field's own slot.
563
+ const p = name.parent;
564
+ if (
565
+ ts.isPropertyAccessExpression(p) &&
566
+ p.name === name &&
567
+ ts.isIdentifier(name) &&
568
+ this.isCatchBinding(p.expression)
569
+ ) {
570
+ const fieldDecl = this.thrownFieldDecl(name.text);
571
+ if (fieldDecl) return this.slots.get(fieldDecl);
572
+ }
573
+ return undefined;
574
+ }
575
+
576
+ /// Whether an expression is a `catch (e)` binding (by declaration).
577
+ private isCatchBinding(e: ts.Expression): boolean {
578
+ let cur = e;
579
+ while (ts.isParenthesizedExpression(cur)) cur = cur.expression;
580
+ if (!ts.isIdentifier(cur)) return false;
581
+ const d = this.tast.declarationOf(cur);
582
+ return d !== undefined && ts.isVariableDeclaration(d) && ts.isCatchClause(d.parent);
583
+ }
584
+
585
+ /// The declaration of the thrown shape's field with this name (first
586
+ /// match across the thrown union's arms), memoized per inference run.
587
+ private thrownShapeMemo: import("./types.ts").ZType | null | undefined;
588
+ private thrownFieldDecl(name: string): ts.Declaration | null {
589
+ if (this.thrownShapeMemo === undefined) {
590
+ this.thrownShapeMemo = thrownShapeOf(this.tast, this.table, this.files).shape;
591
+ }
592
+ const shape = this.thrownShapeMemo;
593
+ if (!shape) return null;
594
+ if (shape.k === "union") {
595
+ for (const arm of this.table.unions.get(shape.name)?.arms ?? []) {
596
+ const f = arm.fields.find((x) => x.tsName === name);
597
+ if (f) return f.decl;
598
+ }
599
+ return null;
600
+ }
601
+ if (shape.k === "struct") {
602
+ return this.table.structs.get(shape.name)?.fields.find((x) => x.tsName === name)?.decl ?? null;
603
+ }
604
+ return null;
605
+ }
606
+
607
+ /// The number slots and source classes contributing to an expression.
608
+ contribution(expr: ts.Expression): Contribution {
609
+ const c: Contribution = { slots: [], float: false, unknown: false, intSource: false, site: expr };
610
+ this.contribute(expr, c);
611
+ return c;
612
+ }
613
+
614
+ private contribute(expr: ts.Expression, c: Contribution): void {
615
+ if (
616
+ ts.isParenthesizedExpression(expr) ||
617
+ ts.isAsExpression(expr) ||
618
+ ts.isNonNullExpression(expr) ||
619
+ ts.isSatisfiesExpression(expr)
620
+ ) {
621
+ return this.contribute(expr.expression, c);
622
+ }
623
+ if (ts.isNumericLiteral(expr)) {
624
+ if (Number.isInteger(Number(expr.text)) && !expr.text.includes(".") && !/[eE]/.test(expr.text)) {
625
+ c.intSource = true;
626
+ } else {
627
+ c.float = true;
628
+ }
629
+ return;
630
+ }
631
+ if (ts.isPostfixUnaryExpression(expr)) {
632
+ // `i++` in value position: the value is the slot's own (pre-step).
633
+ return this.contribute(expr.operand, c);
634
+ }
635
+ if (ts.isPrefixUnaryExpression(expr)) {
636
+ if (expr.operator === ts.SyntaxKind.PlusPlusToken || expr.operator === ts.SyntaxKind.MinusMinusToken) {
637
+ return this.contribute(expr.operand, c);
638
+ }
639
+ if (expr.operator === ts.SyntaxKind.MinusToken || expr.operator === ts.SyntaxKind.PlusToken) {
640
+ // `-0` (and any negation folding to -0) is a float source: i64 has no
641
+ // signed zero, so an int-claimed slot would return +0 where node
642
+ // keeps -0 — the same family as the % fold rule below.
643
+ const folded = this.tast.constEvalNumber(expr);
644
+ if (folded !== null && Object.is(folded, -0)) {
645
+ c.float = true;
646
+ return;
647
+ }
648
+ return this.contribute(expr.operand, c);
649
+ }
650
+ if (expr.operator === ts.SyntaxKind.TildeToken) {
651
+ // `~x` is ToInt32 then bitwise-not: always a signed 32-bit integer.
652
+ c.intSource = true;
653
+ return;
654
+ }
655
+ return;
656
+ }
657
+ if (ts.isIdentifier(expr)) {
658
+ const slot = this.slotOfName(expr);
659
+ if (slot) {
660
+ c.slots.push(slot);
661
+ return;
662
+ }
663
+ // The NaN/Infinity globals are definitely-float values (a shadowing
664
+ // declaration in this module does not count).
665
+ if (expr.text === "NaN" || expr.text === "Infinity") {
666
+ const decl = this.tast.declarationOf(expr);
667
+ if (!decl || !this.fileSet.has(decl.getSourceFile())) c.float = true;
668
+ return;
669
+ }
670
+ // R15e: a slot typed by a TYPE PARAMETER has no inference slot; under
671
+ // an active instantiation scope it resolves — `T = number` slots are
672
+ // f64 (the JS-exact class), so they read as definitely-float here.
673
+ {
674
+ const decl = this.tast.declarationOf(expr);
675
+ const typeNode =
676
+ decl && (ts.isParameter(decl) || ts.isVariableDeclaration(decl)) ? decl.type : undefined;
677
+ if (typeNode) {
678
+ const t = this.table.resolveTypeNode(typeNode);
679
+ if (t.k === "f64" || (t.k === "optional" && t.inner.k === "f64")) c.float = true;
680
+ }
681
+ }
682
+ return;
683
+ }
684
+ if (ts.isPropertyAccessExpression(expr)) {
685
+ if (expr.name.text === "length") {
686
+ c.intSource = true;
687
+ return;
688
+ }
689
+ const slot = this.slotOfName(expr.name);
690
+ if (slot) c.slots.push(slot);
691
+ return;
692
+ }
693
+ if (ts.isElementAccessExpression(expr)) {
694
+ // Byte reads are integer-valued, and numeric-literal-union elements
695
+ // (e.g. RunClass arrays) carry integer members. A plain number-ARRAY
696
+ // element is f64 — R2 covers slots, not elements — so it reads as a
697
+ // definitely-float source, the same rule as callback captures.
698
+ if (this.tast.isBytesTyped(expr.expression)) {
699
+ c.intSource = true;
700
+ return;
701
+ }
702
+ const t = this.tast.typeOf(expr);
703
+ const members = t.isUnion() ? t.types : [t];
704
+ if (members.every((m) => m.isNumberLiteral())) {
705
+ c.intSource = true;
706
+ return;
707
+ }
708
+ c.float = true;
709
+ return;
710
+ }
711
+ if (ts.isBinaryExpression(expr)) {
712
+ switch (expr.operatorToken.kind) {
713
+ case ts.SyntaxKind.SlashToken:
714
+ case ts.SyntaxKind.AsteriskAsteriskToken:
715
+ // Division is float always; `**` follows it (2 ** -2 is 0.25, and
716
+ // the NaN/Infinity corners are float-only values).
717
+ c.float = true;
718
+ this.contribute(expr.left, c);
719
+ this.contribute(expr.right, c);
720
+ return;
721
+ case ts.SyntaxKind.PercentToken: {
722
+ // A remainder that folds to a non-integer is a float source even
723
+ // over integer operands: a zero (or -0) divisor makes NaN, and a
724
+ // negative dividend can make -0 (both spelled f64Literal at emit).
725
+ const folded = this.tast.constEvalNumber(expr);
726
+ if (folded !== null && (!Number.isInteger(folded) || Object.is(folded, -0))) {
727
+ c.float = true;
728
+ return;
729
+ }
730
+ this.contribute(expr.left, c);
731
+ this.contribute(expr.right, c);
732
+ return;
733
+ }
734
+ case ts.SyntaxKind.PlusToken:
735
+ case ts.SyntaxKind.MinusToken:
736
+ case ts.SyntaxKind.AsteriskToken: {
737
+ // Constant arithmetic that folds to -0 (`0 * -1`) is a float
738
+ // source even over integer operands, same as the % rule below.
739
+ const folded = this.tast.constEvalNumber(expr);
740
+ if (folded !== null && Object.is(folded, -0)) {
741
+ c.float = true;
742
+ return;
743
+ }
744
+ this.contribute(expr.left, c);
745
+ this.contribute(expr.right, c);
746
+ return;
747
+ }
748
+ case ts.SyntaxKind.AmpersandToken:
749
+ case ts.SyntaxKind.BarToken:
750
+ case ts.SyntaxKind.CaretToken:
751
+ case ts.SyntaxKind.LessThanLessThanToken:
752
+ case ts.SyntaxKind.GreaterThanGreaterThanToken:
753
+ case ts.SyntaxKind.GreaterThanGreaterThanGreaterThanToken:
754
+ case ts.SyntaxKind.QuestionQuestionToken:
755
+ this.contribute(expr.left, c);
756
+ this.contribute(expr.right, c);
757
+ return;
758
+ case ts.SyntaxKind.EqualsToken:
759
+ case ts.SyntaxKind.PlusEqualsToken:
760
+ case ts.SyntaxKind.MinusEqualsToken:
761
+ case ts.SyntaxKind.AsteriskEqualsToken:
762
+ case ts.SyntaxKind.SlashEqualsToken:
763
+ case ts.SyntaxKind.PercentEqualsToken:
764
+ case ts.SyntaxKind.AsteriskAsteriskEqualsToken:
765
+ // An assignment in value position reads the target after the
766
+ // statement — the target slot's own value.
767
+ this.contribute(expr.left, c);
768
+ return;
769
+ default:
770
+ return; // comparisons/logic produce booleans
771
+ }
772
+ }
773
+ if (ts.isConditionalExpression(expr)) {
774
+ this.contribute(expr.whenTrue, c);
775
+ this.contribute(expr.whenFalse, c);
776
+ return;
777
+ }
778
+ if (ts.isCallExpression(expr)) {
779
+ const callee = expr.expression;
780
+ if (ts.isPropertyAccessExpression(callee) && this.isNamespaceAliasBase(callee.expression)) {
781
+ // `ns.helper()` contributes the target function's return slot.
782
+ const decl = this.tast.declarationOf(callee.name);
783
+ const ret = decl && ts.isFunctionDeclaration(decl) ? this.slots.get(decl) : undefined;
784
+ if (ret) c.slots.push(ret);
785
+ else c.unknown = true;
786
+ return;
787
+ }
788
+ if (ts.isPropertyAccessExpression(callee) && this.methodDeclOf(callee) !== null) {
789
+ // R19: a data-class method call contributes its return slot.
790
+ const ret = this.slots.get(this.methodDeclOf(callee)!);
791
+ if (ret) c.slots.push(ret);
792
+ else c.unknown = true;
793
+ return;
794
+ }
795
+ if (ts.isPropertyAccessExpression(callee)) {
796
+ const method = callee.name.text;
797
+ if (ts.isIdentifier(callee.expression) && callee.expression.text === "Math") {
798
+ // A Math call that folds at compile time contributes its folded JS
799
+ // value's own class — `Math.floor(5 / 2)` is the integer 2 even
800
+ // though the division inside is a float source.
801
+ const folded = this.tast.constEvalNumber(expr);
802
+ if (folded !== null) {
803
+ if (Number.isInteger(folded) && !Object.is(folded, -0)) c.intSource = true;
804
+ else c.float = true;
805
+ return;
806
+ }
807
+ if (method === "min" || method === "max") {
808
+ if (expr.arguments.length === 0) {
809
+ // Math.min() is Infinity, Math.max() is -Infinity.
810
+ c.float = true;
811
+ return;
812
+ }
813
+ for (const arg of expr.arguments) this.contribute(arg, c);
814
+ return;
815
+ }
816
+ if (method === "floor" || method === "ceil" || method === "trunc" || method === "abs" || method === "sign") {
817
+ // Integer-classed argument in, integer-classed value out (the
818
+ // identity/abs/sign of an integer). A float argument keeps the
819
+ // result float: floor(NaN) is NaN, floor(Infinity) is Infinity,
820
+ // so no integer type can hold the result soundly.
821
+ for (const arg of expr.arguments) this.contribute(arg, c);
822
+ return;
823
+ }
824
+ if (method === "round" || method === "sqrt") {
825
+ // Definitely-float sources: round/sqrt of NaN/Infinity is not an
826
+ // integer (and sqrt is irrational off perfect squares), so these
827
+ // live in f64 slots and an index use is a taught conflict. The
828
+ // argument stays unconstrained — an integer-classed read widens
829
+ // at the site.
830
+ c.float = true;
831
+ return;
832
+ }
833
+ c.unknown = true;
834
+ return;
835
+ }
836
+ if (method === "charCodeAt" || method === "indexOf" || method === "lastIndexOf" || method === "findIndex" || method === "length") {
837
+ c.intSource = true;
838
+ return;
839
+ }
840
+ if (method === "at") {
841
+ // Bytes `.at(i)` — byte values are integers (the same rule as a
842
+ // bytes element read; strings have no `.at` past the checker).
843
+ c.intSource = true;
844
+ return;
845
+ }
846
+ if (method === "reduce") {
847
+ // The value of a reduce IS its accumulator slot (fed by the initial
848
+ // value and the body result; flows wired in collectFlows).
849
+ const arrow = expr.arguments[0];
850
+ const accP = arrow !== undefined && ts.isArrowFunction(arrow) ? arrow.parameters[0] : undefined;
851
+ const slot = accP ? this.slots.get(accP) : undefined;
852
+ if (slot) {
853
+ c.slots.push(slot);
854
+ } else {
855
+ c.unknown = true;
856
+ }
857
+ return;
858
+ }
859
+ if (method === "find" || method === "pop" || method === "shift") {
860
+ // Array elements are f64-classed (R2 covers slots, not elements),
861
+ // so a find/pop/shift value reads as a definitely-float source in
862
+ // numeric positions — an index use downstream is a taught NS1016.
863
+ c.float = true;
864
+ return;
865
+ }
866
+ c.unknown = true;
867
+ return;
868
+ }
869
+ if (ts.isIdentifier(callee)) {
870
+ const decl = this.tast.declarationOf(callee);
871
+ if (decl && ts.isFunctionDeclaration(decl)) {
872
+ const ret = this.slots.get(decl);
873
+ if (ret) {
874
+ c.slots.push(ret);
875
+ return;
876
+ }
877
+ }
878
+ // A hoisted local helper's numbers emit f64 (its parameter slots
879
+ // are element-style float slots), so its call value reads float.
880
+ if (decl && ts.isVariableDeclaration(decl)) {
881
+ const fn = constFunctionValue(decl);
882
+ if (fn?.type && this.numberish(fn.type)) {
883
+ c.float = true;
884
+ return;
885
+ }
886
+ }
887
+ }
888
+ c.unknown = true;
889
+ return;
890
+ }
891
+ // Anything else (object/array literals, template strings) contributes no
892
+ // number value in a numeric position; mark unknown to stay conservative.
893
+ if (
894
+ ts.isObjectLiteralExpression(expr) ||
895
+ ts.isArrayLiteralExpression(expr) ||
896
+ ts.isTemplateExpression(expr) ||
897
+ ts.isStringLiteral(expr) ||
898
+ expr.kind === ts.SyntaxKind.NullKeyword ||
899
+ expr.kind === ts.SyntaxKind.TrueKeyword ||
900
+ expr.kind === ts.SyntaxKind.FalseKeyword ||
901
+ ts.isNewExpression(expr) ||
902
+ ts.isArrowFunction(expr)
903
+ ) {
904
+ return;
905
+ }
906
+ c.unknown = true;
907
+ }
908
+
909
+ private flowInto(target: ts.Node | undefined, expr: ts.Expression): void {
910
+ if (!target) return;
911
+ const slot = this.slots.get(target);
912
+ if (!slot) return;
913
+ slot.inflows.push(this.contribution(expr));
914
+ }
915
+
916
+ private demand(expr: ts.Expression): void {
917
+ this.demandSeeds.push(this.contribution(expr));
918
+ }
919
+
920
+ private collectFlows(): void {
921
+ const enclosingFunction = (node: ts.Node): ts.Node | undefined => {
922
+ let cur: ts.Node | undefined = node.parent;
923
+ while (cur) {
924
+ if (
925
+ ts.isFunctionDeclaration(cur) ||
926
+ ts.isArrowFunction(cur) ||
927
+ ts.isFunctionExpression(cur) ||
928
+ ts.isMethodDeclaration(cur) ||
929
+ ts.isConstructorDeclaration(cur)
930
+ ) {
931
+ return cur;
932
+ }
933
+ cur = cur.parent;
934
+ }
935
+ return undefined;
936
+ };
937
+
938
+ /// A class-field slot written through a property access (`this.x = e`,
939
+ /// `t.x = e`), else undefined — assignment flows wire into it exactly
940
+ /// like a local's.
941
+ const fieldAssignTarget = (left: ts.Expression): ts.Node | undefined => {
942
+ if (!ts.isPropertyAccessExpression(left)) return undefined;
943
+ const decl = this.tast.declarationOf(left.name);
944
+ return decl && ts.isPropertyDeclaration(decl) ? decl : undefined;
945
+ };
946
+
947
+ const visit = (node: ts.Node): void => {
948
+ if (ts.isVariableDeclaration(node) && node.initializer && ts.isIdentifier(node.name)) {
949
+ this.flowInto(node, node.initializer);
950
+ } else if (ts.isPropertyDeclaration(node) && node.initializer && ts.isIdentifier(node.name)) {
951
+ // R19: `count: number = 0` feeds the field slot like a local's init.
952
+ this.flowInto(node, node.initializer);
953
+ } else if (ts.isBindingElement(node) && ts.isIdentifier(node.name)) {
954
+ // `const { total } = stats;` — the local is fed by the record field's
955
+ // own slot, so its machine class follows the field's. An
956
+ // unresolvable base stays a conservative unknown (kills proof).
957
+ const slot = this.slots.get(node);
958
+ if (slot) {
959
+ const f = this.destructuredField(node);
960
+ const fieldSlot = f ? this.slots.get(f.decl) : undefined;
961
+ slot.inflows.push({
962
+ slots: fieldSlot ? [fieldSlot] : [],
963
+ float: false,
964
+ unknown: fieldSlot === undefined,
965
+ intSource: false,
966
+ site: node.name,
967
+ });
968
+ }
969
+ } else if (ts.isPrefixUnaryExpression(node) && node.operator === ts.SyntaxKind.TildeToken) {
970
+ // `~x` applies ToInt32: the operand is an integer-required position.
971
+ this.demand(node.operand);
972
+ } else if (ts.isBinaryExpression(node)) {
973
+ const op = node.operatorToken.kind;
974
+ if (op === ts.SyntaxKind.EqualsToken && ts.isIdentifier(node.left)) {
975
+ const decl = this.tast.declarationOf(node.left);
976
+ this.flowInto(decl, node.right);
977
+ } else if (op === ts.SyntaxKind.EqualsToken && fieldAssignTarget(node.left) !== undefined) {
978
+ this.flowInto(fieldAssignTarget(node.left), node.right);
979
+ } else if (
980
+ op === ts.SyntaxKind.PlusEqualsToken ||
981
+ op === ts.SyntaxKind.MinusEqualsToken ||
982
+ op === ts.SyntaxKind.AsteriskEqualsToken ||
983
+ op === ts.SyntaxKind.PercentEqualsToken ||
984
+ op === ts.SyntaxKind.QuestionQuestionEqualsToken
985
+ ) {
986
+ if (ts.isIdentifier(node.left)) this.flowInto(this.tast.declarationOf(node.left), node.right);
987
+ else if (fieldAssignTarget(node.left) !== undefined) this.flowInto(fieldAssignTarget(node.left), node.right);
988
+ } else if (
989
+ op === ts.SyntaxKind.SlashEqualsToken ||
990
+ op === ts.SyntaxKind.AsteriskAsteriskEqualsToken
991
+ ) {
992
+ // `x /= y` and `x **= y` assign a float-always result into x.
993
+ if (ts.isIdentifier(node.left)) {
994
+ const decl = this.tast.declarationOf(node.left);
995
+ const slot = decl ? this.slots.get(decl) : undefined;
996
+ if (slot) {
997
+ const c = this.contribution(node.right);
998
+ c.float = true;
999
+ slot.inflows.push(c);
1000
+ }
1001
+ }
1002
+ } else if (
1003
+ op === ts.SyntaxKind.AmpersandEqualsToken ||
1004
+ op === ts.SyntaxKind.BarEqualsToken ||
1005
+ op === ts.SyntaxKind.CaretEqualsToken ||
1006
+ op === ts.SyntaxKind.LessThanLessThanEqualsToken ||
1007
+ op === ts.SyntaxKind.GreaterThanGreaterThanEqualsToken ||
1008
+ op === ts.SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken
1009
+ ) {
1010
+ // Bitwise/shift compounds: both sides are integer-required, and
1011
+ // the assigned result is a definite ToInt32/ToUint32 integer.
1012
+ this.demand(node.left);
1013
+ this.demand(node.right);
1014
+ if (ts.isIdentifier(node.left)) {
1015
+ const decl = this.tast.declarationOf(node.left);
1016
+ const slot = decl ? this.slots.get(decl) : undefined;
1017
+ if (slot) {
1018
+ slot.inflows.push({ slots: [], float: false, unknown: false, intSource: true, site: node.right });
1019
+ }
1020
+ }
1021
+ } else if (
1022
+ op === ts.SyntaxKind.AmpersandToken ||
1023
+ op === ts.SyntaxKind.BarToken ||
1024
+ op === ts.SyntaxKind.CaretToken ||
1025
+ op === ts.SyntaxKind.LessThanLessThanToken ||
1026
+ op === ts.SyntaxKind.GreaterThanGreaterThanToken ||
1027
+ op === ts.SyntaxKind.GreaterThanGreaterThanGreaterThanToken
1028
+ ) {
1029
+ this.demand(node.left);
1030
+ this.demand(node.right);
1031
+ } else if (
1032
+ op === ts.SyntaxKind.EqualsEqualsEqualsToken ||
1033
+ op === ts.SyntaxKind.ExclamationEqualsEqualsToken ||
1034
+ op === ts.SyntaxKind.LessThanToken ||
1035
+ op === ts.SyntaxKind.LessThanEqualsToken ||
1036
+ op === ts.SyntaxKind.GreaterThanToken ||
1037
+ op === ts.SyntaxKind.GreaterThanEqualsToken
1038
+ ) {
1039
+ this.compareSites.push({ left: this.contribution(node.left), right: this.contribution(node.right) });
1040
+ } else if (
1041
+ op === ts.SyntaxKind.PlusToken ||
1042
+ op === ts.SyntaxKind.MinusToken ||
1043
+ op === ts.SyntaxKind.AsteriskToken ||
1044
+ op === ts.SyntaxKind.PercentToken
1045
+ ) {
1046
+ this.mixSites.push({ left: this.contribution(node.left), right: this.contribution(node.right) });
1047
+ }
1048
+ } else if (ts.isElementAccessExpression(node)) {
1049
+ this.demand(node.argumentExpression);
1050
+ } else if (ts.isAsExpression(node) && ts.isObjectLiteralExpression(node.expression)) {
1051
+ // `{ kind: "outer", n: err.n } as Fail` (throw payloads, mostly):
1052
+ // the assertion IS the contextual type — wire each member into the
1053
+ // asserted shape's field slot, arm-matched by the kind tag.
1054
+ const t = this.table.resolveTypeNode(node.type);
1055
+ let fields: readonly { tsName: string; decl: ts.Declaration }[] | null = null;
1056
+ if (t.k === "struct") {
1057
+ fields = this.table.structs.get(t.name)?.fields ?? null;
1058
+ } else if (t.k === "union") {
1059
+ const kindProp = node.expression.properties.find(
1060
+ (pp): pp is ts.PropertyAssignment =>
1061
+ ts.isPropertyAssignment(pp) && ts.isIdentifier(pp.name) && pp.name.text === "kind",
1062
+ );
1063
+ const tag = kindProp && ts.isStringLiteral(kindProp.initializer) ? kindProp.initializer.text : null;
1064
+ fields = tag !== null ? (this.table.unions.get(t.name)?.arms.find((a) => a.tag === tag)?.fields ?? null) : null;
1065
+ }
1066
+ if (fields !== null) {
1067
+ for (const pp of node.expression.properties) {
1068
+ if (ts.isPropertyAssignment(pp) && ts.isIdentifier(pp.name)) {
1069
+ const fld = fields.find((x) => x.tsName === (pp.name as ts.Identifier).text);
1070
+ if (fld) this.flowInto(fld.decl, pp.initializer);
1071
+ } else if (ts.isShorthandPropertyAssignment(pp)) {
1072
+ const fld = fields.find((x) => x.tsName === pp.name.text);
1073
+ const slot = fld ? this.slots.get(fld.decl) : undefined;
1074
+ if (slot) {
1075
+ const valueDecl = this.tast.shorthandValueDeclaration(pp);
1076
+ const valueSlot = valueDecl ? this.slots.get(valueDecl) : undefined;
1077
+ slot.inflows.push({
1078
+ slots: valueSlot ? [valueSlot] : [],
1079
+ float: false,
1080
+ unknown: valueSlot === undefined,
1081
+ intSource: false,
1082
+ site: pp.name,
1083
+ });
1084
+ }
1085
+ }
1086
+ }
1087
+ }
1088
+ } else if (ts.isPropertyAssignment(node)) {
1089
+ const target = this.tast.contextualPropDecl(node);
1090
+ this.flowInto(target, node.initializer);
1091
+ } else if (ts.isShorthandPropertyAssignment(node)) {
1092
+ const target = this.tast.contextualPropDecl(node as unknown as ts.PropertyAssignment);
1093
+ if (target) {
1094
+ const slot = this.slots.get(target);
1095
+ if (slot) {
1096
+ // The shorthand's name resolves to the PROPERTY symbol; the
1097
+ // value flowing in is the local/param it reads, which needs its
1098
+ // own symbol query. Unresolvable stays a conservative unknown
1099
+ // (kills proof), never a phantom integer proof.
1100
+ const valueDecl = this.tast.shorthandValueDeclaration(node);
1101
+ const valueSlot = valueDecl ? this.slots.get(valueDecl) : undefined;
1102
+ slot.inflows.push({
1103
+ slots: valueSlot ? [valueSlot] : [],
1104
+ float: false,
1105
+ unknown: valueSlot === undefined,
1106
+ intSource: false,
1107
+ site: node.name,
1108
+ });
1109
+ }
1110
+ }
1111
+ } else if (ts.isReturnStatement(node) && node.expression) {
1112
+ const fn = enclosingFunction(node);
1113
+ if (fn) this.flowInto(fn, node.expression);
1114
+ } else if (ts.isCallExpression(node)) {
1115
+ const callee = node.expression;
1116
+ if (ts.isIdentifier(callee)) {
1117
+ const decl = this.tast.declarationOf(callee);
1118
+ if (decl && ts.isFunctionDeclaration(decl)) {
1119
+ decl.parameters.forEach((p, i) => {
1120
+ const arg = node.arguments[i];
1121
+ if (arg) this.flowInto(p, arg);
1122
+ });
1123
+ }
1124
+ } else if (ts.isPropertyAccessExpression(callee) && this.isNamespaceAliasBase(callee.expression)) {
1125
+ // `ns.helper(x)` — the namespace alias erases, so arguments flow
1126
+ // into the target function's parameter slots exactly like a
1127
+ // direct call.
1128
+ const decl = this.tast.declarationOf(callee.name);
1129
+ if (decl && ts.isFunctionDeclaration(decl)) {
1130
+ decl.parameters.forEach((p, i) => {
1131
+ const arg = node.arguments[i];
1132
+ if (arg) this.flowInto(p, arg);
1133
+ });
1134
+ }
1135
+ } else if (ts.isPropertyAccessExpression(callee) && this.methodDeclOf(callee) !== null) {
1136
+ // R19: `t.method(x)` flows arguments into the method's parameter
1137
+ // slots, exactly like a direct call.
1138
+ this.methodDeclOf(callee)!.parameters.forEach((mp, i) => {
1139
+ const arg = node.arguments[i];
1140
+ if (arg) this.flowInto(mp, arg);
1141
+ });
1142
+ } else if (ts.isPropertyAccessExpression(callee)) {
1143
+ const method = callee.name.text;
1144
+ if (ts.isIdentifier(callee.expression) && callee.expression.text === "Math") {
1145
+ if ((method === "min" || method === "max") && node.arguments.length >= 2) {
1146
+ // Pairwise over consecutive arguments: demotion chains through,
1147
+ // so one float argument floats the whole site.
1148
+ for (let i = 0; i + 1 < node.arguments.length; i++) {
1149
+ this.mixSites.push({
1150
+ left: this.contribution(node.arguments[i]),
1151
+ right: this.contribution(node.arguments[i + 1]),
1152
+ });
1153
+ }
1154
+ }
1155
+ } else if (method === "subarray" || method === "slice" || method === "set" || method === "charCodeAt" || method === "repeat" || method === "at") {
1156
+ // repeat's count and at's index are integer positions, like
1157
+ // every index (a fractional flow is a taught NS1016).
1158
+ const start = method === "set" ? 1 : 0;
1159
+ for (let i = start; i < node.arguments.length; i++) this.demand(node.arguments[i]);
1160
+ } else if (method === "padStart" || method === "padEnd") {
1161
+ // The target BYTE length indexes memory; the fill is bytes.
1162
+ if (node.arguments[0]) this.demand(node.arguments[0]);
1163
+ } else if (method === "splice") {
1164
+ // start and deleteCount index memory (rt.sliceIndex); inserted
1165
+ // items are elements and stay unconstrained (f64 like all array
1166
+ // elements).
1167
+ for (let i = 0; i < Math.min(node.arguments.length, 2); i++) this.demand(node.arguments[i]);
1168
+ } else if (method === "fill") {
1169
+ // start/end index memory; the fill VALUE (argument 0) is an
1170
+ // element and stays unconstrained.
1171
+ for (let i = 1; i < node.arguments.length; i++) this.demand(node.arguments[i]);
1172
+ } else if (method === "reduce") {
1173
+ // The accumulator slot is fed by the initial value and by the
1174
+ // callback body's result (each iteration assigns it back) — for
1175
+ // a block body, by every `return` expression.
1176
+ const arrow = node.arguments[0];
1177
+ if (arrow && ts.isArrowFunction(arrow) && arrow.parameters.length === 2) {
1178
+ const accP = arrow.parameters[0];
1179
+ if (node.arguments[1]) this.flowInto(accP, node.arguments[1]);
1180
+ if (!ts.isBlock(arrow.body)) this.flowInto(accP, arrow.body);
1181
+ else for (const r of returnExpressionsOf(arrow.body)) this.flowInto(accP, r);
1182
+ }
1183
+ }
1184
+ }
1185
+ } else if (ts.isNewExpression(node)) {
1186
+ if (ts.isIdentifier(node.expression) && node.expression.text === "Uint8Array") {
1187
+ for (const arg of node.arguments ?? []) this.demand(arg);
1188
+ } else if (ts.isIdentifier(node.expression)) {
1189
+ // R19: `new C(x)` flows arguments into the constructor's
1190
+ // parameter slots, exactly like a direct call.
1191
+ const decl = this.tast.declarationOf(node.expression);
1192
+ if (decl && ts.isClassDeclaration(decl)) {
1193
+ const ctor = decl.members.find(
1194
+ (m): m is ts.ConstructorDeclaration => ts.isConstructorDeclaration(m) && m.body !== undefined,
1195
+ );
1196
+ ctor?.parameters.forEach((cp, i) => {
1197
+ const arg = node.arguments?.[i];
1198
+ if (arg) this.flowInto(cp, arg);
1199
+ });
1200
+ }
1201
+ }
1202
+ } else if (ts.isArrowFunction(node) && !ts.isBlock(node.body)) {
1203
+ this.flowInto(node, node.body);
1204
+ }
1205
+ ts.forEachChild(node, visit);
1206
+ };
1207
+ for (const file of this.files) visit(file);
1208
+ }
1209
+
1210
+ // ------------------------------------------------------------- resolution
1211
+
1212
+ private sideIsInt(c: Contribution): boolean {
1213
+ if (c.float || c.unknown) return false;
1214
+ if (c.slots.length === 0) return c.intSource;
1215
+ return c.slots.every((s) => !s.float && (s.proven || s.demanded));
1216
+ }
1217
+
1218
+ /// Taint-only float check (demand phase): undecided slots are not float yet.
1219
+ private sideFloatTaint(c: Contribution): boolean {
1220
+ if (c.float) return true;
1221
+ return c.slots.some((s) => s.float);
1222
+ }
1223
+
1224
+ /// Final float check (demotion phase): undecided slots resolve to f64.
1225
+ private sideIsFloat(c: Contribution): boolean {
1226
+ if (c.float) return true;
1227
+ return c.slots.some((s) => s.float) || (c.slots.length > 0 && c.slots.every((s) => this.finalClassOf(s) === "f64"));
1228
+ }
1229
+
1230
+ private finalClassOf(s: Slot): "i64" | "f64" {
1231
+ if (s.float) return "f64";
1232
+ return s.proven || s.demanded ? "i64" : "f64";
1233
+ }
1234
+
1235
+ private resolve(): void {
1236
+ const all = [...this.slots.values()];
1237
+
1238
+ // Forward float taint from literal/div sources. The fixpoint flag is
1239
+ // LOCAL: this also runs inside the demotion loop below, and clobbering
1240
+ // that loop's `changed` would end its fixpoint one pass early (a
1241
+ // two-hop demotion chain — field -> destructured alias -> local —
1242
+ // would strand the far end as a phantom NS1016 conflict).
1243
+ let changed = true;
1244
+ const propagateFloat = () => {
1245
+ let moved = true;
1246
+ while (moved) {
1247
+ moved = false;
1248
+ for (const s of all) {
1249
+ if (s.float) continue;
1250
+ if (s.inflows.some((c) => c.float || c.slots.some((x) => x.float))) {
1251
+ s.float = true;
1252
+ moved = true;
1253
+ }
1254
+ }
1255
+ }
1256
+ };
1257
+ propagateFloat();
1258
+
1259
+ // Greatest-fixpoint integer proof: demote until stable.
1260
+ changed = true;
1261
+ while (changed) {
1262
+ changed = false;
1263
+ for (const s of all) {
1264
+ if (!s.proven) continue;
1265
+ const bad =
1266
+ s.float ||
1267
+ s.external ||
1268
+ s.inflows.some((c) => c.float || c.unknown || c.slots.some((x) => !x.proven || x.float));
1269
+ if (bad) {
1270
+ s.proven = false;
1271
+ changed = true;
1272
+ }
1273
+ }
1274
+ }
1275
+
1276
+ // Least-fixpoint demand: seeds, backward through inflows, plus
1277
+ // comparisons against proven/demanded integer sides. Comparison-origin
1278
+ // demand never claims a host-boundary slot, nor any slot a host-boundary
1279
+ // slot feeds: the comparison itself does not require an integer (the
1280
+ // emitter widens the integer side into f64 instead), and an i64-claimed
1281
+ // exported signature would truncate host f64 values that node compares
1282
+ // exactly — claiming only part of such a chain would manufacture an
1283
+ // NS1016 conflict out of thin air. Genuine demand chains (index,
1284
+ // bitwise, size positions) still claim host params — there the emitted
1285
+ // i64 signature is the contract type the wiring builds against.
1286
+ const boundaryFed = new Map<Slot, boolean>();
1287
+ const touchesBoundary = (s: Slot): boolean => {
1288
+ const memo = boundaryFed.get(s);
1289
+ if (memo !== undefined) return memo;
1290
+ boundaryFed.set(s, false); // cycle guard: a cycle adds no boundary
1291
+ const touched =
1292
+ s.hostBoundary || s.inflows.some((c) => !c.float && c.slots.some((x) => touchesBoundary(x)));
1293
+ boundaryFed.set(s, touched);
1294
+ return touched;
1295
+ };
1296
+ const demandSlot = (s: Slot, viaComparison: boolean): void => {
1297
+ if (s.float) return;
1298
+ if (s.demanded) {
1299
+ // A hard requirement reaching a tentatively-claimed slot upgrades
1300
+ // it (and its backward chain): the claim stops being yieldable.
1301
+ if (!viaComparison && s.comparisonDemanded) {
1302
+ s.comparisonDemanded = false;
1303
+ for (const c of s.inflows) {
1304
+ if (c.float) continue;
1305
+ for (const x of c.slots) demandSlot(x, false);
1306
+ }
1307
+ }
1308
+ return;
1309
+ }
1310
+ if (viaComparison && touchesBoundary(s)) return;
1311
+ s.demanded = true;
1312
+ s.comparisonDemanded = viaComparison;
1313
+ for (const c of s.inflows) {
1314
+ if (c.float) continue;
1315
+ for (const x of c.slots) demandSlot(x, viaComparison);
1316
+ }
1317
+ };
1318
+ for (const c of this.demandSeeds) {
1319
+ if (c.float) continue;
1320
+ for (const s of c.slots) demandSlot(s, false);
1321
+ }
1322
+ changed = true;
1323
+ while (changed) {
1324
+ changed = false;
1325
+ for (const site of this.compareSites) {
1326
+ const pairs: Array<[Contribution, Contribution]> = [
1327
+ [site.left, site.right],
1328
+ [site.right, site.left],
1329
+ ];
1330
+ for (const [a, b] of pairs) {
1331
+ if (this.sideIsInt(a) && !this.sideFloatTaint(b)) {
1332
+ // A side partly fed by the host boundary resolves f64 as a
1333
+ // whole; claiming its other slots would only split the side.
1334
+ if (b.slots.some((s) => touchesBoundary(s))) continue;
1335
+ for (const s of b.slots) {
1336
+ if (!s.demanded && !s.float) {
1337
+ demandSlot(s, true);
1338
+ changed = true;
1339
+ }
1340
+ }
1341
+ }
1342
+ }
1343
+ }
1344
+ }
1345
+
1346
+ // Forward demand across assignment edges: a demanded source is i64, so
1347
+ // the slot it is assigned into must match (and its other sources follow
1348
+ // through demandSlot's backward recursion). Tentativeness rides along:
1349
+ // a slot fed only by comparison-claimed sources is itself yieldable,
1350
+ // while a hard-demanded source hardens what it feeds.
1351
+ changed = true;
1352
+ while (changed) {
1353
+ changed = false;
1354
+ for (const s of all) {
1355
+ if (s.float) continue;
1356
+ const hardFed = s.inflows.some(
1357
+ (c) => !c.float && c.slots.some((x) => !x.float && x.demanded && !x.comparisonDemanded),
1358
+ );
1359
+ if (!s.demanded) {
1360
+ const tentativeFed = s.inflows.some(
1361
+ (c) => !c.float && c.slots.some((x) => !x.float && x.demanded && x.comparisonDemanded),
1362
+ );
1363
+ if (hardFed || tentativeFed) {
1364
+ demandSlot(s, !hardFed);
1365
+ changed = true;
1366
+ }
1367
+ } else if (s.comparisonDemanded && hardFed) {
1368
+ demandSlot(s, false);
1369
+ changed = true;
1370
+ }
1371
+ }
1372
+ }
1373
+
1374
+ // Mixed-site and assignment-edge demotion: an unclaimed integer slot
1375
+ // meeting a float side becomes f64, and an f64-resolving slot demotes
1376
+ // the proven-but-undemanded slots assigned into it — every edge lands
1377
+ // same-typed unless a HARD-demanded slot meets float (a reported
1378
+ // conflict). Comparison-claimed slots yield here: the tentative claim
1379
+ // existed only to keep the comparison same-typed, so float reaching it
1380
+ // demotes the slot and the comparison widens instead of manufacturing
1381
+ // an NS1016 conflict.
1382
+ const demote = (s: Slot): boolean => {
1383
+ if (s.float) return false;
1384
+ if (s.demanded && !s.comparisonDemanded) return false;
1385
+ s.demanded = false;
1386
+ s.comparisonDemanded = false;
1387
+ s.float = true;
1388
+ s.proven = false;
1389
+ return true;
1390
+ };
1391
+ changed = true;
1392
+ while (changed) {
1393
+ changed = false;
1394
+ const sites = [...this.mixSites, ...this.compareSites];
1395
+ for (const site of sites) {
1396
+ const pairs: Array<[Contribution, Contribution]> = [
1397
+ [site.left, site.right],
1398
+ [site.right, site.left],
1399
+ ];
1400
+ for (const [a, b] of pairs) {
1401
+ if (!this.sideIsFloat(a)) continue;
1402
+ for (const s of b.slots) {
1403
+ // Claimed slots (tentative included) hold their class here:
1404
+ // the emitter widens the integer side of a mixed comparison
1405
+ // exactly, so a compare site never needs to demote a claim.
1406
+ if (!s.float && !s.demanded && this.finalClassOf(s) === "i64") {
1407
+ s.float = true;
1408
+ s.proven = false;
1409
+ changed = true;
1410
+ }
1411
+ }
1412
+ }
1413
+ }
1414
+ for (const s of all) {
1415
+ if (this.finalClassOf(s) !== "f64") continue;
1416
+ for (const c of s.inflows) {
1417
+ for (const x of c.slots) {
1418
+ if (demote(x)) changed = true;
1419
+ }
1420
+ }
1421
+ }
1422
+ // A tentative claim with float flowing straight into the slot yields
1423
+ // too — the same rule, seen from the inflow side.
1424
+ for (const s of all) {
1425
+ if (!s.demanded || !s.comparisonDemanded) continue;
1426
+ const floatIn = s.inflows.some((c) => c.float || c.slots.some((x) => x.float));
1427
+ if (floatIn && demote(s)) changed = true;
1428
+ }
1429
+ if (changed) propagateFloat();
1430
+ }
1431
+
1432
+ this.collectConflicts();
1433
+ }
1434
+
1435
+ /// Every edge the fixed point above could not make same-typed is a real
1436
+ /// int/float conflict; report it instead of emitting mismatched Zig.
1437
+ private collectConflicts(): void {
1438
+ const seen = new Set<ts.Node>();
1439
+ const report = (node: ts.Node, slotLabel: string): void => {
1440
+ if (seen.has(node)) return;
1441
+ seen.add(node);
1442
+ this.conflicts.push({ node, slotLabel });
1443
+ };
1444
+ for (const s of this.slots.values()) {
1445
+ if (s.demanded) {
1446
+ // An integer-required slot with float reaching it, directly or
1447
+ // through taint, cannot be emitted as either machine type.
1448
+ const src = s.inflows.find((c) => c.float || c.slots.some((x) => x.float));
1449
+ if (s.float || src) report(src?.site ?? s.decl, s.label);
1450
+ } else if (this.finalClassOf(s) === "f64") {
1451
+ for (const c of s.inflows) {
1452
+ const hard = c.slots.find((x) => this.finalClassOf(x) === "i64");
1453
+ if (hard) report(c.site, hard.label);
1454
+ }
1455
+ }
1456
+ }
1457
+ // Index/bitwise positions themselves: a float-valued expression can
1458
+ // never become the usize the memory site needs.
1459
+ for (const c of this.demandSeeds) {
1460
+ if (c.float || c.slots.some((x) => this.finalClassOf(x) === "f64")) {
1461
+ report(c.site, c.site.getText().replace(/\s+/g, " "));
1462
+ }
1463
+ }
1464
+ for (const site of this.mixSites) {
1465
+ const pairs: Array<[Contribution, Contribution]> = [
1466
+ [site.left, site.right],
1467
+ [site.right, site.left],
1468
+ ];
1469
+ for (const [a, b] of pairs) {
1470
+ if (!this.sideIsFloat(a)) continue;
1471
+ const hard = b.slots.find((x) => this.finalClassOf(x) === "i64");
1472
+ if (hard) report(b.site, hard.label);
1473
+ }
1474
+ }
1475
+ // Comparisons are looser than mixes: an INTERNAL i64 slot holds only
1476
+ // integer values by proof, so the emitter widens its read exactly and
1477
+ // the comparison agrees with node bit for bit — no conflict. An
1478
+ // EXTERNAL i64-claimed slot is different: node can receive a fraction
1479
+ // there that the emitted i64 boundary cannot represent, so a float
1480
+ // comparison against it is a real divergence to teach.
1481
+ for (const site of this.compareSites) {
1482
+ const pairs: Array<[Contribution, Contribution]> = [
1483
+ [site.left, site.right],
1484
+ [site.right, site.left],
1485
+ ];
1486
+ for (const [a, b] of pairs) {
1487
+ if (!this.sideIsFloat(a)) continue;
1488
+ const hard = b.slots.find((x) => this.finalClassOf(x) === "i64" && x.external);
1489
+ if (hard) report(b.site, hard.label);
1490
+ }
1491
+ }
1492
+ }
1493
+
1494
+ // ------------------------------------------------------------------ query
1495
+
1496
+ /// Final emission class of a number slot's declaration.
1497
+ classOfDecl(decl: ts.Node): "i64" | "f64" | null {
1498
+ const s = this.slots.get(decl);
1499
+ return s ? this.finalClassOf(s) : null;
1500
+ }
1501
+
1502
+ /// Final emission class of a numeric expression.
1503
+ classOfExpr(expr: ts.Expression): "i64" | "f64" {
1504
+ const c = this.contribution(expr);
1505
+ if (c.float) return "f64";
1506
+ if (c.slots.length === 0) return "i64";
1507
+ return c.slots.every((s) => this.finalClassOf(s) === "i64") ? "i64" : "f64";
1508
+ }
1509
+
1510
+ debugDump(): string {
1511
+ return [...this.slots.values()]
1512
+ .map((s) => `${s.label}: ${this.finalClassOf(s)}${s.external ? " (ext)" : ""}${s.demanded ? " (dem)" : ""}${s.proven ? " (prov)" : ""}`)
1513
+ .join("\n");
1514
+ }
1515
+ }