@geastack/compiler 1.0.23 → 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.
@@ -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, programCellConstantsOf, 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
@@ -705,7 +706,12 @@ export const integerStorageCensusOf = (question) => {
705
706
  // Program-wide single-literal cells ride on every facts object handed out,
706
707
  // so a body that only READS a module constant still sees its value.
707
708
  const cellConstants = programCellConstantsOf(question.bodies);
708
- const withCells = (facts) => (cellConstants.size > 0 ? { ...facts, cellConstants } : facts);
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
+ });
709
715
  // A box whose payload this census cannot name may hold ANY struct -- a
710
716
  // member read off a boxed record is a box of a struct no conversion named --
711
717
  // so it strikes every field slot, and every method's signature, since a
@@ -806,6 +812,7 @@ export const integerStorageCensusOf = (question) => {
806
812
  // version of a body is rendered under -- which a program with no integral
807
813
  // slot at all still asks for, since the premise is the version's own.
808
814
  const censusFrom = (slots, settledSlots, magnitudes, facts) => ({
815
+ integerCells: new Set(cellIntegers.keys()),
809
816
  slots,
810
817
  factsOf: (owner) => withCells(facts.get(String(owner)) ?? emptyFacts),
811
818
  entryCheckedFactsOf: (owner, ordinals) => {
@@ -133,6 +133,14 @@ export interface IntegerStorageFacts {
133
133
  * reading the cell had none and every index derived from it was a double.
134
134
  */
135
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>;
136
144
  }
137
145
  /**
138
146
  * Which cells hold one integer literal at every read, program-wide: exactly
@@ -140,6 +148,24 @@ export interface IntegerStorageFacts {
140
148
  * that is a safe integer.
141
149
  */
142
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>;
143
169
  export type IntegerMagnitude = {
144
170
  readonly kind: 'bounded';
145
171
  readonly limit: number;
@@ -45,6 +45,67 @@ export const programCellConstantsOf = (bodies) => {
45
45
  }
46
46
  return constants;
47
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
+ };
48
109
  const noStorageFacts = { reads: new Map(), integral: new Set(), magnitudes: new Map() };
49
110
  /** 2^53: the last integer a double can hold with every integer below it. */
50
111
  const exactIntegerLimit = 9007199254740992;
@@ -141,6 +202,15 @@ const product = (left, right) => {
141
202
  };
142
203
  /** 2^32, the width every ECMA-262 bitwise operator reduces to before it computes. */
143
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;
144
214
  /**
145
215
  * The largest `length` (2^40) and `byteLength`/`byteOffset` (2^43) a typed
146
216
  * array can have: the runtime's stated implementation limit
@@ -511,7 +581,9 @@ export const narrowableIntegersOf = (body, storage = noStorageFacts) => {
511
581
  }
512
582
  openCells.add(cell);
513
583
  const written = cellWrites.get(cell) ?? [];
514
- 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);
515
587
  let step = null;
516
588
  const stepBlocks = [];
517
589
  for (const write of written) {
@@ -606,7 +678,7 @@ export const narrowableIntegersOf = (body, storage = noStorageFacts) => {
606
678
  // `-x` and `+x` keep the magnitude; `~x` is a 32-bit result like every
607
679
  // other bitwise operator.
608
680
  if (compute.operator === '~')
609
- return boundedBy(bitwiseWidth);
681
+ return boundedBy(int32Magnitude);
610
682
  if (compute.operator !== '-' && compute.operator !== '+')
611
683
  return null;
612
684
  return magnitudeOfValue(left);
@@ -618,12 +690,13 @@ export const narrowableIntegersOf = (body, storage = noStorageFacts) => {
618
690
  // A mask by a non-negative constant bounds the result at the mask; any
619
691
  // other AND is still a 32-bit quantity.
620
692
  const mask = constants.get(right.value) ?? constants.get(left.value);
621
- return mask !== undefined && mask >= 0 ? boundedBy(mask) : boundedBy(bitwiseWidth);
693
+ return mask !== undefined && mask >= 0 ? boundedBy(mask) : boundedBy(int32Magnitude);
622
694
  }
623
695
  case '|':
624
696
  case '^':
625
697
  case '<<':
626
698
  case '>>':
699
+ return boundedBy(int32Magnitude);
627
700
  case '>>>':
628
701
  return boundedBy(bitwiseWidth);
629
702
  case '+':
@@ -671,6 +744,12 @@ export const narrowableIntegersOf = (body, storage = noStorageFacts) => {
671
744
  if (magnitudeOfCell(cell) !== null)
672
745
  bindings.add(cell);
673
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
+ }
674
753
  // Only the values that HAVE a magnitude: `valueMagnitudes` records a refusal
675
754
  // as `null`, and a consumer reading one back would take "refused" for
676
755
  // "unknown" and re-derive it.
@@ -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;
@@ -0,0 +1,182 @@
1
+ import ts from 'typescript';
2
+ import { forEachReachableStatement } from './reachability.js';
3
+ export const emptyAssertedArgumentArmCensus = { armsOf: () => null };
4
+ const presentMembersOf = (type) => (type.isUnion() ? type.types : [type]).filter((member) => (member.flags & (ts.TypeFlags.Undefined | ts.TypeFlags.Null)) === 0);
5
+ const containsTypeParameter = (checker, type, depth = 0) => {
6
+ if (depth > 4)
7
+ return true;
8
+ if (type.flags & ts.TypeFlags.TypeParameter)
9
+ return true;
10
+ if (type.isUnionOrIntersection())
11
+ return type.types.some((member) => containsTypeParameter(checker, member, depth + 1));
12
+ if ((type.flags & ts.TypeFlags.Object) !== 0 && (type.objectFlags & ts.ObjectFlags.Reference) !== 0)
13
+ return checker.getTypeArguments(type).some((argument) => containsTypeParameter(checker, argument, depth + 1));
14
+ return false;
15
+ };
16
+ const unwrapParens = (node) => (ts.isParenthesizedExpression(node) ? unwrapParens(node.expression) : node);
17
+ /**
18
+ * A plain record: an object type with no call or construct signature that is
19
+ * not a class instance, an array, or a tuple. A class arm is nominal, so a
20
+ * record beside it would be a second layout the class's methods never see.
21
+ */
22
+ const isPlainRecord = (checker, type) => (type.flags & ts.TypeFlags.Object) !== 0 &&
23
+ ((type.getSymbol()?.flags ?? 0) & ts.SymbolFlags.Class) === 0 &&
24
+ type.getCallSignatures().length === 0 &&
25
+ type.getConstructSignatures().length === 0 &&
26
+ !checker.isArrayType(type) &&
27
+ !checker.isTupleType(type);
28
+ /** Whether a narrowing condition reads `node` -- the walk `record-stand-in-arms.ts` states. */
29
+ const narrows = (node) => {
30
+ let current = node;
31
+ for (;;) {
32
+ const parent = current.parent;
33
+ if (!parent)
34
+ return false;
35
+ if (ts.isParenthesizedExpression(parent) ||
36
+ ts.isTypeOfExpression(parent) ||
37
+ ts.isNonNullExpression(parent) ||
38
+ (ts.isPrefixUnaryExpression(parent) && parent.operator === ts.SyntaxKind.ExclamationToken) ||
39
+ (ts.isPropertyAccessExpression(parent) && parent.expression === current) ||
40
+ (ts.isElementAccessExpression(parent) && parent.expression === current)) {
41
+ current = parent;
42
+ continue;
43
+ }
44
+ if (ts.isBinaryExpression(parent)) {
45
+ switch (parent.operatorToken.kind) {
46
+ case ts.SyntaxKind.AmpersandAmpersandToken:
47
+ case ts.SyntaxKind.BarBarToken:
48
+ case ts.SyntaxKind.QuestionQuestionToken:
49
+ case ts.SyntaxKind.EqualsEqualsEqualsToken:
50
+ case ts.SyntaxKind.ExclamationEqualsEqualsToken:
51
+ case ts.SyntaxKind.EqualsEqualsToken:
52
+ case ts.SyntaxKind.ExclamationEqualsToken:
53
+ case ts.SyntaxKind.InstanceOfKeyword:
54
+ case ts.SyntaxKind.InKeyword:
55
+ current = parent;
56
+ continue;
57
+ default:
58
+ return false;
59
+ }
60
+ }
61
+ if (ts.isIfStatement(parent) || ts.isWhileStatement(parent) || ts.isDoStatement(parent))
62
+ return parent.expression === current;
63
+ if (ts.isForStatement(parent))
64
+ return parent.condition === current;
65
+ if (ts.isConditionalExpression(parent))
66
+ return parent.condition === current;
67
+ if (ts.isSwitchStatement(parent))
68
+ return parent.expression === current;
69
+ if (ts.isCaseClause(parent))
70
+ return parent.expression === current;
71
+ return false;
72
+ }
73
+ };
74
+ export const censusAssertedArgumentArms = (checker, files, reachable) => {
75
+ /** The seed one call argument states, when it is `record as unknown as Union` landing where the union is the parameter. */
76
+ const seedOf = (argument) => {
77
+ const outer = unwrapParens(argument);
78
+ if (!ts.isAsExpression(outer) && !ts.isTypeAssertionExpression(outer))
79
+ return null;
80
+ const inner = unwrapParens(outer.expression);
81
+ if (!ts.isAsExpression(inner) && !ts.isTypeAssertionExpression(inner))
82
+ return null;
83
+ if ((checker.getTypeFromTypeNode(inner.type).flags & ts.TypeFlags.Unknown) === 0)
84
+ return null;
85
+ const union = checker.getTypeFromTypeNode(outer.type);
86
+ const record = checker.getTypeAtLocation(unwrapParens(inner.expression));
87
+ if (!union.isUnion() || containsTypeParameter(checker, union) || containsTypeParameter(checker, record))
88
+ return null;
89
+ const homes = presentMembersOf(union);
90
+ if (homes.length < 2 || !homes.every((home) => isPlainRecord(checker, home)))
91
+ return null;
92
+ if (!isPlainRecord(checker, record) || homes.includes(record) || checker.isTypeAssignableTo(record, union))
93
+ return null;
94
+ return { union, record };
95
+ };
96
+ const seeds = [];
97
+ for (const file of files) {
98
+ if (file.isDeclarationFile)
99
+ continue;
100
+ const visit = (node) => {
101
+ if (reachable.memberIsPruned(node))
102
+ return;
103
+ if (ts.isCallExpression(node) || ts.isNewExpression(node)) {
104
+ const argumentsList = node.arguments ?? [];
105
+ const signature = checker.getResolvedSignature(node);
106
+ argumentsList.forEach((argument, index) => {
107
+ if (argumentsList.slice(0, index + 1).some(ts.isSpreadElement))
108
+ return;
109
+ const seed = seedOf(argument);
110
+ const parameter = signature?.getParameters()[index];
111
+ if (!seed || !parameter || checker.getTypeOfSymbol(parameter) !== seed.union)
112
+ return;
113
+ seeds.push(seed);
114
+ });
115
+ }
116
+ ts.forEachChild(node, visit);
117
+ };
118
+ forEachReachableStatement(reachable, file, visit);
119
+ }
120
+ if (seeds.length === 0)
121
+ return emptyAssertedArgumentArmCensus;
122
+ const records = new Map();
123
+ for (const seed of seeds) {
124
+ const held = records.get(seed.union);
125
+ if (!held)
126
+ records.set(seed.union, [seed.record]);
127
+ else if (!held.includes(seed.record))
128
+ held.push(seed.record);
129
+ }
130
+ /**
131
+ * Whether a narrowing test on a value of `union` can tell its arms apart.
132
+ * Truthiness and nullishness of the value itself cannot -- every arm is an
133
+ * object -- and neither can a member every arm states with a non-unit type.
134
+ */
135
+ const discriminates = (use, union) => {
136
+ const parent = use.parent;
137
+ if (!parent)
138
+ return true;
139
+ if (ts.isPropertyAccessExpression(parent) || ts.isElementAccessExpression(parent)) {
140
+ const key = ts.isPropertyAccessExpression(parent)
141
+ ? parent.name.text
142
+ : ts.isStringLiteralLike(parent.argumentExpression)
143
+ ? parent.argumentExpression.text
144
+ : null;
145
+ if (key === null)
146
+ return true;
147
+ return [...presentMembersOf(union), ...(records.get(union) ?? [])].some((arm) => {
148
+ const property = arm.getProperty(key);
149
+ return !property || (checker.getTypeOfSymbol(property).flags & ts.TypeFlags.Unit) !== 0;
150
+ });
151
+ }
152
+ if (ts.isBinaryExpression(parent)) {
153
+ const operator = parent.operatorToken.kind;
154
+ return operator === ts.SyntaxKind.InstanceOfKeyword || operator === ts.SyntaxKind.InKeyword;
155
+ }
156
+ return ts.isTypeOfExpression(parent);
157
+ };
158
+ const withdrawn = new Set();
159
+ for (const file of files) {
160
+ if (file.isDeclarationFile)
161
+ continue;
162
+ const visit = (node) => {
163
+ if (reachable.memberIsPruned(node) || ts.isTypeNode(node))
164
+ return;
165
+ if ((ts.isIdentifier(node) || ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) && narrows(node)) {
166
+ const type = checker.getTypeAtLocation(node);
167
+ if (records.has(type) && discriminates(node, type))
168
+ withdrawn.add(type);
169
+ }
170
+ ts.forEachChild(node, visit);
171
+ };
172
+ forEachReachableStatement(reachable, file, visit);
173
+ }
174
+ for (const union of withdrawn)
175
+ records.delete(union);
176
+ if (process.env['GEA_BINDING_DEBUG'])
177
+ for (const seed of seeds)
178
+ console.error(`[ASSERTED-ARGUMENT-ARM] ${checker.typeToString(seed.record)} into ${checker.typeToString(seed.union)}${withdrawn.has(seed.union) ? ' :: withdrawn' : ''}`);
179
+ if (records.size === 0)
180
+ return emptyAssertedArgumentArmCensus;
181
+ return { armsOf: (union) => records.get(union) ?? null };
182
+ };
@@ -4,6 +4,7 @@ import type { ValueFlowIndex } from './flow/model.js';
4
4
  import { type SloppyAbsenceCensus } from './sloppy-absence.js';
5
5
  import { type SuppressedWriteArmCensus } from './suppressed-write-arms.js';
6
6
  import { type RecordStandInArmCensus } from './record-stand-in-arms.js';
7
+ import { type AssertedArgumentArmCensus } from './asserted-argument-arms.js';
7
8
  import { type RecordLinkFamilyCensus } from './record-link-families.js';
8
9
  import { type DeclaredMemberCensus } from './structural-declarations.js';
9
10
  import type { DeclarationId, StructuralTypeId } from '../../identity/ids.js';
@@ -203,7 +204,7 @@ export interface StructuralMapper {
203
204
  */
204
205
  readonly classCopies: () => ReadonlyMap<DeclarationId, readonly ClassCopyKey[]>;
205
206
  }
206
- export declare const createStructuralMapper: (checker: ts.TypeChecker, identities: IdentityTable, table: StructuralTypeTable, instantiations?: InstantiationCensus, specializations?: SpecializationCensus, parameters?: ParameterBindingCensus, absent?: AbsentGlobalCensus, collections?: CollectionBindingCensus, bags?: ObjectBagCensus, flow?: ValueFlowIndex, families?: InterfaceFamilyCensus, moduleRecords?: CommonJsModuleRecordCensus, declaredMembers?: DeclaredMemberCensus, isIntrinsicDescriptorCall?: (call: ts.CallExpression) => boolean, standIns?: RecordStandInArmCensus, linkFamilies?: RecordLinkFamilyCensus, sloppyAbsence?: SloppyAbsenceCensus, suppressedWrites?: SuppressedWriteArmCensus) => StructuralMapper;
207
+ export declare const createStructuralMapper: (checker: ts.TypeChecker, identities: IdentityTable, table: StructuralTypeTable, instantiations?: InstantiationCensus, specializations?: SpecializationCensus, parameters?: ParameterBindingCensus, absent?: AbsentGlobalCensus, collections?: CollectionBindingCensus, bags?: ObjectBagCensus, flow?: ValueFlowIndex, families?: InterfaceFamilyCensus, moduleRecords?: CommonJsModuleRecordCensus, declaredMembers?: DeclaredMemberCensus, isIntrinsicDescriptorCall?: (call: ts.CallExpression) => boolean, standIns?: RecordStandInArmCensus, linkFamilies?: RecordLinkFamilyCensus, sloppyAbsence?: SloppyAbsenceCensus, suppressedWrites?: SuppressedWriteArmCensus, assertedArguments?: AssertedArgumentArmCensus) => StructuralMapper;
207
208
  /**
208
209
  * `JSON.stringify(value)` from the default lib over a value that may have no
209
210
  * JSON form, so the call may return `undefined` although the lib declares
@@ -6,6 +6,7 @@ import { noSloppyAbsence, withAbsences } from './sloppy-absence.js';
6
6
  import { emptySuppressedWriteArmCensus } from './suppressed-write-arms.js';
7
7
  import { recordStorageFamilies } from './record-storage-families.js';
8
8
  import { emptyRecordStandInArmCensus } from './record-stand-in-arms.js';
9
+ import { emptyAssertedArgumentArmCensus } from './asserted-argument-arms.js';
9
10
  import { emptyRecordLinkFamilyCensus } from './record-link-families.js';
10
11
  import { bivariantSlotArrayAliasTypeOf, bivariantSlotBindingTypeOf, bivariantSlotElementTypeOf, bivariantSlotParameterTypeOf, bivariantSlotReadTypeOf } from './bivariant-slot-parameter.js';
11
12
  import { emptyDeclaredMemberCensus } from './structural-declarations.js';
@@ -100,7 +101,7 @@ const nativeErrorNames = new Set([
100
101
  'TypeError',
101
102
  'URIError'
102
103
  ]);
103
- export const createStructuralMapper = (checker, identities, table, instantiations = emptyInstantiationCensus, specializations = emptySpecializationCensus, parameters = emptyParameterBindingCensus, absent = emptyAbsentGlobalCensus, collections = emptyCollectionBindingCensus, bags = emptyObjectBagCensus, flow, families = emptyInterfaceFamilyCensus, moduleRecords = emptyCommonJsModuleRecordCensus, declaredMembers = emptyDeclaredMemberCensus, isIntrinsicDescriptorCall = () => false, standIns = emptyRecordStandInArmCensus, linkFamilies = emptyRecordLinkFamilyCensus, sloppyAbsence = noSloppyAbsence, suppressedWrites = emptySuppressedWriteArmCensus) => {
104
+ export const createStructuralMapper = (checker, identities, table, instantiations = emptyInstantiationCensus, specializations = emptySpecializationCensus, parameters = emptyParameterBindingCensus, absent = emptyAbsentGlobalCensus, collections = emptyCollectionBindingCensus, bags = emptyObjectBagCensus, flow, families = emptyInterfaceFamilyCensus, moduleRecords = emptyCommonJsModuleRecordCensus, declaredMembers = emptyDeclaredMemberCensus, isIntrinsicDescriptorCall = () => false, standIns = emptyRecordStandInArmCensus, linkFamilies = emptyRecordLinkFamilyCensus, sloppyAbsence = noSloppyAbsence, suppressedWrites = emptySuppressedWriteArmCensus, assertedArguments = emptyAssertedArgumentArmCensus) => {
104
105
  const storageTypeOf = recordStorageFamilies(checker, flow, parameters);
105
106
  // One disagreement list for the WHOLE mapper, for the same reason the caches
106
107
  // below are shared: two rules answering for one node is a fact about the rule
@@ -133,13 +134,13 @@ export const createStructuralMapper = (checker, identities, table, instantiation
133
134
  const cached = views.get(key);
134
135
  if (cached)
135
136
  return cached;
136
- const built = buildMapper(checker, identities.forSpecialization(path), table, instantiations, specializations, path, bindingPath, mapperFor, parameters, absent, collections, bags, flow, storageTypeOf, families, moduleRecords, declaredMembers, isIntrinsicDescriptorCall, standIns, linkFamilies, aliasRecurrence, instantiatedMembersFor(bindingPath), viewIndependentKeyOf, sharedCompleted, classCopyKeys, disagreements, sloppyAbsence, suppressedWrites);
137
+ const built = buildMapper(checker, identities.forSpecialization(path), table, instantiations, specializations, path, bindingPath, mapperFor, parameters, absent, collections, bags, flow, storageTypeOf, families, moduleRecords, declaredMembers, isIntrinsicDescriptorCall, standIns, linkFamilies, aliasRecurrence, instantiatedMembersFor(bindingPath), viewIndependentKeyOf, sharedCompleted, classCopyKeys, disagreements, sloppyAbsence, suppressedWrites, assertedArguments);
137
138
  views.set(key, built);
138
139
  return built;
139
140
  };
140
141
  return mapperFor(rootSpecialization);
141
142
  };
142
- const buildMapper = (checker, identities, table, instantiations, specializations, path, bindingPath, mapperFor, programParameters, absent, collections, bags, flow, storageTypeOf, families, moduleRecords, declaredMembers, isIntrinsicDescriptorCall, standIns, linkFamilies, aliasRecurrence, instantiatedMembers, viewIndependentKeyOf, sharedCompleted, classCopyKeys, disagreements, sloppyAbsence, suppressedWrites) => {
143
+ const buildMapper = (checker, identities, table, instantiations, specializations, path, bindingPath, mapperFor, programParameters, absent, collections, bags, flow, storageTypeOf, families, moduleRecords, declaredMembers, isIntrinsicDescriptorCall, standIns, linkFamilies, aliasRecurrence, instantiatedMembers, viewIndependentKeyOf, sharedCompleted, classCopyKeys, disagreements, sloppyAbsence, suppressedWrites, assertedArguments) => {
143
144
  const { boundByPath, bindingOf: censusBindingOf, substituteTypeParameter } = createTypeParameterSubstitution(identities, instantiations, specializations, bindingPath);
144
145
  // What a parameter holds is a fact about the COPY this view describes: a
145
146
  // generic body's copies are called with different carriers. Scoped once,
@@ -2246,6 +2247,12 @@ const buildMapper = (checker, identities, table, instantiations, specializations
2246
2247
  const standInArms = standInArmIdsOf(standIns.armsOf(type));
2247
2248
  if (standInArms)
2248
2249
  return remember(type, table.intern({ kind: 'union', members: [...present.map(typeOf), ...standInArms] }));
2250
+ // A record an argument hands this union through `as unknown as` is the
2251
+ // same object in the callee -- `asserted-argument-arms.ts` -- so it is
2252
+ // its own carrier's arm, never a stand-in copy of another shape.
2253
+ const assertedArms = assertedArguments.armsOf(type);
2254
+ if (assertedArms)
2255
+ return remember(type, table.intern({ kind: 'union', members: [...present.map(typeOf), ...assertedArms.map(typeOf)] }));
2249
2256
  // A union of pure INDEX-SIGNATURE objects is one table whose values are
2250
2257
  // the union. `Record<string, string> | Record<string, string[]>` (hono's
2251
2258
  // `_getQueryParam`, `utils/url.ts:255`) describes one object either way:
@@ -192,14 +192,18 @@ const storageSpelling = (type, name, realm = false) => realm
192
192
  * guessed type -- the body that reads it then refuses by name, which is the
193
193
  * answer, instead of this file inventing a layout to make the file compile.
194
194
  */
195
- const globalStorage = (placements, omit, realm = false) => [...placements.entries()]
195
+ const globalStorage = (placements, omit, realm = false, integerCells = new Set()) => [...placements.entries()]
196
196
  .filter(([declaration, placement]) => placement.storage.kind === 'region' && placement.representation !== null && !omit.has(declaration))
197
197
  .sort(([left], [right]) => left.localeCompare(right))
198
198
  .flatMap(([declaration, placement]) => {
199
199
  const representation = placement.representation;
200
200
  if (!representation || representation.kind === 'unresolved' || representation.kind === 'void')
201
201
  return [];
202
- return [storageSpelling(cppTypeOf(representation), cppGlobalName(declaration), realm)];
202
+ // A cell the program writes once with a bounded integer is held as one: a
203
+ // `double` here is read back through a double->integer conversion in every
204
+ // index built from it, which is a libcall on a core with no double FPU.
205
+ const type = integerCells.has(declaration) ? cppNarrowedIntegerType : cppTypeOf(representation);
206
+ return [storageSpelling(type, cppGlobalName(declaration), realm)];
203
207
  });
204
208
  const absentDefinitions = (placements, realm = false) => [...placements.entries()]
205
209
  .filter(([, placement]) => placement.storage.kind === 'absent' && placement.representation !== null)
@@ -1638,6 +1642,14 @@ const renderTranslationUnitSession = (input) => {
1638
1642
  }
1639
1643
  const narrowedStorage = integerStorageCensusOf({
1640
1644
  bodies: input.bodies,
1645
+ integerCellEligible: (cell) => {
1646
+ const placement = input.placements.get(cell);
1647
+ const representation = placement?.representation;
1648
+ return (placement?.storage.kind === 'region' &&
1649
+ !input.omitGlobals.has(cell) &&
1650
+ representation?.kind === 'scalar' &&
1651
+ representation.domain === 'number');
1652
+ },
1641
1653
  structNameOf: cppStructNameOf,
1642
1654
  structFamilyOf,
1643
1655
  fieldStructNameOf,
@@ -1754,7 +1766,7 @@ const renderTranslationUnitSession = (input) => {
1754
1766
  // name the host member instead (`buildHostMethodAliasIndex`) -- so declaring
1755
1767
  // it would leave a `CallableObject` of the method's own convention in the
1756
1768
  // unit, boxing an `any` formal that no code ever passes.
1757
- const globals = globalStorage(input.placements, new Set([...input.omitGlobals, ...hostMethodAliases.keys()]), input.realmStorage);
1769
+ const globals = globalStorage(input.placements, new Set([...input.omitGlobals, ...hostMethodAliases.keys()]), input.realmStorage, narrowedStorage.integerCells);
1758
1770
  // Environment structs ahead of every forward signature: a capturing body's
1759
1771
  // own formal names its struct as a pointer type, so the struct must already
1760
1772
  // be a complete type by the time that formal is spelled.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geastack/compiler",
3
- "version": "1.0.23",
3
+ "version": "1.0.24",
4
4
  "description": "The geastack TypeScript-to-C++ compiler: one semantic spine, no source-shaped authority, no boxing of statically typed values.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {