@geastack/compiler 1.0.22 → 1.0.24

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 (38) hide show
  1. package/dist/ir/borrow-effects.js +55 -1
  2. package/dist/ir/dense-loops.d.ts +16 -2
  3. package/dist/ir/dense-loops.js +66 -21
  4. package/dist/ir/facts.d.ts +6 -29
  5. package/dist/ir/facts.js +46 -1
  6. package/dist/ir/floats.d.ts +46 -0
  7. package/dist/ir/floats.js +196 -0
  8. package/dist/ir/hoist.d.ts +11 -2
  9. package/dist/ir/hoist.js +17 -2
  10. package/dist/ir/integer-storage.d.ts +8 -0
  11. package/dist/ir/integer-storage.js +15 -4
  12. package/dist/ir/integers.d.ts +40 -0
  13. package/dist/ir/integers.js +137 -4
  14. package/dist/ir/numeric-intrinsics.d.ts +1 -1
  15. package/dist/ir/numeric-intrinsics.js +3 -2
  16. package/dist/representation/derive.js +30 -1
  17. package/dist/semantics/frontend.js +5 -1
  18. package/dist/semantics/normalize/asserted-argument-arms.d.ts +38 -0
  19. package/dist/semantics/normalize/asserted-argument-arms.js +182 -0
  20. package/dist/semantics/normalize/structural.d.ts +2 -1
  21. package/dist/semantics/normalize/structural.js +10 -3
  22. package/dist/targets/cpp/emit-arrays.d.ts +2 -1
  23. package/dist/targets/cpp/emit-arrays.js +7 -3
  24. package/dist/targets/cpp/emit-bindings.js +4 -2
  25. package/dist/targets/cpp/emit-callable.js +13 -0
  26. package/dist/targets/cpp/emit-carrier-members.d.ts +3 -1
  27. package/dist/targets/cpp/emit-carrier-members.js +18 -2
  28. package/dist/targets/cpp/emit-context.d.ts +13 -0
  29. package/dist/targets/cpp/emit-context.js +18 -2
  30. package/dist/targets/cpp/emit-properties.js +16 -3
  31. package/dist/targets/cpp/emit.js +36 -4
  32. package/dist/targets/cpp/host/emit-host-invoke.js +10 -1
  33. package/dist/targets/cpp/host/host-members.js +43 -30
  34. package/dist/targets/cpp/translation-unit.js +15 -3
  35. package/dist/targets/cpp/types.d.ts +2 -0
  36. package/dist/targets/cpp/types.js +2 -0
  37. package/package.json +9 -9
  38. package/src/targets/cpp/runtime/gea_runtime.h +80 -4
@@ -1,4 +1,4 @@
1
- import type { IrValueId } from '../identity/ids.js';
1
+ import type { DeclarationId, IrValueId } from '../identity/ids.js';
2
2
  import type { IrBlockId, IrBody, IrNonTerminatorOperation } from './model.js';
3
3
  /**
4
4
  * Loop-invariant operations, and the block each one moves to.
@@ -35,7 +35,16 @@ export interface HoistPlan {
35
35
  readonly relocated: ReadonlySet<IrValueId>;
36
36
  }
37
37
  export declare const emptyHoistPlan: HoistPlan;
38
- export declare const loopInvariantHoistsOf: (body: IrBody) => HoistPlan;
38
+ /**
39
+ * @param programConstants cells written exactly once program-wide, with that
40
+ * integer literal (`ir/integers.ts`'s `programCellConstantsOf`). A module
41
+ * `const` is written by the module body, so every OTHER body that reads it
42
+ * sees no write of its own -- and without this, the read could never leave
43
+ * a loop: `for (c = 1; c < LAST - 1; c++)` recomputed its bound every turn,
44
+ * in software doubles on a core with no double FPU, and `dense-loops.ts`
45
+ * refused the window because its bound was defined inside the loop.
46
+ */
47
+ export declare const loopInvariantHoistsOf: (body: IrBody, programConstants?: ReadonlyMap<DeclarationId, number>) => HoistPlan;
39
48
  /**
40
49
  * The values a loop cannot change: what clang's licm would lift, stated here.
41
50
  *
package/dist/ir/hoist.js CHANGED
@@ -46,7 +46,16 @@ const storageNeutralKinds = new Set([
46
46
  'receiver',
47
47
  'get'
48
48
  ]);
49
- export const loopInvariantHoistsOf = (body) => {
49
+ /**
50
+ * @param programConstants cells written exactly once program-wide, with that
51
+ * integer literal (`ir/integers.ts`'s `programCellConstantsOf`). A module
52
+ * `const` is written by the module body, so every OTHER body that reads it
53
+ * sees no write of its own -- and without this, the read could never leave
54
+ * a loop: `for (c = 1; c < LAST - 1; c++)` recomputed its bound every turn,
55
+ * in software doubles on a core with no double FPU, and `dense-loops.ts`
56
+ * refused the window because its bound was defined inside the loop.
57
+ */
58
+ export const loopInvariantHoistsOf = (body, programConstants = new Map()) => {
50
59
  // A try region renders as one `try { } catch { }` chunk assembled from
51
60
  // several blocks at once, so a relocation into or out of one has no single
52
61
  // place to land. Bodies with a region are left alone entirely.
@@ -106,9 +115,13 @@ export const loopInvariantHoistsOf = (body) => {
106
115
  if (cell === undefined)
107
116
  return null;
108
117
  const written = cellWrites.get(cell) ?? [];
118
+ if (written.length === 0)
119
+ return programConstants.get(cell) ?? null;
109
120
  const only = written.length === 1 ? written[0] : undefined;
110
121
  return only ? (constants.get(only.value.value) ?? null) : null;
111
122
  };
123
+ /** A cell this body never writes and the whole program writes once: it holds the same value at every read here. */
124
+ const isProgramConstant = (cell) => programConstants.has(cell) && !cellWrites.has(cell);
112
125
  /**
113
126
  * Whether this loop's first test is known to pass.
114
127
  *
@@ -229,6 +242,8 @@ export const loopInvariantHoistsOf = (body) => {
229
242
  return true;
230
243
  }
231
244
  if (operation.kind === 'binding-read') {
245
+ if (isProgramConstant(operation.declaration))
246
+ return true;
232
247
  if (mayCaptureLocals)
233
248
  return false;
234
249
  // Invariant only while the loop writes the cell nowhere.
@@ -291,7 +306,7 @@ export const loopInvariantHoistsOf = (body) => {
291
306
  // A cell read moved ahead of the loop has to name a cell something
292
307
  // already assigned; a write that only happens AFTER the loop leaves
293
308
  // the variable uninitialized at the new position.
294
- if (operation.kind === 'binding-read') {
309
+ if (operation.kind === 'binding-read' && !isProgramConstant(operation.declaration)) {
295
310
  const written = cellWrites.get(operation.declaration) ?? [];
296
311
  if (!written.some((write) => dominance.dominates(write.block, preheader)))
297
312
  continue;
@@ -31,6 +31,8 @@ import type { IrBody } from './model.js';
31
31
  * lattice, so a field and a local can never disagree about what an integer is.
32
32
  */
33
33
  export interface IntegerStorageCensus {
34
+ /** The file-scope cells whose one program-wide write is a bounded integer: declared `long long`. */
35
+ readonly integerCells: ReadonlySet<DeclarationId>;
34
36
  /** The slots whose C++ storage may be `long long`. */
35
37
  readonly slots: ReadonlySet<string>;
36
38
  /** What one body should be censused with, so its reads of those slots narrow too. */
@@ -89,6 +91,12 @@ export declare const integerParameterSlot: (owner: FunctionId | RegionId, ordina
89
91
  export declare const integerResultSlot: (owner: FunctionId | RegionId) => string;
90
92
  export interface IntegerStorageQuestion {
91
93
  readonly bodies: readonly IrBody[];
94
+ /**
95
+ * Whether a cell may be judged by `programCellIntegersOf`: its storage is one
96
+ * the compiled program alone writes, and every body that names it agrees on
97
+ * the `long long` carrier the answer implies.
98
+ */
99
+ readonly integerCellEligible?: (cell: DeclarationId) => boolean;
92
100
  /** The struct a carrier IS, or `null` when this census may not name one (a host struct, a non-record). */
93
101
  readonly structNameOf: (representation: Representation) => string | null;
94
102
  /** Every native struct whose storage a value exposes, including class bases. */
@@ -1,5 +1,5 @@
1
1
  import { walkRepresentation } from '../representation/model.js';
2
- import { integerLinearMagnitude, narrowableIntegersOf, widenIntegerMagnitude } from './integers.js';
2
+ import { integerLinearMagnitude, narrowableIntegersOf, programCellConstantsOf, programCellIntegersOf, widenIntegerMagnitude } from './integers.js';
3
3
  import { callableMemberSlot } from './callable-member-candidates.js';
4
4
  import { operandsOfIrOperation, resultOfIrOperation } from './queries.js';
5
5
  /**
@@ -249,6 +249,7 @@ const selfSumOf = (scan, slot, value) => {
249
249
  };
250
250
  const emptyFacts = { reads: new Map(), integral: new Set(), magnitudes: new Map() };
251
251
  export const emptyIntegerStorageCensus = {
252
+ integerCells: new Set(),
252
253
  slots: new Set(),
253
254
  factsOf: () => emptyFacts,
254
255
  entryCheckedFactsOf: () => emptyFacts
@@ -702,6 +703,15 @@ export const integerStorageCensusOf = (question) => {
702
703
  const scans = new Map();
703
704
  for (const body of question.bodies)
704
705
  scans.set(String(body.sourceOwner), scanBody(body, question, disqualified));
706
+ // Program-wide single-literal cells ride on every facts object handed out,
707
+ // so a body that only READS a module constant still sees its value.
708
+ const cellConstants = programCellConstantsOf(question.bodies);
709
+ const cellIntegers = programCellIntegersOf(question.bodies, question.integerCellEligible ?? (() => false), cellConstants);
710
+ const withCells = (facts) => ({
711
+ ...facts,
712
+ ...(cellConstants.size > 0 ? { cellConstants } : {}),
713
+ ...(cellIntegers.size > 0 ? { cellIntegers } : {})
714
+ });
705
715
  // A box whose payload this census cannot name may hold ANY struct -- a
706
716
  // member read off a boxed record is a box of a struct no conversion named --
707
717
  // so it strikes every field slot, and every method's signature, since a
@@ -802,11 +812,12 @@ export const integerStorageCensusOf = (question) => {
802
812
  // version of a body is rendered under -- which a program with no integral
803
813
  // slot at all still asks for, since the premise is the version's own.
804
814
  const censusFrom = (slots, settledSlots, magnitudes, facts) => ({
815
+ integerCells: new Set(cellIntegers.keys()),
805
816
  slots,
806
- factsOf: (owner) => facts.get(String(owner)) ?? emptyFacts,
817
+ factsOf: (owner) => withCells(facts.get(String(owner)) ?? emptyFacts),
807
818
  entryCheckedFactsOf: (owner, ordinals) => {
808
819
  const scan = scans.get(String(owner));
809
- const base = facts.get(String(owner)) ?? emptyFacts;
820
+ const base = withCells(facts.get(String(owner)) ?? emptyFacts);
810
821
  if (scan === undefined || ordinals.size === 0)
811
822
  return base;
812
823
  const checked = new Set([...ordinals].map((ordinal) => integerParameterSlot(owner, ordinal)));
@@ -835,7 +846,7 @@ export const integerStorageCensusOf = (question) => {
835
846
  const scan = scans.get(owner);
836
847
  if (scan === undefined || (scan.reads.size === 0 && scan.writes.size === 0 && scan.returns === null))
837
848
  continue;
838
- answers.set(owner, narrowableIntegersOf(body, { reads: scan.reads, integral, magnitudes }));
849
+ answers.set(owner, narrowableIntegersOf(body, withCells({ reads: scan.reads, integral, magnitudes })));
839
850
  }
840
851
  return answers;
841
852
  };
@@ -125,7 +125,47 @@ export interface IntegerStorageFacts {
125
125
  * answers otherwise stops the program instead of being truncated.
126
126
  */
127
127
  readonly guarded?: ReadonlyMap<IrValueId, number>;
128
+ /**
129
+ * Cells the WHOLE program writes exactly once, with an integer literal --
130
+ * `programCellConstantsOf`. A module `const PITCH = 122` is written by the
131
+ * module body and read by every method that indexes with it; the one-write
132
+ * rule below sees only its own body's writes, so without this a method
133
+ * reading the cell had none and every index derived from it was a double.
134
+ */
135
+ readonly cellConstants?: ReadonlyMap<DeclarationId, number>;
136
+ /**
137
+ * Cells the WHOLE program writes exactly once, with a value the writing body's
138
+ * own census proves an integer of bounded magnitude -- `programCellIntegersOf`.
139
+ * The generalization of `cellConstants` from a literal to `(w >> 1) | 0`: a
140
+ * body that only READS the cell has no write to examine, so without this
141
+ * every index built from a computed module constant was a double.
142
+ */
143
+ readonly cellIntegers?: ReadonlyMap<DeclarationId, IntegerMagnitude>;
128
144
  }
145
+ /**
146
+ * Which cells hold one integer literal at every read, program-wide: exactly
147
+ * one `binding-write` across all `bodies`, and its value a number constant
148
+ * that is a safe integer.
149
+ */
150
+ export declare const programCellConstantsOf: (bodies: readonly IrBody[]) => ReadonlyMap<DeclarationId, number>;
151
+ /**
152
+ * Which cells hold an integer of a known bound at every read, program-wide:
153
+ * exactly one `binding-write` across all `bodies`, and the writing body's
154
+ * census proves its value integral with a BOUNDED magnitude under 2^53.
155
+ *
156
+ * Bounded only, never linear: the write may run many times (a loop, a function
157
+ * called repeatedly), and only a bound holds for every execution. Exactly one
158
+ * static write is what makes the cell's content "that expression" at every read
159
+ * that follows it; a read that precedes it sees the cell's initial content,
160
+ * which `eligible` restricts to cells whose placement is a number scalar
161
+ * (zero-initialized, so 0 as a `long long` or as a double).
162
+ *
163
+ * Settled from below, as a least fixed point: the first round knows no cell, so
164
+ * a writer that reads another such cell (`HALF_W = WIDTH >> 1`) joins only after
165
+ * that cell has joined. Nothing is ever assumed and later struck, so a round
166
+ * that stops early is merely less precise, never unsound.
167
+ */
168
+ export declare const programCellIntegersOf: (bodies: readonly IrBody[], eligible: (cell: DeclarationId) => boolean, cellConstants: ReadonlyMap<DeclarationId, number>) => ReadonlyMap<DeclarationId, IntegerMagnitude>;
129
169
  export type IntegerMagnitude = {
130
170
  readonly kind: 'bounded';
131
171
  readonly limit: number;
@@ -9,6 +9,103 @@ export const emptyIntegerNarrowing = {
9
9
  dynamicRemainders: new Set(),
10
10
  roundingArithmetic: new Set()
11
11
  };
12
+ /**
13
+ * Which cells hold one integer literal at every read, program-wide: exactly
14
+ * one `binding-write` across all `bodies`, and its value a number constant
15
+ * that is a safe integer.
16
+ */
17
+ export const programCellConstantsOf = (bodies) => {
18
+ const writes = new Map();
19
+ const literal = new Map();
20
+ for (const body of bodies) {
21
+ const constantValues = new Map();
22
+ for (const blockId of body.blockOrder) {
23
+ for (const operation of body.blocks.get(blockId)?.operations ?? []) {
24
+ if (operation.kind === 'constant' && operation.literal === 'number') {
25
+ const value = integerText(operation.text);
26
+ if (value !== null)
27
+ constantValues.set(operation.result.id, value);
28
+ }
29
+ }
30
+ }
31
+ for (const blockId of body.blockOrder) {
32
+ for (const operation of body.blocks.get(blockId)?.operations ?? []) {
33
+ if (operation.kind !== 'binding-write')
34
+ continue;
35
+ writes.set(operation.declaration, (writes.get(operation.declaration) ?? 0) + 1);
36
+ literal.set(operation.declaration, constantValues.get(operation.value.value) ?? null);
37
+ }
38
+ }
39
+ }
40
+ const constants = new Map();
41
+ for (const [cell, count] of writes) {
42
+ const value = literal.get(cell);
43
+ if (count === 1 && value !== undefined && value !== null)
44
+ constants.set(cell, value);
45
+ }
46
+ return constants;
47
+ };
48
+ /**
49
+ * Which cells hold an integer of a known bound at every read, program-wide:
50
+ * exactly one `binding-write` across all `bodies`, and the writing body's
51
+ * census proves its value integral with a BOUNDED magnitude under 2^53.
52
+ *
53
+ * Bounded only, never linear: the write may run many times (a loop, a function
54
+ * called repeatedly), and only a bound holds for every execution. Exactly one
55
+ * static write is what makes the cell's content "that expression" at every read
56
+ * that follows it; a read that precedes it sees the cell's initial content,
57
+ * which `eligible` restricts to cells whose placement is a number scalar
58
+ * (zero-initialized, so 0 as a `long long` or as a double).
59
+ *
60
+ * Settled from below, as a least fixed point: the first round knows no cell, so
61
+ * a writer that reads another such cell (`HALF_W = WIDTH >> 1`) joins only after
62
+ * that cell has joined. Nothing is ever assumed and later struck, so a round
63
+ * that stops early is merely less precise, never unsound.
64
+ */
65
+ export const programCellIntegersOf = (bodies, eligible, cellConstants) => {
66
+ const writeCounts = new Map();
67
+ for (const body of bodies)
68
+ for (const blockId of body.blockOrder)
69
+ for (const operation of body.blocks.get(blockId)?.operations ?? [])
70
+ if (operation.kind === 'binding-write')
71
+ writeCounts.set(operation.declaration, (writeCounts.get(operation.declaration) ?? 0) + 1);
72
+ const pending = new Map();
73
+ for (const body of bodies)
74
+ for (const blockId of body.blockOrder)
75
+ for (const operation of body.blocks.get(blockId)?.operations ?? []) {
76
+ if (operation.kind !== 'binding-write' || writeCounts.get(operation.declaration) !== 1)
77
+ continue;
78
+ if (!isNumberScalar(operation.value) || !eligible(operation.declaration))
79
+ continue;
80
+ const writes = pending.get(body) ?? [];
81
+ writes.push({ cell: operation.declaration, value: operation.value });
82
+ pending.set(body, writes);
83
+ }
84
+ const cells = new Map();
85
+ for (let round = 0; round < 16 && pending.size > 0; round++) {
86
+ let changed = false;
87
+ for (const [body, writes] of [...pending]) {
88
+ const narrowed = narrowableIntegersOf(body, { ...noStorageFacts, cellConstants, cellIntegers: cells });
89
+ const unresolved = writes.filter(({ cell, value }) => {
90
+ const magnitude = narrowed.magnitudes.get(value.value);
91
+ if (!narrowed.integral.has(value.value) || magnitude === undefined || magnitude.kind !== 'bounded')
92
+ return true;
93
+ if (magnitude.limit > exactIntegerLimit)
94
+ return true;
95
+ cells.set(cell, magnitude);
96
+ changed = true;
97
+ return false;
98
+ });
99
+ if (unresolved.length === 0)
100
+ pending.delete(body);
101
+ else
102
+ pending.set(body, unresolved);
103
+ }
104
+ if (!changed)
105
+ break;
106
+ }
107
+ return cells;
108
+ };
12
109
  const noStorageFacts = { reads: new Map(), integral: new Set(), magnitudes: new Map() };
13
110
  /** 2^53: the last integer a double can hold with every integer below it. */
14
111
  const exactIntegerLimit = 9007199254740992;
@@ -105,6 +202,15 @@ const product = (left, right) => {
105
202
  };
106
203
  /** 2^32, the width every ECMA-262 bitwise operator reduces to before it computes. */
107
204
  const bitwiseWidth = 4294967296;
205
+ /**
206
+ * 2^31: the magnitude of a signed 32-bit result. `|`, `&`, `^`, `<<`, `>>` and
207
+ * `~` answer ToInt32 of their result, in [-2^31, 2^31); only `>>>` reaches
208
+ * 2^32. The difference matters for products: two `| 0` int32s multiply to
209
+ * under 2^62, which the 64-bit carrier holds, while two 2^32 bounds give 2^64
210
+ * and refuse the whole chain -- `(cell + 1) * pitch` over a runtime grid
211
+ * size then indexes a typed array through the double ToInt32.
212
+ */
213
+ const int32Magnitude = 2147483648;
108
214
  /**
109
215
  * The largest `length` (2^40) and `byteLength`/`byteOffset` (2^43) a typed
110
216
  * array can have: the runtime's stated implementation limit
@@ -159,9 +265,17 @@ export const narrowableIntegersOf = (body, storage = noStorageFacts) => {
159
265
  // Math.imul always returns a signed int32, including for fractional, NaN,
160
266
  // infinite and overflowing inputs. Its callable ABI alone says only number.
161
267
  const imulResults = new Set();
268
+ // `Math.min`/`Math.max` of two integers is one of them: an integer exactly
269
+ // when both arguments are, no larger than the larger of the two. Without
270
+ // this a clamped row index (`Math.max(cell - 1, 0)`) was a double, and so
271
+ // was every index derived from it -- soft-float on every pixel of Bloom's
272
+ // upscaler.
273
+ const minMaxResults = new Map();
162
274
  for (const [call, intrinsic] of numericIntrinsicsOf(body).calls) {
163
275
  if (intrinsic === 'imul' && call.result)
164
276
  imulResults.add(call.result.id);
277
+ else if (call.result)
278
+ minMaxResults.set(call.result.id, call.arguments);
165
279
  }
166
280
  const definitions = new Map();
167
281
  const computes = new Map();
@@ -246,7 +360,7 @@ export const narrowableIntegersOf = (body, storage = noStorageFacts) => {
246
360
  continue;
247
361
  const written = cellWrites.get(cell) ?? [];
248
362
  const only = written.length === 1 ? written[0] : undefined;
249
- const literal = only === undefined ? undefined : constants.get(only.value.value);
363
+ const literal = only === undefined ? (written.length === 0 ? storage.cellConstants?.get(cell) : undefined) : constants.get(only.value.value);
250
364
  if (literal !== undefined)
251
365
  constants.set(value, literal);
252
366
  }
@@ -290,6 +404,9 @@ export const narrowableIntegersOf = (body, storage = noStorageFacts) => {
290
404
  const producesInteger = (value) => {
291
405
  if (imulResults.has(value))
292
406
  return true;
407
+ const chosen = minMaxResults.get(value);
408
+ if (chosen !== undefined)
409
+ return chosen.every((argument) => integral.has(argument.value));
293
410
  if (constants.has(value))
294
411
  return true;
295
412
  if (lengthReads.has(value))
@@ -464,7 +581,9 @@ export const narrowableIntegersOf = (body, storage = noStorageFacts) => {
464
581
  }
465
582
  openCells.add(cell);
466
583
  const written = cellWrites.get(cell) ?? [];
467
- let seeds = written.length > 0 ? { kind: 'bounded', limit: 0 } : null;
584
+ // A cell this body never writes is whatever the rest of the program wrote
585
+ // into it: nothing, unless the program-wide census proved its one write.
586
+ let seeds = written.length > 0 ? { kind: 'bounded', limit: 0 } : (storage.cellIntegers?.get(cell) ?? null);
468
587
  let step = null;
469
588
  const stepBlocks = [];
470
589
  for (const write of written) {
@@ -505,6 +624,13 @@ export const narrowableIntegersOf = (body, storage = noStorageFacts) => {
505
624
  const computeMagnitude = (operand) => {
506
625
  if (imulResults.has(operand.value))
507
626
  return boundedBy(2 ** 31);
627
+ const chosen = minMaxResults.get(operand.value);
628
+ if (chosen !== undefined) {
629
+ let answer = { kind: 'bounded', limit: 0 };
630
+ for (const argument of chosen)
631
+ answer = widen(answer, magnitudeOfValue(argument));
632
+ return answer;
633
+ }
508
634
  const constant = constants.get(operand.value);
509
635
  if (constant !== undefined)
510
636
  return boundedBy(Math.abs(constant));
@@ -552,7 +678,7 @@ export const narrowableIntegersOf = (body, storage = noStorageFacts) => {
552
678
  // `-x` and `+x` keep the magnitude; `~x` is a 32-bit result like every
553
679
  // other bitwise operator.
554
680
  if (compute.operator === '~')
555
- return boundedBy(bitwiseWidth);
681
+ return boundedBy(int32Magnitude);
556
682
  if (compute.operator !== '-' && compute.operator !== '+')
557
683
  return null;
558
684
  return magnitudeOfValue(left);
@@ -564,12 +690,13 @@ export const narrowableIntegersOf = (body, storage = noStorageFacts) => {
564
690
  // A mask by a non-negative constant bounds the result at the mask; any
565
691
  // other AND is still a 32-bit quantity.
566
692
  const mask = constants.get(right.value) ?? constants.get(left.value);
567
- return mask !== undefined && mask >= 0 ? boundedBy(mask) : boundedBy(bitwiseWidth);
693
+ return mask !== undefined && mask >= 0 ? boundedBy(mask) : boundedBy(int32Magnitude);
568
694
  }
569
695
  case '|':
570
696
  case '^':
571
697
  case '<<':
572
698
  case '>>':
699
+ return boundedBy(int32Magnitude);
573
700
  case '>>>':
574
701
  return boundedBy(bitwiseWidth);
575
702
  case '+':
@@ -617,6 +744,12 @@ export const narrowableIntegersOf = (body, storage = noStorageFacts) => {
617
744
  if (magnitudeOfCell(cell) !== null)
618
745
  bindings.add(cell);
619
746
  }
747
+ // A cell stored as `long long` program-wide (its one write proved integral)
748
+ // is integer storage in every body that reads it, whether or not it writes.
749
+ for (const cell of readsCell.values()) {
750
+ if (storage.cellIntegers?.has(cell) === true && magnitudeOfCell(cell) !== null)
751
+ bindings.add(cell);
752
+ }
620
753
  // Only the values that HAVE a magnitude: `valueMagnitudes` records a refusal
621
754
  // as `null`, and a consumer reading one back would take "refused" for
622
755
  // "unknown" and re-derive it.
@@ -1,6 +1,6 @@
1
1
  import type { IrValueId } from '../identity/ids.js';
2
2
  import type { CallOperation, IrBody } from './model.js';
3
- export type NumericIntrinsic = 'imul';
3
+ export type NumericIntrinsic = 'imul' | 'min' | 'max';
4
4
  /**
5
5
  * Language builtin calls authenticated by their native protocol, never by a
6
6
  * source identifier spelling. A user object named Math has no such protocol.
@@ -1,5 +1,6 @@
1
1
  import { allOperationsOf } from './model.js';
2
2
  import { operandsOfIrOperation } from './queries.js';
3
+ const twoArgumentIntrinsics = new Set(['imul', 'min', 'max']);
3
4
  /**
4
5
  * Language builtin calls authenticated by their native protocol, never by a
5
6
  * source identifier spelling. A user object named Math has no such protocol.
@@ -25,8 +26,8 @@ export const numericIntrinsicsOf = (body) => {
25
26
  if (receiver.kind === 'native-handle' &&
26
27
  receiver.native === null &&
27
28
  receiver.protocol === 'Math' &&
28
- keys.get(operation.key.value) === 'imul') {
29
- callees.set(operation.result.id, 'imul');
29
+ twoArgumentIntrinsics.has(keys.get(operation.key.value) ?? '')) {
30
+ callees.set(operation.result.id, keys.get(operation.key.value));
30
31
  }
31
32
  }
32
33
  }
@@ -1209,8 +1209,31 @@ unwrittenMembers = new Map()) => {
1209
1209
  return null;
1210
1210
  return kept.length === 1 ? derive(kept[0]) : deriveUnion({ kind: 'union', members: kept });
1211
1211
  };
1212
+ /**
1213
+ * A compiled class instance beside a standard TYPED ARRAY: no value is both.
1214
+ *
1215
+ * `body instanceof Uint8Array` over a declared `string | ReadableStream |
1216
+ * null` (`@hono/node-server`'s `responseViaCache`, listener.ts:186) narrows
1217
+ * the class arm by intersecting rather than discarding it, so the taken
1218
+ * branch reads `ReadableStream & Uint8Array`. A class instance's carrier is
1219
+ * its own struct, and a class-instance shape can name a native `Map`/`Set`,
1220
+ * `Error` or `Promise` base but never typed-array storage, so the instance
1221
+ * cannot be the native view the other member requires. The branch is dead;
1222
+ * left unstated, the nominal-class branch below reads the typed array as
1223
+ * plain structure and answers the class, and the branch then owes a
1224
+ * conversion from that class into whatever the typed array is handed to.
1225
+ */
1226
+ const isUninhabitedClassTypedArrayIntersection = (substantive) => {
1227
+ const typedArray = substantive.some((member) => {
1228
+ const memberShape = shapeOf(member);
1229
+ return memberShape?.kind === 'declared' && elements.forDeclaration(memberShape.declaration) !== null;
1230
+ });
1231
+ return typedArray && substantive.some((member) => nominalClassDeclarationOf(member) !== null);
1232
+ };
1212
1233
  /** ONE answer to "can no value have this intersection's type", for the carrier and the reachability question alike. */
1213
- const isUninhabitedIntersection = (substantive) => isUninhabitedNominalIntersection(substantive) || isUninhabitedPrimitiveIntersection(substantive);
1234
+ const isUninhabitedIntersection = (substantive) => isUninhabitedNominalIntersection(substantive) ||
1235
+ isUninhabitedPrimitiveIntersection(substantive) ||
1236
+ isUninhabitedClassTypedArrayIntersection(substantive);
1214
1237
  const intersectionMemberKind = (member) => intersectionMemberKindOf(shapeOf, member);
1215
1238
  const isPrimitiveValueMember = (member) => isPrimitiveValueShape(shapeOf, member);
1216
1239
  const flattenedIntersectionMembers = createIntersectionFlattener(shapeOf, (declaration) => Boolean(binding.forDeclaration(declaration)?.native));
@@ -1439,6 +1462,12 @@ unwrittenMembers = new Map()) => {
1439
1462
  // object members need no carrier of their own for this decision, so leave
1440
1463
  // them unexpanded. Other members still derive normally, preserving the
1441
1464
  // refusal for incompatible physical carriers.
1465
+ //
1466
+ // Asked before either the typed-array or the nominal-class reduction:
1467
+ // each would otherwise pick one of the two members of a pair that has no
1468
+ // inhabitant at all (`isUninhabitedClassTypedArrayIntersection`).
1469
+ if (isUninhabitedClassTypedArrayIntersection(substantive))
1470
+ return { kind: 'void' };
1442
1471
  const intersectionCarriers = substantive.map((member) => {
1443
1472
  const memberShape = shapeOf(member);
1444
1473
  if (memberShape?.kind === 'declared') {
@@ -15,6 +15,7 @@ import { intrinsicPropertyCallOf } from './normalize/intrinsic-property-call.js'
15
15
  import { createStructuralMapper } from './normalize/structural.js';
16
16
  import { createSloppyAbsenceCensus, noSloppyAbsence } from './normalize/sloppy-absence.js';
17
17
  import { censusRecordStandInArms } from './normalize/record-stand-in-arms.js';
18
+ import { censusAssertedArgumentArms } from './normalize/asserted-argument-arms.js';
18
19
  import { censusSuppressedWriteArms } from './normalize/suppressed-write-arms.js';
19
20
  import { withOverrideFieldArms } from './normalize/override-field-arms.js';
20
21
  import { censusDeclaredMembers } from './normalize/structural-declarations.js';
@@ -725,7 +726,10 @@ export const runFrontend = (input) => {
725
726
  // keeps its own arm -- see `suppressed-write-arms.ts`.
726
727
  // A field a subclass redeclares as another record keeps each declaration's
727
728
  // record as an arm of its one slot -- see `override-field-arms.ts`.
728
- withOverrideFieldArms(compiled.checker, compiled.sourceFiles, censusSuppressedWriteArms(compiled.checker, compiled.sourceFiles, reachable, valueFlow)));
729
+ withOverrideFieldArms(compiled.checker, compiled.sourceFiles, censusSuppressedWriteArms(compiled.checker, compiled.sourceFiles, reachable, valueFlow)),
730
+ // A record an argument asserts through `unknown` into a union keeps its
731
+ // own arm of that union -- see `asserted-argument-arms.ts`.
732
+ censusAssertedArgumentArms(compiled.checker, compiled.sourceFiles, reachable));
729
733
  // The frontend's evidence-policy tables: built from the same
730
734
  // `identities`/`valueFlow`/`reachable` the fixpoint above already settled,
731
735
  // right after `types` exists so the agreement instrument can ask the
@@ -0,0 +1,38 @@
1
+ import ts from 'typescript';
2
+ import { type ProgramReachability } from './reachability.js';
3
+ /**
4
+ * A record handed to a union-typed parameter through an explicit
5
+ * `value as unknown as T` assertion, kept as one more native arm of that union.
6
+ *
7
+ * `@hono/node-server`'s websocket upgrade (websocket.ts) builds
8
+ *
9
+ * const env: UpgradeBindings = { incoming: request, outgoing: undefined, wss, [WAIT_FOR_WEBSOCKET_SYMBOL]: waitForWebSocket }
10
+ * await fetchCallback(createUpgradeRequest(request), env as unknown as Parameters<FetchCallback>[1])
11
+ *
12
+ * where the parameter is `HttpBindings | Http2Bindings`. The assertion emits
13
+ * nothing in JavaScript: the callee receives `env` itself, and the program
14
+ * depends on that identity -- hono's helper reads `c.env as UpgradeBindings`,
15
+ * writes `env[CONNECTION_SYMBOL_KEY]`, and the upgrade handler reads it back
16
+ * off the very object it built. A converting copy would lose that write, and
17
+ * a box would be a dynamic carrier for a statically typed record.
18
+ *
19
+ * So the union carries the asserted record's own carrier beside its declared
20
+ * arms. Keyed by the union TYPE, as `record-stand-in-arms.ts` keys its arms,
21
+ * because the parameter here belongs to a callable TYPE (`FetchCallback`):
22
+ * every function value stored into that slot, and the call through it, must
23
+ * agree on one carrier, and the union type is the one thing they share.
24
+ * Adding an arm is a superset -- every value already admitted converts as
25
+ * before -- and a read of a member the record lacks answers through the
26
+ * record's own arm or refuses, never reinterprets one layout as another.
27
+ *
28
+ * Sound only where no narrowing can route the extra arm somewhere the checker
29
+ * says no value goes: any test on a value of the union that can tell its arms
30
+ * apart -- `instanceof`, `in`, `typeof`, a discriminant member, or a member the
31
+ * record lacks -- withdraws the arm, and the certification refusal stands.
32
+ */
33
+ export interface AssertedArgumentArmCensus {
34
+ /** The asserted records a union type carries beside its declared arms, or `null`. */
35
+ readonly armsOf: (union: ts.Type) => readonly ts.Type[] | null;
36
+ }
37
+ export declare const emptyAssertedArgumentArmCensus: AssertedArgumentArmCensus;
38
+ export declare const censusAssertedArgumentArms: (checker: ts.TypeChecker, files: readonly ts.SourceFile[], reachable: ProgramReachability) => AssertedArgumentArmCensus;