@geastack/compiler 1.0.25 → 1.0.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
File without changes
@@ -126,7 +126,7 @@ export interface IrBodyBuilder {
126
126
  readonly allocateOrdinaryObject: (block: IrBlockId, lineage: SemanticResultId, representation: Representation) => IrValueId;
127
127
  readonly allocateArrayObject: (block: IrBlockId, lineage: SemanticResultId, elements: readonly IrArrayElement[], representation: Representation) => IrValueId;
128
128
  readonly allocateCallable: (block: IrBlockId, lineage: SemanticResultId, functionId: FunctionId, captures: readonly IrOperand[], representation: Representation) => IrValueId;
129
- readonly bindCallable: (block: IrBlockId, lineage: SemanticResultId, source: IrOperand, sourceFunctionId: FunctionId | null, sourceAbi: CallableAbi, thisArgument: IrOperand | null, receiver: IrOperand | null, bound: readonly IrOperand[], representation: Representation, detached?: boolean | 'holder', unboxedMethod?: UnboxedMethodAssumption) => IrValueId;
129
+ readonly bindCallable: (block: IrBlockId, lineage: SemanticResultId, source: IrOperand, sourceFunctionId: FunctionId | null, sourceAbi: CallableAbi, thisArgument: IrOperand | null, receiver: IrOperand | null, bound: readonly IrOperand[], representation: Representation, detached?: boolean | 'holder', unboxedMethod?: UnboxedMethodAssumption, shadowGuarded?: true) => IrValueId;
130
130
  readonly allocateConstructor: (block: IrBlockId, lineage: SemanticResultId, declaration: DeclarationId, captures: readonly IrOperand[], representation: Representation, heritage?: IrOperand) => IrValueId;
131
131
  readonly allocateProxy: (block: IrBlockId, lineage: SemanticResultId, target: IrOperand, handler: IrOperand, representation: Representation) => IrValueId;
132
132
  readonly proxyPart: (block: IrBlockId, lineage: SemanticResultId, proxy: IrOperand, part: 'target' | 'handler', representation: Representation) => IrValueId;
package/dist/ir/build.js CHANGED
@@ -293,7 +293,7 @@ export const createIrBodyBuilder = (owner, sourceOwner, abi, constructAbi = null
293
293
  append(block, { kind: 'allocate-callable', lineage, functionId, captures, result });
294
294
  return result.id;
295
295
  };
296
- const bindCallable = (block, lineage, source, sourceFunctionId, sourceAbi, thisArgument, receiver, bound, representation, detached = false, unboxedMethod) => {
296
+ const bindCallable = (block, lineage, source, sourceFunctionId, sourceAbi, thisArgument, receiver, bound, representation, detached = false, unboxedMethod, shadowGuarded) => {
297
297
  const result = mintResult(representation);
298
298
  append(block, {
299
299
  kind: 'bind-callable',
@@ -306,6 +306,7 @@ export const createIrBodyBuilder = (owner, sourceOwner, abi, constructAbi = null
306
306
  bound,
307
307
  detached,
308
308
  ...(unboxedMethod === undefined ? {} : { unboxedMethod }),
309
+ ...(shadowGuarded === undefined ? {} : { builtinShadowGuard: 'bind' }),
309
310
  result
310
311
  });
311
312
  return result.id;
@@ -69,7 +69,7 @@ const lowerDeferredFunctionBind = (ctx, block, lineage, operation, deferred) =>
69
69
  if (!exactFrame) {
70
70
  throw new IrLoweringBlockedError('Function.prototype.bind result does not state the source callable suffix convention exactly');
71
71
  }
72
- registerResult(ctx, operation, ctx.builder.bindCallable(block, lineage, source, deferred.functionId, deferred.abi, thisArgument, receiver, values, result, false, deferred.unboxedMethod));
72
+ registerResult(ctx, operation, ctx.builder.bindCallable(block, lineage, source, deferred.functionId, deferred.abi, thisArgument, receiver, values, result, false, deferred.unboxedMethod, deferred.bindShadowGuard));
73
73
  };
74
74
  /**
75
75
  * Rewriting `add.call(x, 3, 4)` into `add`'s own call, with `x` as the
@@ -945,6 +945,8 @@ export interface BindCallableOperation extends IrOperationBase {
945
945
  */
946
946
  readonly unboxedMethod?: UnboxedMethodAssumption;
947
947
  readonly unboxedMethodConfirmed?: boolean;
948
+ /** The same run-time check for a bind no census can confirm (`DeferredCallee.bindShadowGuard`). */
949
+ readonly builtinShadowGuard?: 'bind';
948
950
  readonly result: IrResult;
949
951
  }
950
952
  export interface AllocateConstructorOperation extends IrOperationBase {
@@ -107,6 +107,13 @@ export interface DeferredCallee {
107
107
  * Function object the call reaches at run time.
108
108
  */
109
109
  readonly shadowGuard?: 'call' | 'apply';
110
+ /**
111
+ * Set on a `bind` lowered as the builtin under `'builtin-unless-boxed'`
112
+ * when no census can confirm the assumption -- the Function object has no
113
+ * known origin, or its method value escapes. The emitter checks that one
114
+ * object's own `bind` at run time, as `shadowGuard` does for `call`.
115
+ */
116
+ readonly bindShadowGuard?: true;
110
117
  /**
111
118
  * The RECEIVER's own carrier -- the boxed frame's argument carrier, and the
112
119
  * carrier the this-argument must keep its identity in. Carried here because
@@ -187,7 +187,8 @@ export const deferredCalleeOf = (input, operation) => {
187
187
  const shadowGuard = member === 'call' && resolution === 'builtin-unless-boxed' && representation.kind !== 'dynamic' ? member : null;
188
188
  if (process.env.GEA_CALLABLE_FACTS_DEBUG)
189
189
  console.error(`[deferred-callee] member=${member} functionId=${functionId} carrier=${representation.kind} resolution=${resolution}`);
190
- if (resolution !== 'builtin' && unboxedMethod === null && shadowGuard === null)
190
+ const bindShadowGuard = member === 'bind' && resolution === 'builtin-unless-boxed' && representation.kind !== 'dynamic' && unboxedMethod === null;
191
+ if (resolution !== 'builtin' && unboxedMethod === null && shadowGuard === null && !bindShadowGuard)
191
192
  return null;
192
193
  // Read off the receiver's own carrier, which is what decides how the call
193
194
  // renders -- see `DeferredCallee.frame`.
@@ -214,7 +215,16 @@ export const deferredCalleeOf = (input, operation) => {
214
215
  : null
215
216
  : bindAbiOfCallableReceiver(representation);
216
217
  return abi
217
- ? { member, receiver, abi, functionId, frame, receiverCarrier: representation, ...(unboxedMethod === null ? {} : { unboxedMethod }) }
218
+ ? {
219
+ member,
220
+ receiver,
221
+ abi,
222
+ functionId,
223
+ frame,
224
+ receiverCarrier: representation,
225
+ ...(unboxedMethod === null ? {} : { unboxedMethod }),
226
+ ...(bindShadowGuard ? { bindShadowGuard } : {})
227
+ }
218
228
  : null;
219
229
  }
220
230
  if (functionId === null && representation.kind !== 'function-value-dispatch')
@@ -18,10 +18,18 @@ export declare const classPrototypeMemberIsPresent: (classes: ReadonlyMap<Declar
18
18
  * this answers `false`, the sidecar is not merely one source of the answer: it
19
19
  * is the WHOLE answer, and `in` over that receiver is exactly its verdict.
20
20
  *
21
- * When it answers `true`, the layout owns a symbol-keyed slot with its own
22
- * presence bit that the sidecar knows nothing about, and which of the two holds
23
- * the key is undecidable without knowing WHICH symbol -- so the site refuses by
24
- * name instead, rather than consulting one half and calling it the answer.
21
+ * When it answers `true`, the layout owns a symbol-keyed member the sidecar
22
+ * knows nothing about, and which of the two holds the key is undecidable
23
+ * without knowing WHICH symbol -- so the site refuses by name instead, rather
24
+ * than consulting one half and calling it the answer.
25
+ *
26
+ * A CLASS's symbol-keyed FIELD is not such a member. `gea::nativeDynamicHas`
27
+ * asks the receiver's virtual `gea_ownFieldPresent` before the sidecar, and a
28
+ * generated class answers that from the field's own presence bit for every
29
+ * key it declares, symbols included (`symbol-keyed-this-slots.ts` lays out
30
+ * hono's `cacheKey` cache that way) -- so the one call still sees both halves.
31
+ * What it cannot see is a symbol-keyed method or accessor, which lives on the
32
+ * prototype; those, and a plain record's symbol field, still refuse.
25
33
  */
26
34
  export declare const symbolKeyedMemberIsDeclared: (classes: ReadonlyMap<DeclarationId, ClassLayout>, fields: readonly {
27
35
  readonly key: string;
@@ -31,14 +31,22 @@ export const classPrototypeMemberIsPresent = (classes, declaration, key) => {
31
31
  * this answers `false`, the sidecar is not merely one source of the answer: it
32
32
  * is the WHOLE answer, and `in` over that receiver is exactly its verdict.
33
33
  *
34
- * When it answers `true`, the layout owns a symbol-keyed slot with its own
35
- * presence bit that the sidecar knows nothing about, and which of the two holds
36
- * the key is undecidable without knowing WHICH symbol -- so the site refuses by
37
- * name instead, rather than consulting one half and calling it the answer.
34
+ * When it answers `true`, the layout owns a symbol-keyed member the sidecar
35
+ * knows nothing about, and which of the two holds the key is undecidable
36
+ * without knowing WHICH symbol -- so the site refuses by name instead, rather
37
+ * than consulting one half and calling it the answer.
38
+ *
39
+ * A CLASS's symbol-keyed FIELD is not such a member. `gea::nativeDynamicHas`
40
+ * asks the receiver's virtual `gea_ownFieldPresent` before the sidecar, and a
41
+ * generated class answers that from the field's own presence bit for every
42
+ * key it declares, symbols included (`symbol-keyed-this-slots.ts` lays out
43
+ * hono's `cacheKey` cache that way) -- so the one call still sees both halves.
44
+ * What it cannot see is a symbol-keyed method or accessor, which lives on the
45
+ * prototype; those, and a plain record's symbol field, still refuse.
38
46
  */
39
47
  export const symbolKeyedMemberIsDeclared = (classes, fields, declaration) => {
40
48
  const isSymbolKey = (entry) => symbolPropertyKeyDeclarationOf(entry.key) !== null;
41
- if (fields !== null && fields.some(isSymbolKey))
49
+ if (declaration === null && fields !== null && fields.some(isSymbolKey))
42
50
  return true;
43
51
  const seen = new Set();
44
52
  let current = declaration;
@@ -47,10 +55,7 @@ export const symbolKeyedMemberIsDeclared = (classes, fields, declaration) => {
47
55
  const layout = classes.get(current);
48
56
  if (!layout)
49
57
  return true;
50
- if (layout.fields.some(isSymbolKey) ||
51
- layout.methods.some(isSymbolKey) ||
52
- layout.accessors.some(isSymbolKey) ||
53
- (layout.methodOverrides ?? []).some(isSymbolKey))
58
+ if (layout.methods.some(isSymbolKey) || layout.accessors.some(isSymbolKey) || (layout.methodOverrides ?? []).some(isSymbolKey))
54
59
  return true;
55
60
  current = layout.base;
56
61
  }
@@ -389,10 +389,13 @@ export const callableBuiltinResolution = (facts, functionId, member) => {
389
389
  */
390
390
  export const callableBindResolution = (facts, functionId) => {
391
391
  const resolution = callableBuiltinResolution(facts, functionId, 'bind');
392
- if (resolution !== 'ordinary-property' || functionId === null)
392
+ if (resolution !== 'ordinary-property')
393
393
  return resolution;
394
- const own = facts.ownProperties.get(functionId);
395
- if (own?.has('bind') || own?.has(unknownCallableOwnProperty))
394
+ // An unknown origin (a read through an interface union: hono's
395
+ // `router.match.bind(router)`) could be any function, so a statically named
396
+ // own `bind` anywhere stays decisive for it.
397
+ const owns = functionId === null ? [...facts.ownProperties.values()] : [facts.ownProperties.get(functionId)];
398
+ if (owns.some((own) => own?.has('bind') || own?.has(unknownCallableOwnProperty)))
396
399
  return resolution;
397
400
  const boxedOnly = (name) => !facts.anonymousProperties.has(name) || facts.boxedOnlyProperties.has(name);
398
401
  return boxedOnly('bind') && boxedOnly(unknownCallableOwnProperty) ? 'builtin-unless-boxed' : resolution;
@@ -286,7 +286,11 @@ const modulesReachableFrom = (start) => {
286
286
  return seen;
287
287
  };
288
288
  /** The declaration file mirroring this source file, or `null`. */
289
- const declarationPathFor = (fileName) => {
289
+ const declarationPathFor = (spelledFileName) => {
290
+ // A Windows program spells files with backslashes (`...\node_modules\three\...`)
291
+ // wherever the module graph stated them; matched as-is, no JS file there ever
292
+ // found its `@types` mirror and three's sources compiled untyped.
293
+ const fileName = spelledFileName.replaceAll('\\', '/');
290
294
  const marker = '/node_modules/';
291
295
  const at = fileName.lastIndexOf(marker);
292
296
  if (at < 0)
@@ -16,6 +16,7 @@ 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
18
  import { censusAssertedArgumentArms } from './normalize/asserted-argument-arms.js';
19
+ import { censusSymbolKeyedThisSlots } from './normalize/symbol-keyed-this-slots.js';
19
20
  import { censusSuppressedWriteArms } from './normalize/suppressed-write-arms.js';
20
21
  import { withOverrideFieldArms } from './normalize/override-field-arms.js';
21
22
  import { censusDeclaredMembers } from './normalize/structural-declarations.js';
@@ -729,7 +730,10 @@ export const runFrontend = (input) => {
729
730
  withOverrideFieldArms(compiled.checker, compiled.sourceFiles, censusSuppressedWriteArms(compiled.checker, compiled.sourceFiles, reachable, valueFlow)),
730
731
  // A record an argument asserts through `unknown` into a union keeps its
731
732
  // own arm of that union -- see `asserted-argument-arms.ts`.
732
- censusAssertedArgumentArms(compiled.checker, compiled.sourceFiles, reachable));
733
+ censusAssertedArgumentArms(compiled.checker, compiled.sourceFiles, reachable),
734
+ // A module-private symbol a class writes on `this` without declaring it is
735
+ // a native optional field -- see `symbol-keyed-this-slots.ts`.
736
+ censusSymbolKeyedThisSlots(compiled.checker, compiled.sourceFiles, reachable));
733
737
  // The frontend's evidence-policy tables: built from the same
734
738
  // `identities`/`valueFlow`/`reachable` the fixpoint above already settled,
735
739
  // right after `types` exists so the agreement instrument can ask the
@@ -5,6 +5,7 @@ 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
7
  import { type AssertedArgumentArmCensus } from './asserted-argument-arms.js';
8
+ import { type SymbolKeyedThisSlotCensus } from './symbol-keyed-this-slots.js';
8
9
  import { type RecordLinkFamilyCensus } from './record-link-families.js';
9
10
  import { type DeclaredMemberCensus } from './structural-declarations.js';
10
11
  import type { DeclarationId, StructuralTypeId } from '../../identity/ids.js';
@@ -204,7 +205,7 @@ export interface StructuralMapper {
204
205
  */
205
206
  readonly classCopies: () => ReadonlyMap<DeclarationId, readonly ClassCopyKey[]>;
206
207
  }
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;
208
+ 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, symbolSlots?: SymbolKeyedThisSlotCensus) => StructuralMapper;
208
209
  /**
209
210
  * `JSON.stringify(value)` from the default lib over a value that may have no
210
211
  * JSON form, so the call may return `undefined` although the lib declares
@@ -7,6 +7,7 @@ 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
9
  import { emptyAssertedArgumentArmCensus } from './asserted-argument-arms.js';
10
+ import { emptySymbolKeyedThisSlotCensus } from './symbol-keyed-this-slots.js';
10
11
  import { emptyRecordLinkFamilyCensus } from './record-link-families.js';
11
12
  import { bivariantSlotArrayAliasTypeOf, bivariantSlotBindingTypeOf, bivariantSlotElementTypeOf, bivariantSlotParameterTypeOf, bivariantSlotReadTypeOf } from './bivariant-slot-parameter.js';
12
13
  import { emptyDeclaredMemberCensus } from './structural-declarations.js';
@@ -101,7 +102,7 @@ const nativeErrorNames = new Set([
101
102
  'TypeError',
102
103
  'URIError'
103
104
  ]);
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) => {
105
+ 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, symbolSlots = emptySymbolKeyedThisSlotCensus) => {
105
106
  const storageTypeOf = recordStorageFamilies(checker, flow, parameters);
106
107
  // One disagreement list for the WHOLE mapper, for the same reason the caches
107
108
  // below are shared: two rules answering for one node is a fact about the rule
@@ -134,13 +135,13 @@ export const createStructuralMapper = (checker, identities, table, instantiation
134
135
  const cached = views.get(key);
135
136
  if (cached)
136
137
  return cached;
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);
138
+ 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, symbolSlots);
138
139
  views.set(key, built);
139
140
  return built;
140
141
  };
141
142
  return mapperFor(rootSpecialization);
142
143
  };
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) => {
144
+ 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, symbolSlots) => {
144
145
  const { boundByPath, bindingOf: censusBindingOf, substituteTypeParameter } = createTypeParameterSubstitution(identities, instantiations, specializations, bindingPath);
145
146
  // What a parameter holds is a fact about the COPY this view describes: a
146
147
  // generic body's copies are called with different carriers. Scoped once,
@@ -754,11 +755,11 @@ const buildMapper = (checker, identities, table, instantiations, specializations
754
755
  // constructor-function/class-alias question to ask in the first place
755
756
  // (see `buildMapper`'s `flow?: ValueFlowIndex`); `ts.isClassLike` matches
756
757
  // this function's one call site, gated the same way at `declaredAnchorOf`.
758
+ const extra = [];
757
759
  if (flow && ts.isClassLike(location) && shape.kind === 'object') {
758
760
  const installed = constructorInstalledMemberDeclarationsOf(flow, location);
759
761
  if (installed.size > 0) {
760
762
  const existing = new Set(shape.members.flatMap((member) => (member.key.kind === 'string' ? [member.key.value] : [])));
761
- const extra = [];
762
763
  for (const [key, declarations] of installed) {
763
764
  if (existing.has(key))
764
765
  continue;
@@ -771,10 +772,33 @@ const buildMapper = (checker, identities, table, instantiations, specializations
771
772
  accessor: null
772
773
  });
773
774
  }
774
- if (extra.length > 0)
775
- return table.intern({ ...shape, members: [...shape.members, ...extra] });
776
775
  }
777
776
  }
777
+ // A module-private symbol key the class writes on `this` without declaring
778
+ // it -- see `symbol-keyed-this-slots.ts`. Optional with no initializer, so
779
+ // the slot is absent until the first write, as the expando it replaces was.
780
+ // A subclass's shape lists inherited members too, so it carries every
781
+ // base class's slots.
782
+ const slotOwners = [];
783
+ for (let owner = ts.isClassLike(location) ? location : null; owner && !slotOwners.includes(owner);) {
784
+ slotOwners.push(owner);
785
+ const heritage = owner.heritageClauses?.find((clause) => clause.token === ts.SyntaxKind.ExtendsKeyword)?.types[0];
786
+ const base = heritage ? checker.getTypeAtLocation(heritage).getSymbol()?.valueDeclaration : undefined;
787
+ owner = base && ts.isClassLike(base) ? base : null;
788
+ }
789
+ if (shape.kind === 'object') {
790
+ for (const property of slotOwners.flatMap((owner) => symbolSlots.slotsOf(owner))) {
791
+ const member = memberOf(property, location);
792
+ if (!member || member.key.kind !== 'symbol')
793
+ continue;
794
+ const declaration = member.key.declaration;
795
+ if (shape.members.some((existing) => existing.key.kind === 'symbol' && existing.key.declaration === declaration))
796
+ continue;
797
+ extra.push({ ...member, optional: true, readonly: false, accessor: null });
798
+ }
799
+ }
800
+ if (extra.length > 0 && shape.kind === 'object')
801
+ return table.intern({ ...shape, members: [...shape.members, ...extra] });
778
802
  return table.intern(shape);
779
803
  };
780
804
  const { declaredBodyOf } = createDeclaredBodyResolver({ table, typeOf, signatureOf, objectShapeOf, arrayHeritageShapeOf });
@@ -0,0 +1,46 @@
1
+ import ts from 'typescript';
2
+ import { type ProgramReachability } from './reachability.js';
3
+ /**
4
+ * A module-private `Symbol()` key a class writes onto its own instances
5
+ * without declaring it, laid out as an optional native field of that class.
6
+ *
7
+ * `@hono/node-server`'s `LightweightResponse` (response.ts) is the case. Its
8
+ * per-response cache lives under `cacheKey`, which the class never declares:
9
+ *
10
+ * ;(this as any)[cacheKey] = [init?.status || 200, body ?? null, headers || init?.headers]
11
+ * const cache = (this as LightResponse)[cacheKey]
12
+ * delete (this as LightResponse)[cacheKey]
13
+ * return ((this as LightResponse)[responseCache] ||= new GlobalResponse(...))
14
+ *
15
+ * and the listener asks `cacheKey in res` / `(res as any)[cacheKey]` once per
16
+ * request. Without a field, every one of those went to the object's expando
17
+ * sidecar: a heap `DynamicObject`, a weak owner and a registry slot minted per
18
+ * response, then a hash probe per access.
19
+ *
20
+ * The field is OPTIONAL and has no initializer, so its presence bit starts
21
+ * false: `in` answers false until the first write and again after `delete`,
22
+ * exactly as the expando did. The native field protocol is virtual, so a
23
+ * receiver typed as a base class (`cacheKey in res`) reaches it too.
24
+ *
25
+ * Its type is the one the program itself states for the key -- the property
26
+ * an `as T` cast on `this` declares (`LightResponse[cacheKey]`). A key no such
27
+ * interface types stays an expando: inventing a type from the writes would be
28
+ * a guess.
29
+ *
30
+ * Sound only where every way the key can reach an object is visible, so the
31
+ * census withdraws a key when:
32
+ * - the symbol escapes: any reference to its declaration that is not an
33
+ * element-access key, an `in` operand, a type-position computed name, or an
34
+ * import/export specifier (`const k = cacheKey; o[k] = v` writes through a
35
+ * name this walk cannot follow);
36
+ * - a write anywhere in the program stores a value whose type is disjoint
37
+ * from the declared one (`fits` says why comparable is the bar);
38
+ * - an access is a destructuring or compound target other than `||=`, `&&=`
39
+ * and `??=`.
40
+ */
41
+ export interface SymbolKeyedThisSlotCensus {
42
+ /** The interface properties typing the symbol keys `owner` writes on `this`, in first-write order. */
43
+ readonly slotsOf: (owner: ts.ClassLikeDeclaration) => readonly ts.Symbol[];
44
+ }
45
+ export declare const emptySymbolKeyedThisSlotCensus: SymbolKeyedThisSlotCensus;
46
+ export declare const censusSymbolKeyedThisSlots: (checker: ts.TypeChecker, files: readonly ts.SourceFile[], reachable: ProgramReachability) => SymbolKeyedThisSlotCensus;
@@ -0,0 +1,270 @@
1
+ import ts from 'typescript';
2
+ import { forEachReachableStatement } from './reachability.js';
3
+ export const emptySymbolKeyedThisSlotCensus = { slotsOf: () => [] };
4
+ const unwrapCasts = (node) => {
5
+ let current = node;
6
+ while (ts.isParenthesizedExpression(current) ||
7
+ ts.isAsExpression(current) ||
8
+ ts.isTypeAssertionExpression(current) ||
9
+ ts.isSatisfiesExpression(current) ||
10
+ ts.isNonNullExpression(current))
11
+ current = current.expression;
12
+ return current;
13
+ };
14
+ /** The types an expression is asserted to on the way out of `node`, outermost last. */
15
+ const assertedTypesOf = (node) => {
16
+ const asserted = [];
17
+ let current = node;
18
+ for (;;) {
19
+ if (ts.isAsExpression(current) || ts.isTypeAssertionExpression(current) || ts.isSatisfiesExpression(current))
20
+ asserted.push(current.type);
21
+ else if (!ts.isParenthesizedExpression(current) && !ts.isNonNullExpression(current))
22
+ return asserted;
23
+ current = current.expression;
24
+ }
25
+ };
26
+ const writeOperators = new Set([
27
+ ts.SyntaxKind.EqualsToken,
28
+ ts.SyntaxKind.BarBarEqualsToken,
29
+ ts.SyntaxKind.AmpersandAmpersandEqualsToken,
30
+ ts.SyntaxKind.QuestionQuestionEqualsToken
31
+ ]);
32
+ /** The parent of `node` past parentheses, with the child it was reached through. */
33
+ const outerOf = (node) => {
34
+ let child = node;
35
+ while (child.parent && ts.isParenthesizedExpression(child.parent))
36
+ child = child.parent;
37
+ return { child, parent: child.parent };
38
+ };
39
+ /** A `const k = Symbol(...)` declaration: one fresh symbol per evaluation of a module-level binding. */
40
+ const isFreshSymbolDeclaration = (declaration) => {
41
+ if (!ts.isVariableDeclaration(declaration) || !ts.isIdentifier(declaration.name) || !declaration.initializer)
42
+ return false;
43
+ const list = declaration.parent;
44
+ if (!ts.isVariableDeclarationList(list) || (list.flags & ts.NodeFlags.Const) === 0)
45
+ return false;
46
+ if (!ts.isVariableStatement(list.parent) || !ts.isSourceFile(list.parent.parent))
47
+ return false;
48
+ const initializer = declaration.initializer;
49
+ return ts.isCallExpression(initializer) && ts.isIdentifier(initializer.expression) && initializer.expression.text === 'Symbol';
50
+ };
51
+ export const censusSymbolKeyedThisSlots = (checker, files, reachable) => {
52
+ const resolvedDeclaration = (identifier) => {
53
+ let symbol = checker.getSymbolAtLocation(identifier);
54
+ if (symbol && symbol.flags & ts.SymbolFlags.Alias)
55
+ symbol = checker.getAliasedSymbol(symbol);
56
+ return symbol?.valueDeclaration ?? null;
57
+ };
58
+ // Every spelling a fresh symbol can be referenced by: its own name, plus any
59
+ // local name an import or export renames it to, to a fixpoint. Only those
60
+ // identifiers are resolved -- asking the checker for every identifier in a
61
+ // three.js-sized program is the cost this filter exists to avoid -- and a
62
+ // missed rename would be a missed escape, so the closure is taken in full.
63
+ const spellings = new Set();
64
+ const sources = files.filter((file) => !file.isDeclarationFile);
65
+ for (const file of sources)
66
+ for (const statement of file.statements)
67
+ if (ts.isVariableStatement(statement))
68
+ for (const declaration of statement.declarationList.declarations)
69
+ if (isFreshSymbolDeclaration(declaration))
70
+ spellings.add(declaration.name.text);
71
+ if (spellings.size === 0)
72
+ return emptySymbolKeyedThisSlotCensus;
73
+ for (let grew = true; grew;) {
74
+ grew = false;
75
+ for (const file of sources)
76
+ for (const statement of file.statements) {
77
+ const bindings = ts.isImportDeclaration(statement) &&
78
+ statement.importClause?.namedBindings &&
79
+ ts.isNamedImports(statement.importClause.namedBindings)
80
+ ? statement.importClause.namedBindings.elements
81
+ : ts.isExportDeclaration(statement) && statement.exportClause && ts.isNamedExports(statement.exportClause)
82
+ ? statement.exportClause.elements
83
+ : [];
84
+ for (const binding of bindings) {
85
+ const imported = (binding.propertyName ?? binding.name).text;
86
+ if (spellings.has(imported) && !spellings.has(binding.name.text)) {
87
+ spellings.add(binding.name.text);
88
+ grew = true;
89
+ }
90
+ }
91
+ }
92
+ }
93
+ const accesses = [];
94
+ const escaped = new Set();
95
+ for (const file of sources) {
96
+ const visit = (node) => {
97
+ if (reachable.memberIsPruned(node))
98
+ return;
99
+ if (ts.isIdentifier(node) && spellings.has(node.text)) {
100
+ const declaration = resolvedDeclaration(node);
101
+ if (declaration && isFreshSymbolDeclaration(declaration) && declaration.name !== node) {
102
+ const { child, parent } = outerOf(node);
103
+ if (parent && ts.isElementAccessExpression(parent) && parent.argumentExpression === child) {
104
+ accesses.push({ node: parent, key: declaration });
105
+ }
106
+ else if (!(parent && ts.isBinaryExpression(parent) && parent.operatorToken.kind === ts.SyntaxKind.InKeyword && parent.left === child) &&
107
+ !(parent && ts.isComputedPropertyName(parent) && isTypePositionMember(parent.parent)) &&
108
+ !(parent && (ts.isImportSpecifier(parent) || ts.isExportSpecifier(parent))) &&
109
+ !(parent && ts.isTypeQueryNode(parent))) {
110
+ escaped.add(declaration);
111
+ }
112
+ }
113
+ }
114
+ ts.forEachChild(node, visit);
115
+ };
116
+ forEachReachableStatement(reachable, file, visit);
117
+ }
118
+ /** The class whose instance `this` is at `access`, when it is an instance member's own `this`. */
119
+ const thisOwnerOf = (access) => {
120
+ if (unwrapCasts(access.expression).kind !== ts.SyntaxKind.ThisKeyword)
121
+ return null;
122
+ let container = access.parent;
123
+ while (!ts.isClassStaticBlockDeclaration(container) &&
124
+ (!ts.isFunctionLike(container) || ts.isArrowFunction(container)) &&
125
+ !ts.isPropertyDeclaration(container)) {
126
+ if (ts.isSourceFile(container))
127
+ return null;
128
+ container = container.parent;
129
+ }
130
+ const owner = container.parent;
131
+ if (!owner || !ts.isClassLike(owner))
132
+ return null;
133
+ if (!ts.isConstructorDeclaration(container) &&
134
+ !ts.isMethodDeclaration(container) &&
135
+ !ts.isAccessor(container) &&
136
+ !ts.isPropertyDeclaration(container))
137
+ return null;
138
+ if (!ts.isConstructorDeclaration(container) && ts.getCombinedModifierFlags(container) & ts.ModifierFlags.Static)
139
+ return null;
140
+ return owner;
141
+ };
142
+ /** The property an `as T` cast on the receiver declares for `key`, or `null`. */
143
+ const declaredPropertyOf = (access, key) => {
144
+ for (const asserted of assertedTypesOf(access.expression)) {
145
+ const type = checker.getTypeFromTypeNode(asserted);
146
+ if (type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown))
147
+ continue;
148
+ for (const property of checker.getPropertiesOfType(type)) {
149
+ for (const declaration of property.getDeclarations() ?? []) {
150
+ const name = declaration.name;
151
+ if (name && ts.isComputedPropertyName(name) && ts.isIdentifier(name.expression) && resolvedDeclaration(name.expression) === key)
152
+ return property;
153
+ }
154
+ }
155
+ }
156
+ return null;
157
+ };
158
+ /**
159
+ * Whether `value` can hold a value of `target`: assignable either way, read
160
+ * element by element for an array literal against a tuple.
161
+ *
162
+ * Comparable rather than assignable, because the program this exists for
163
+ * writes wider than it declares: hono stores a `Blob`/`Uint8Array` body into
164
+ * the `string | ReadableStream | null` element its `InternalCache` states.
165
+ * Every read of the key is a conversion to that declared type
166
+ * (`(res as any)[cacheKey] as InternalCache`), so such a value already
167
+ * refused at its first read through the expando; the native write refuses
168
+ * it at the store instead. A value of a type DISJOINT from the slot's could
169
+ * never be read back at all, so it withdraws the key.
170
+ */
171
+ const fits = (value, target) => {
172
+ const unwrapped = ts.isParenthesizedExpression(value) ? value.expression : value;
173
+ const written = checker.getTypeAtLocation(unwrapped);
174
+ if (ts.isArrayLiteralExpression(unwrapped) && !unwrapped.elements.some(ts.isSpreadElement)) {
175
+ const arms = target.isUnion() ? target.types : [target];
176
+ return arms.some((arm) => {
177
+ if (!checker.isTupleType(arm))
178
+ return false;
179
+ const elements = checker.getTypeArguments(arm);
180
+ const fixedLength = arm.target.fixedLength;
181
+ if (unwrapped.elements.length !== elements.length || fixedLength !== elements.length)
182
+ return false;
183
+ return unwrapped.elements.every((element, index) => fits(element, elements[index]));
184
+ });
185
+ }
186
+ return checker.isTypeAssignableTo(written, target) || checker.isTypeAssignableTo(target, written);
187
+ };
188
+ const declaredByKey = new Map();
189
+ const conflicting = new Set();
190
+ for (const { node, key } of accesses) {
191
+ const property = declaredPropertyOf(node, key);
192
+ if (!property)
193
+ continue;
194
+ const held = declaredByKey.get(key);
195
+ if (!held)
196
+ declaredByKey.set(key, property);
197
+ else if (held !== property && checker.getTypeOfSymbol(held) !== checker.getTypeOfSymbol(property))
198
+ conflicting.add(key);
199
+ }
200
+ const withdrawn = new Set([...escaped, ...conflicting]);
201
+ for (const { node, key } of accesses) {
202
+ const property = declaredByKey.get(key);
203
+ if (!property)
204
+ continue;
205
+ const { child, parent } = outerOf(node);
206
+ if (parent && ts.isBinaryExpression(parent) && parent.left === child) {
207
+ if (!writeOperators.has(parent.operatorToken.kind)) {
208
+ if (parent.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && parent.operatorToken.kind <= ts.SyntaxKind.LastAssignment)
209
+ withdrawn.add(key);
210
+ continue;
211
+ }
212
+ if (!fits(parent.right, checker.getNonNullableType(checker.getTypeOfSymbol(property))))
213
+ withdrawn.add(key);
214
+ continue;
215
+ }
216
+ if (parent &&
217
+ (ts.isPrefixUnaryExpression(parent) || ts.isPostfixUnaryExpression(parent)) &&
218
+ (parent.operator === ts.SyntaxKind.PlusPlusToken || parent.operator === ts.SyntaxKind.MinusMinusToken))
219
+ withdrawn.add(key);
220
+ // A destructuring target (`[o[k]] = xs`) writes without an `=` this walk reads.
221
+ else if (parent && isAssignmentTargetLiteral(child))
222
+ withdrawn.add(key);
223
+ }
224
+ const slots = new Map();
225
+ for (const { node, key } of accesses) {
226
+ if (withdrawn.has(key))
227
+ continue;
228
+ const property = declaredByKey.get(key);
229
+ if (!property)
230
+ continue;
231
+ const { child, parent } = outerOf(node);
232
+ if (!parent || !ts.isBinaryExpression(parent) || parent.left !== child || !writeOperators.has(parent.operatorToken.kind))
233
+ continue;
234
+ const owner = thisOwnerOf(node);
235
+ if (!owner)
236
+ continue;
237
+ const held = slots.get(owner);
238
+ if (!held)
239
+ slots.set(owner, [property]);
240
+ else if (!held.includes(property))
241
+ held.push(property);
242
+ }
243
+ if (process.env['GEA_BINDING_DEBUG']) {
244
+ for (const [owner, properties] of slots)
245
+ console.error(`[SYMBOL-THIS-SLOT] ${owner.name?.text ?? '<anonymous>'} ${properties.map((property) => property.getName()).join(' ')}`);
246
+ for (const key of withdrawn)
247
+ console.error(`[SYMBOL-THIS-SLOT] withdrawn ${key.name.text}`);
248
+ }
249
+ if (slots.size === 0)
250
+ return emptySymbolKeyedThisSlotCensus;
251
+ return { slotsOf: (owner) => slots.get(owner) ?? [] };
252
+ };
253
+ /** A member whose computed name is a type-level declaration (an interface or type literal member, a `declare`d field). */
254
+ const isTypePositionMember = (member) => ts.isPropertySignature(member) ||
255
+ ts.isMethodSignature(member) ||
256
+ (ts.isPropertyDeclaration(member) && (ts.getCombinedModifierFlags(member) & ts.ModifierFlags.Ambient) !== 0);
257
+ /** Whether an array/object literal is itself the left side of a destructuring assignment. */
258
+ const isAssignmentTargetLiteral = (node) => {
259
+ let current = node;
260
+ while (current.parent &&
261
+ (ts.isArrayLiteralExpression(current.parent) ||
262
+ ts.isObjectLiteralExpression(current.parent) ||
263
+ ts.isPropertyAssignment(current.parent) ||
264
+ ts.isShorthandPropertyAssignment(current.parent) ||
265
+ ts.isSpreadElement(current.parent) ||
266
+ ts.isParenthesizedExpression(current.parent)))
267
+ current = current.parent;
268
+ const parent = current.parent;
269
+ return !!parent && ts.isBinaryExpression(parent) && parent.left === current && parent.operatorToken.kind === ts.SyntaxKind.EqualsToken;
270
+ };