@geastack/compiler 1.0.29 → 1.0.31

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 (48) hide show
  1. package/dist/conversion/dictionary-view.js +18 -0
  2. package/dist/conversion/dynamic-wrapper.d.ts +5 -0
  3. package/dist/conversion/dynamic-wrapper.js +4 -1
  4. package/dist/conversion/structural-plan.js +8 -1
  5. package/dist/ir/absent-class-arm.d.ts +4 -0
  6. package/dist/ir/absent-class-arm.js +50 -2
  7. package/dist/ir/call-entry.js +9 -0
  8. package/dist/ir/callable-class-flow.js +1 -1
  9. package/dist/ir/certify.js +12 -1
  10. package/dist/ir/class-allocation-domain.js +64 -17
  11. package/dist/ir/key-order-observation.js +3 -0
  12. package/dist/ir/native-array-transport.js +37 -3
  13. package/dist/ir/native-field-view-domains.d.ts +7 -0
  14. package/dist/ir/native-field-view-domains.js +29 -4
  15. package/dist/ir/native-field-view-facts.js +17 -4
  16. package/dist/ir/native-key-query.js +5 -2
  17. package/dist/ir/operation-conversions.js +6 -0
  18. package/dist/ir/program-conversions.js +8 -0
  19. package/dist/ir/reflection-demand.js +249 -36
  20. package/dist/ir/shake.js +15 -1
  21. package/dist/representation/host-templates.d.ts +1 -1
  22. package/dist/representation/host-templates.js +5 -3
  23. package/dist/semantics/normalize/any-cast-member-call.d.ts +36 -0
  24. package/dist/semantics/normalize/any-cast-member-call.js +55 -0
  25. package/dist/semantics/normalize/derived-expression-type.js +40 -0
  26. package/dist/semantics/normalize/flow/callable-reach.js +56 -23
  27. package/dist/semantics/normalize/fresh-dictionary-storage.d.ts +2 -0
  28. package/dist/semantics/normalize/fresh-dictionary-storage.js +115 -8
  29. package/dist/semantics/normalize/local-bindings.js +8 -1
  30. package/dist/semantics/normalize/producers/boundary.js +3 -22
  31. package/dist/semantics/normalize/producers/cited-value-type.d.ts +19 -0
  32. package/dist/semantics/normalize/producers/cited-value-type.js +38 -0
  33. package/dist/semantics/normalize/producers/computations.js +32 -11
  34. package/dist/semantics/normalize/producers/invocations.js +10 -0
  35. package/dist/semantics/normalize/return-bindings.js +47 -1
  36. package/dist/semantics/normalize/structural-any-binding-consumer.d.ts +34 -0
  37. package/dist/semantics/normalize/structural-any-binding-consumer.js +208 -0
  38. package/dist/semantics/normalize/structural-declarations.js +10 -1
  39. package/dist/semantics/normalize/structural.d.ts +2 -0
  40. package/dist/semantics/normalize/structural.js +42 -2
  41. package/dist/targets/cpp/conversions.js +21 -1
  42. package/dist/targets/cpp/emit-narrowing.js +22 -1
  43. package/dist/targets/cpp/emit-native-field-view.d.ts +1 -1
  44. package/dist/targets/cpp/emit-native-field-view.js +25 -7
  45. package/dist/targets/cpp/emit-union-properties.js +10 -3
  46. package/dist/targets/cpp/host/emit-host-object.js +1 -1
  47. package/package.json +1 -1
  48. package/src/targets/cpp/runtime/gea_runtime.h +50 -6
@@ -35,6 +35,7 @@ import { nativeHostConstructionOf } from './native-host-construction.js';
35
35
  import { closePhysicalClassReflection } from './physical-class-reflection.js';
36
36
  import { absentClassArmRead, classFamilyLacksKey } from './absent-class-arm.js';
37
37
  import { nativeAbsentPropertyReadOf } from './native-absent-property.js';
38
+ import { isPrivateNameKey } from '../semantics/model/structural-types.js';
38
39
  /** A constructor carrier's own construct convention, seen through presence and borrowing; see its use in `closedConstructOperations`. */
39
40
  const constructorCarrierOf = (representation) => {
40
41
  if (representation.kind === 'optional')
@@ -254,6 +255,26 @@ const publishedChildrenOf = (representation, classes, deriver) => {
254
255
  return [representation.call.result, representation.construct.result];
255
256
  case 'native-handle':
256
257
  return [representation.call, representation.construct].flatMap((abi) => (abi ? [abi.result] : []));
258
+ case 'class-ref': {
259
+ // A `#private` element is reachable only from the class's own body,
260
+ // never by dynamic code holding the instance: the reflected protocol
261
+ // leaves it out (`records.ts`), so publishing the instance publishes
262
+ // none of what it holds there. Hono's Context keeps the router's
263
+ // `#matchResult` that way; walking it made every handler tuple in the
264
+ // router fully reflected.
265
+ const layout = classes.get(representation.declaration);
266
+ if (layout?.nativeStorage === undefined)
267
+ return directChildrenOf(representation, classes, deriver);
268
+ const raw = deriver?.layoutOf(representation.shapeId);
269
+ const visible = (members) => members.filter((member) => !isPrivateNameKey(member.key));
270
+ return [
271
+ ...visible(layout.methods).flatMap((method) => (method.representation ? [method.representation] : [])),
272
+ ...visible(layout.nativeStorage.fields).map((field) => field.value),
273
+ ...layout.staticFields.flatMap((field) => (field.representation ? [field.representation] : [])),
274
+ ...(raw?.kind === 'record' ? visible(raw.accessors).map((accessor) => accessor.value) : []),
275
+ ...(raw?.kind === 'record-with-index' ? raw.indexes.map((index) => index.value) : [])
276
+ ];
277
+ }
257
278
  default:
258
279
  return directChildrenOf(representation, classes, deriver);
259
280
  }
@@ -425,6 +446,64 @@ const callMatchesAbi = (operation, abi) => {
425
446
  operation.arguments.length === abi.parameters.length &&
426
447
  operation.arguments.every((argument, index) => representationKey(argument.representation) === representationKey(abi.parameters[index].value)));
427
448
  };
449
+ const unwrappedCallableAbi = (representation) => {
450
+ if (representation.kind === 'optional')
451
+ return unwrappedCallableAbi(representation.payload);
452
+ if (representation.kind === 'borrowed-ref')
453
+ return unwrappedCallableAbi(representation.referent);
454
+ return callableAbiOf(representation);
455
+ };
456
+ /**
457
+ * The inputs a callable adapter from `sourceAbi` to `targetAbi` converts, and
458
+ * so may hand a dynamic source listener: every target input the source does
459
+ * not state in the target's own carrier.
460
+ *
461
+ * A source whose own convention declares no receiver is never handed the
462
+ * target's: the adapter ignores it (`emit-narrowing.ts`'s `resultAdapterOf`,
463
+ * `ignoresReceiver`), which is how an arrow keeps its lexical `this` in a
464
+ * method slot. An event library's async iterator class stores exactly such
465
+ * arrows as `this: EventEmitter` listeners, and promoting that receiver
466
+ * published every emitter subclass and all their fields reach -- loggers and
467
+ * connections -- to full reflection, refusing their `this.method.bind(this)`
468
+ * calls. An input the source convention states in the target's own carrier is
469
+ * forwarded unchanged; only a converted one can reach a dynamic listener.
470
+ */
471
+ const callableAdapterInputsOf = (sourceAbi, targetAbi) => {
472
+ const forwarded = (target, source) => source !== undefined && representationKey(source) === representationKey(target);
473
+ const inputs = [];
474
+ if (targetAbi.receiver !== null &&
475
+ (sourceAbi === null || (sourceAbi.receiver !== null && !forwarded(targetAbi.receiver, sourceAbi.receiver))))
476
+ inputs.push(targetAbi.receiver);
477
+ targetAbi.parameters.forEach((parameter, index) => {
478
+ const source = sourceAbi !== null && sourceAbi.restFrom === targetAbi.restFrom && sourceAbi.argumentsFrame === targetAbi.argumentsFrame
479
+ ? sourceAbi.parameters[index]?.value
480
+ : undefined;
481
+ if (!forwarded(parameter.value, source))
482
+ inputs.push(parameter.value);
483
+ });
484
+ return inputs;
485
+ };
486
+ /**
487
+ * The inputs of the installed callable adapter a member store or read
488
+ * performs inline between two native conventions, or `null` when the pair is
489
+ * not two native callables joined by an installed conversion. The adapter is
490
+ * the same one a `convert` installs, so it publishes exactly what that
491
+ * `convert` would (`callableAdapterInputsOf`) and never the callable's own
492
+ * result graph. Hono's `this.match = match` stores a receiver-less arrow into
493
+ * RegExpRouter's `this`-stating `match` slot; as an unproven slot value it
494
+ * published every handler tuple the router returns.
495
+ */
496
+ const inlineCallableAdapterInputsOf = (source, target, node) => {
497
+ const sourceAbi = unwrappedCallableAbi(source);
498
+ const targetAbi = unwrappedCallableAbi(target);
499
+ if (sourceAbi === null || targetAbi === null || node === null || node === undefined)
500
+ return null;
501
+ if (node.capability.kind !== 'atom' && node.capability.kind !== 'static')
502
+ return null;
503
+ if (representationKey(node.source) !== representationKey(source) || representationKey(node.target) !== representationKey(target))
504
+ return null;
505
+ return callableAdapterInputsOf(sourceAbi, targetAbi);
506
+ };
428
507
  const promote = (rows, representation, reason, classes, deriver, visited = new Set(), publishedChildrenCache = new Map(), observe) => {
429
508
  const work = [];
430
509
  const enqueueNativeChildren = (value, childReason, parent = null) => {
@@ -1093,8 +1172,20 @@ export const reflectionExposureOf = (bodies, classes, deriver, options) => {
1093
1172
  operation.nativeCallableDataSlot?.materialization) {
1094
1173
  citeViewNode(operation.nativeCallableDataSlot.materialization, operation.nativeCallableDataSlot.storage, { kind: 'dynamic', reason: 'declared-any-never-narrowed' }, operation);
1095
1174
  }
1096
- if (operation.kind === 'convert')
1097
- citeViewNode(operation.conversionUse, operation.source.representation, operation.result.representation, operation);
1175
+ if (operation.kind === 'convert') {
1176
+ // An unshared-array rebuild names the ELEMENT conversion each copied
1177
+ // element goes through (`ConvertOperation.rebuild`), so its node pairs
1178
+ // the element carriers, not the arrays this operation converts between.
1179
+ // Matched against the arrays it never cited, and an element converted
1180
+ // into a live view (hono's RegExpRouter maps routes to `[handler, any]`
1181
+ // tuples stored as `[handler, ParamIndexMap]`) read through a source
1182
+ // protocol nothing demanded.
1183
+ const node = operation.rebuild === 'unshared-array' ? options.conversions?.nodeById(operation.conversionUse) : null;
1184
+ if (node)
1185
+ citeViewNode(node.id, node.source, node.target, operation);
1186
+ else
1187
+ citeViewNode(operation.conversionUse, operation.source.representation, operation.result.representation, operation);
1188
+ }
1098
1189
  if (operation.kind === 'call' && operation.nativeArrayDescriptorSnapshot) {
1099
1190
  const node = options.conversions?.nodeById(operation.nativeArrayDescriptorSnapshot.conversion);
1100
1191
  if (node)
@@ -1400,6 +1491,64 @@ export const reflectionExposureOf = (bodies, classes, deriver, options) => {
1400
1491
  if (closed || unionArmCallClosed(operation))
1401
1492
  closedCallOperations.add(operation);
1402
1493
  }
1494
+ // A member read whose value is only ever the callee of a closed call is
1495
+ // that call's own dispatch, not a value: the printer calls each proven
1496
+ // function with the receiver it was read from and never materializes the
1497
+ // read. Hono's `this.router.match(method, path)` over a union of routers is
1498
+ // the shape -- RegExpRouter's `match` states its `this` in its ABI and the
1499
+ // joined read cannot, so the read looked inexact and published the
1500
+ // router's whole match result.
1501
+ // Read lazily: `closedCallOperations` is completed by later loops.
1502
+ let closedCalleeOnlyReadSet = null;
1503
+ const nativeUnboundMethodReadOf = (field, value) => {
1504
+ const node = options.conversions?.nodeById(`${conversionNodeIdOf(field, value)}#native-method`);
1505
+ return (node !== null &&
1506
+ node !== undefined &&
1507
+ node.capability.kind === 'static' &&
1508
+ node.capability.materializer.nativeMethod !== undefined &&
1509
+ node.capability.materializer.nativeFieldProtocol === 'unused');
1510
+ };
1511
+ // `router.match.bind(router)` lowers to one `bind-callable` op over the
1512
+ // method value; the `bind` read it was spelled with is left unused and
1513
+ // never emitted. Reading Function.prototype's `bind`/`call`/`apply` off a
1514
+ // callable carrier publishes nothing of the callable -- its value was
1515
+ // treated as an unproven slot and every router's match tuple went full.
1516
+ const functionPrototypeKeys = new Set(['bind', 'call', 'apply']);
1517
+ const unusedFunctionPrototypeRead = (read, receiver, key) => {
1518
+ if (read.kind !== 'get' || !functionPrototypeKeys.has(key))
1519
+ return false;
1520
+ if (receiver.kind !== 'function' &&
1521
+ receiver.kind !== 'function-family' &&
1522
+ receiver.kind !== 'function-value-dispatch' &&
1523
+ receiver.kind !== 'function-value-family')
1524
+ return false;
1525
+ closedCalleeOnlyRead(read);
1526
+ return !(operandUseCounts?.has(read.result.id) ?? true);
1527
+ };
1528
+ let operandUseCounts = null;
1529
+ const closedCalleeOnlyRead = (read) => {
1530
+ if (closedCalleeOnlyReadSet === null) {
1531
+ const found = new Set();
1532
+ const uses = new Map();
1533
+ const calleeUses = new Map();
1534
+ for (const operation of operations) {
1535
+ for (const operand of operandsOfIrOperation(operation))
1536
+ uses.set(operand.value, (uses.get(operand.value) ?? 0) + 1);
1537
+ if (operation.kind === 'call' && closedCallOperations.has(operation) && !operation.argumentsAreSpread)
1538
+ calleeUses.set(operation.callee.value, (calleeUses.get(operation.callee.value) ?? 0) + 1);
1539
+ }
1540
+ for (const operation of operations) {
1541
+ if (operation.kind !== 'get')
1542
+ continue;
1543
+ const count = calleeUses.get(operation.result.id) ?? 0;
1544
+ if (count > 0 && uses.get(operation.result.id) === count)
1545
+ found.add(operation);
1546
+ }
1547
+ closedCalleeOnlyReadSet = found;
1548
+ operandUseCounts = uses;
1549
+ }
1550
+ return closedCalleeOnlyReadSet.has(read);
1551
+ };
1403
1552
  const closedConstructOperations = new Set();
1404
1553
  for (const operation of operations) {
1405
1554
  if (operation.kind !== 'construct')
@@ -1495,13 +1644,6 @@ export const reflectionExposureOf = (bodies, classes, deriver, options) => {
1495
1644
  if (closed)
1496
1645
  closedConstructOperations.add(operation);
1497
1646
  }
1498
- const unwrappedCallableAbi = (representation) => {
1499
- if (representation.kind === 'optional')
1500
- return unwrappedCallableAbi(representation.payload);
1501
- if (representation.kind === 'borrowed-ref')
1502
- return unwrappedCallableAbi(representation.referent);
1503
- return callableAbiOf(representation);
1504
- };
1505
1647
  // A public nil method frame may wrap an explicitly dynamic source receiver.
1506
1648
  // Internal next/return calls have no ordinary callee SSA operand, so follow
1507
1649
  // their declared storage and the certified native view origins directly.
@@ -1859,6 +2001,46 @@ export const reflectionExposureOf = (bodies, classes, deriver, options) => {
1859
2001
  continue;
1860
2002
  if (nativeArrayTransportOf(operation, keyOf(keyOperandOf(operation), constants)))
1861
2003
  continue;
2004
+ // A spread the lowering admitted with a per-element conversion
2005
+ // (`IrArrayElement.element`) copies each element through the ordinary
2006
+ // `array-element` recipe (`internal-operation-conversions.ts`), so its
2007
+ // demand is that recipe's, exactly as a `convert` citing the same node.
2008
+ // Hono's `routes.push(...(ownRoute as [string, H[]][]))` is the case: the
2009
+ // elements are read by index and converted, never through a field protocol.
2010
+ if (operation.kind === 'allocate-array-object' && operation.result.representation.kind === 'array-object') {
2011
+ const element = operation.result.representation.element;
2012
+ const elementKey = representationKey(element);
2013
+ const converting = [];
2014
+ const native = operation.elements.every((slot) => {
2015
+ if (slot.kind === 'hole')
2016
+ return true;
2017
+ if (slot.kind === 'element')
2018
+ return representationKey(slot.value.representation) === elementKey;
2019
+ if (slot.kind !== 'spread' || slot.value.representation.kind !== 'array-object')
2020
+ return false;
2021
+ if (slot.element === undefined)
2022
+ return representationKey(slot.value.representation.element) === elementKey;
2023
+ if (representationKey(slot.element) !== elementKey)
2024
+ return false;
2025
+ converting.push(slot.value.representation.element);
2026
+ return true;
2027
+ });
2028
+ // Boxing an element publishes the whole of it, and a conversion the
2029
+ // program never certified is no recipe to cite: both stay on the
2030
+ // ordinary demand path below.
2031
+ const certified = converting.every((source) => options.conversions?.nodeById(conversionNodeIdOf(source, element)) != null);
2032
+ if (native && certified && element.kind !== 'dynamic' && operation.result.representation.ownership === 'shared-refcount') {
2033
+ for (const source of converting) {
2034
+ const id = conversionNodeIdOf(source, element);
2035
+ const node = options.conversions?.nodeById(id);
2036
+ if ((node?.capability.kind === 'atom' || node?.capability.kind === 'static' || node?.capability.kind === 'class-family') &&
2037
+ node.capability.materializer.nativeFieldProtocol === 'unused')
2038
+ continue;
2039
+ promoteCitedConversion(id, source, element, 'array-element-conversion');
2040
+ }
2041
+ continue;
2042
+ }
2043
+ }
1862
2044
  if (nativeDictionaryTransportOf(operation))
1863
2045
  continue;
1864
2046
  if (nativeRecordIndexTransportOf(operation, deriver, options.conversions, keyOf(keyOperandOf(operation), constants)))
@@ -1970,19 +2152,42 @@ export const reflectionExposureOf = (bodies, classes, deriver, options) => {
1970
2152
  // carriers say -- see `storesIntoDeclaredSlot` -- so the exact-carrier
1971
2153
  // and static-slot proofs below are asked only of a write that takes the
1972
2154
  // ordinary member store.
2155
+ // Inputs of an inline callable adapter an exact store or read
2156
+ // performs; published only when the access is otherwise exact.
2157
+ const adapterInputs = [];
1973
2158
  const exact = value !== null &&
1974
2159
  !(operation.kind === 'define-own-property' && !storesIntoDeclaredSlot(operation)) &&
1975
- (nativeStaticSlotHolds(receiver.representation, key, value) ||
2160
+ ((operation.kind === 'get' && closedCalleeOnlyRead(operation)) ||
2161
+ unusedFunctionPrototypeRead(operation, receiver.representation, key) ||
2162
+ nativeStaticSlotHolds(receiver.representation, key, value) ||
1976
2163
  (operation.kind === 'get' && classPrototypeReadOf(classes, receiver.representation, key, value) !== null) ||
1977
2164
  (surfaces.length > 0 &&
1978
2165
  surfaces.every((surface) => {
1979
2166
  const field = declaredFieldOf(surface, key, classes, deriver);
1980
2167
  return ((field !== null &&
1981
2168
  (representationKey(field.value) === representationKey(value) ||
2169
+ // A `this`-stating callable field read as a plain
2170
+ // function value -- SmartRouter's `router.match` off a
2171
+ // RegExpRouter whose `match` field holds `function
2172
+ // match(this: R, ...)` -- is the native unbound-method
2173
+ // view `fieldReadFor` mints (`#native-method`): the
2174
+ // receiver is resolved later by native type tests.
2175
+ (operation.kind === 'get' && nativeUnboundMethodReadOf(field.value, value)) ||
1982
2176
  (operation.kind === 'get' &&
1983
2177
  nativePayloadTransportMatches(field.value, value, options.conversions?.nodeById(conversionNodeIdOf(field.value, value)))) ||
1984
2178
  (storesIntoDeclaredSlot(operation) &&
1985
- nativePayloadTransportMatches(value, field.value, options.conversions?.nodeById(conversionNodeIdOf(value, field.value)))))) ||
2179
+ nativePayloadTransportMatches(value, field.value, options.conversions?.nodeById(conversionNodeIdOf(value, field.value)))) ||
2180
+ (() => {
2181
+ const inputs = operation.kind === 'get'
2182
+ ? inlineCallableAdapterInputsOf(field.value, value, options.conversions?.nodeById(conversionNodeIdOf(field.value, value)))
2183
+ : storesIntoDeclaredSlot(operation)
2184
+ ? inlineCallableAdapterInputsOf(value, field.value, options.conversions?.nodeById(conversionNodeIdOf(value, field.value)))
2185
+ : null;
2186
+ if (inputs === null)
2187
+ return false;
2188
+ adapterInputs.push(...inputs);
2189
+ return true;
2190
+ })())) ||
1986
2191
  (operation.kind === 'get' &&
1987
2192
  // An index read of one arm that is an Array -- a tuple
1988
2193
  // carried as an Array beside a sibling tuple carried as
@@ -2002,6 +2207,9 @@ export const reflectionExposureOf = (bodies, classes, deriver, options) => {
2002
2207
  if (value)
2003
2208
  promoteFull(value, 'unproven-native-slot-value');
2004
2209
  }
2210
+ else
2211
+ for (const input of adapterInputs)
2212
+ promoteFull(input, 'callable-adapter-input');
2005
2213
  }
2006
2214
  continue;
2007
2215
  }
@@ -2025,6 +2233,33 @@ export const reflectionExposureOf = (bodies, classes, deriver, options) => {
2025
2233
  for (const record of dynamicallyAdoptedRecords(operation.source.representation, operation.result.representation))
2026
2234
  promoteFull(record, 'dynamic-document-adoption');
2027
2235
  }
2236
+ // An unshared array rebuilt at another element carrier
2237
+ // (`ConvertOperation.rebuild`) cites the ELEMENT conversion each copied
2238
+ // element goes through, so its demand is that conversion's -- the copy
2239
+ // itself is `appendRangeConverted` over native storage. Hono's static
2240
+ // route table (`[handlers.map(([h]) => [h, Object.create(null)]),
2241
+ // emptyParam]`) is the case: the `[T, any]` tuples are rebuilt as `[T,
2242
+ // ParamIndexMap]`, and only the unboxed dictionary is read dynamically.
2243
+ if (operation.kind === 'convert' && operation.rebuild === 'unshared-array') {
2244
+ const unwrap = (value) => (value.kind === 'promise' ? value.value : value);
2245
+ const source = unwrap(operation.source.representation);
2246
+ const target = unwrap(operation.result.representation);
2247
+ const node = options.conversions?.nodeById(operation.conversionUse);
2248
+ if (source.kind === 'array-object' &&
2249
+ target.kind === 'array-object' &&
2250
+ node !== null &&
2251
+ node !== undefined &&
2252
+ representationKey(node.source) === representationKey(source.element) &&
2253
+ representationKey(node.target) === representationKey(target.element)) {
2254
+ const capability = node.capability;
2255
+ if (capability.kind === 'identity' ||
2256
+ ((capability.kind === 'atom' || capability.kind === 'static' || capability.kind === 'class-family') &&
2257
+ capability.materializer.nativeFieldProtocol === 'unused'))
2258
+ continue;
2259
+ promoteCitedConversion(operation.conversionUse, source.element, target.element, 'unshared-array-element-conversion');
2260
+ continue;
2261
+ }
2262
+ }
2028
2263
  if (operation.kind === 'convert') {
2029
2264
  const node = options.conversions?.nodeById(operation.conversionUse);
2030
2265
  if (node?.capability.kind === 'static' &&
@@ -2073,31 +2308,9 @@ export const reflectionExposureOf = (bodies, classes, deriver, options) => {
2073
2308
  // conversion that installs it.
2074
2309
  if (reflectionWatch !== undefined && targetAbi !== null)
2075
2310
  console.error(`[REFLECTION-ADAPTER] lineage=${String(operation.lineage)} node=${operation.conversionUse} capability=${node?.capability.kind ?? 'none'}`);
2076
- if (targetAbi !== null) {
2077
- // A source whose own convention declares no receiver is never handed
2078
- // the target's: the adapter ignores it (`emit-narrowing.ts`'s
2079
- // `resultAdapterOf`, `ignoresReceiver`), which is how an arrow keeps
2080
- // its lexical `this` in a method slot. An event library's async
2081
- // iterator class stores exactly such arrows as `this: EventEmitter` listeners, and
2082
- // promoting that receiver published every emitter subclass and all
2083
- // their fields reach -- loggers and connections -- to full
2084
- // reflection, refusing their `this.method.bind(this)` calls.
2085
- const sourceAbi = unwrappedCallableAbi(operation.source.representation);
2086
- // An input the source convention states in the target's own carrier
2087
- // is forwarded unchanged by the adapter; only a converted one can
2088
- // reach a dynamic listener.
2089
- const forwarded = (target, source) => source !== undefined && representationKey(source) === representationKey(target);
2090
- if (targetAbi.receiver !== null &&
2091
- (sourceAbi === null || (sourceAbi.receiver !== null && !forwarded(targetAbi.receiver, sourceAbi.receiver))))
2092
- promoteFull(targetAbi.receiver, 'callable-adapter-input');
2093
- targetAbi.parameters.forEach((parameter, index) => {
2094
- const source = sourceAbi !== null && sourceAbi.restFrom === targetAbi.restFrom && sourceAbi.argumentsFrame === targetAbi.argumentsFrame
2095
- ? sourceAbi.parameters[index]?.value
2096
- : undefined;
2097
- if (!forwarded(parameter.value, source))
2098
- promoteFull(parameter.value, 'callable-adapter-input');
2099
- });
2100
- }
2311
+ if (targetAbi !== null)
2312
+ for (const input of callableAdapterInputsOf(unwrappedCallableAbi(operation.source.representation), targetAbi))
2313
+ promoteFull(input, 'callable-adapter-input');
2101
2314
  }
2102
2315
  if (observesNativeCarrierOnly(operation))
2103
2316
  continue;
package/dist/ir/shake.js CHANGED
@@ -346,7 +346,21 @@ const sliceBody = (body, placements, liveCells, structuralViewScopes) => {
346
346
  operation.kind === 'define-own-property') {
347
347
  const text = constants.get(operation.key.value);
348
348
  const scopes = receiverClassScopes(operation.receiver.representation, structuralViewScopes);
349
- if (text !== undefined)
349
+ // A computed key the semantic graph proved to a finite name set
350
+ // (`GetOperation.provenKeyTexts`) names exactly those members, the same
351
+ // fact `reflection-demand.ts` demands fields by. Hono's
352
+ // `bodyCache[key]` for `key: keyof Body` reads a cache boxed because
353
+ // `Body` states `json: any`; filed as an unknown key on an unknown
354
+ // receiver, it kept every method of every class -- `HonoRequest#query`
355
+ // and the query-string parser nothing calls among them.
356
+ const proven = text === undefined && (operation.kind === 'get' || operation.kind === 'set') && operation.provenKeyTexts?.length
357
+ ? operation.provenKeyTexts
358
+ : undefined;
359
+ if (proven !== undefined)
360
+ for (const scope of scopes)
361
+ for (const key of proven)
362
+ spelledKeys.add(`${scope}#${key}`);
363
+ else if (text !== undefined)
350
364
  for (const scope of scopes)
351
365
  spelledKeys.add(`${scope}#${text}`);
352
366
  // A dynamic key is a hazard only where it READS. `fieldInitializerRuns`
@@ -13,7 +13,7 @@ import type { Representation } from './model.js';
13
13
  * one side could drift from the other, and the frame would then describe C++
14
14
  * the printer no longer emits.
15
15
  */
16
- export type HostTemplate = 'object-assign' | 'array-is-array' | 'array-from' | 'typed-array-set' | 'json-stringify';
16
+ export type HostTemplate = 'object-assign' | 'object-create' | 'array-is-array' | 'array-from' | 'typed-array-set' | 'json-stringify';
17
17
  /**
18
18
  * The host protocol a member read off this receiver is looked up on, or `null`.
19
19
  *
@@ -26,9 +26,11 @@ export const hostMemberTemplateOf = (protocol, member) => protocol === 'ArrayCon
26
26
  ? 'array-from'
27
27
  : protocol === 'ObjectConstructor' && member === 'assign'
28
28
  ? 'object-assign'
29
- : protocol === 'JSON' && member === 'stringify'
30
- ? 'json-stringify'
31
- : null;
29
+ : protocol === 'ObjectConstructor' && member === 'create'
30
+ ? 'object-create'
31
+ : protocol === 'JSON' && member === 'stringify'
32
+ ? 'json-stringify'
33
+ : null;
32
34
  /** A union whose every arm is a typed array: one `%TypedArray%.prototype` receiver whose arm the invoker dispatches. */
33
35
  export const typedArrayUnionOnly = (representation) => representation.kind === 'tagged-union' && representation.arms.every((arm) => arm.value.kind === 'typed-array');
34
36
  /** The template a deferred `%TypedArray%.prototype` member's call is spelled from, for the members this file names. */
@@ -0,0 +1,36 @@
1
+ import ts from 'typescript';
2
+ /**
3
+ * A method called through an `as any` receiver whose result the program
4
+ * immediately states: `const matchers: MatcherMap<T> = (this as any)
5
+ * .buildAllMatchers()`.
6
+ *
7
+ * Hono's RegExpRouter installs a free `match` function as its `match` field,
8
+ * and that function calls back into the router through `this as any` because
9
+ * its declared receiver (`R extends Router<T>`) names no such method. The `as`
10
+ * erases the static type and nothing else: the receiver is still the router
11
+ * carrier, and the read and call dispatch over its classes exactly as a typed
12
+ * member call does. Typed `any`, the read boxed the method, the call published
13
+ * every router's fields to a dynamic call, and the result was unboxed into the
14
+ * binding the program states anyway.
15
+ *
16
+ * The call takes the stated slot's type, and its callee is a callable taking
17
+ * the erased receiver and returning it, or `undefined` -- a receiver class with no
18
+ * such member answers `undefined` and the call throws the TypeError calling it
19
+ * throws. Nothing here asserts that a receiver class returns the stated type:
20
+ * each class's method is converted into that callable where it is read, and a
21
+ * method whose result has no conversion into the slot refuses there.
22
+ *
23
+ * Fail-closed: only a non-optional property call with no arguments, on an
24
+ * `as any` operand the checker types as something other than `any`/`unknown`,
25
+ * whose result initializes a binding with a stated type or is returned from a
26
+ * function with a stated, non-async, non-generator return.
27
+ */
28
+ export interface AnyCastMemberCall {
29
+ readonly call: ts.CallExpression;
30
+ readonly read: ts.PropertyAccessExpression;
31
+ /** The receiver the `as any` erased: what the method is read off and called on. */
32
+ readonly receiver: ts.Expression;
33
+ /** The type the program states for the call's result. */
34
+ readonly stated: ts.Type;
35
+ }
36
+ export declare const anyCastMemberCallOf: (checker: ts.TypeChecker, node: ts.Node) => AnyCastMemberCall | null;
@@ -0,0 +1,55 @@
1
+ import ts from 'typescript';
2
+ const unwrapParens = (node) => {
3
+ let current = node;
4
+ while (ts.isParenthesizedExpression(current))
5
+ current = current.expression;
6
+ return current;
7
+ };
8
+ const isAnyKeyword = (node) => node.kind === ts.SyntaxKind.AnyKeyword;
9
+ const statedResultOf = (checker, call) => {
10
+ let value = call;
11
+ while (ts.isParenthesizedExpression(value.parent))
12
+ value = value.parent;
13
+ const parent = value.parent;
14
+ if (ts.isVariableDeclaration(parent) && parent.initializer === value && parent.type)
15
+ return checker.getTypeFromTypeNode(parent.type);
16
+ if (ts.isReturnStatement(parent) && parent.expression === value) {
17
+ let owner = parent.parent;
18
+ while (owner && !ts.isFunctionLike(owner))
19
+ owner = owner.parent;
20
+ if (!owner || !ts.isFunctionLike(owner) || !owner.type || ts.isConstructorDeclaration(owner))
21
+ return null;
22
+ const modifiers = ts.canHaveModifiers(owner) ? ts.getModifiers(owner) : undefined;
23
+ if (modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword))
24
+ return null;
25
+ if ('asteriskToken' in owner && owner.asteriskToken !== undefined)
26
+ return null;
27
+ return checker.getTypeFromTypeNode(owner.type);
28
+ }
29
+ return null;
30
+ };
31
+ export const anyCastMemberCallOf = (checker, node) => {
32
+ const read = ts.isCallExpression(node) ? unwrapParens(node.expression) : node;
33
+ if (!ts.isPropertyAccessExpression(read) || read.questionDotToken !== undefined || !ts.isIdentifier(read.name))
34
+ return null;
35
+ let callee = read;
36
+ while (ts.isParenthesizedExpression(callee.parent))
37
+ callee = callee.parent;
38
+ const call = callee.parent;
39
+ if (!ts.isCallExpression(call) || call.expression !== callee || call.questionDotToken !== undefined)
40
+ return null;
41
+ if (ts.isCallExpression(node) && node !== call)
42
+ return null;
43
+ if (call.arguments.length !== 0 || call.typeArguments !== undefined)
44
+ return null;
45
+ const receiver = unwrapParens(read.expression);
46
+ if (!(ts.isAsExpression(receiver) || ts.isTypeAssertionExpression(receiver)) || !isAnyKeyword(receiver.type))
47
+ return null;
48
+ const erased = checker.getTypeAtLocation(receiver.expression);
49
+ if ((erased.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) !== 0)
50
+ return null;
51
+ const stated = statedResultOf(checker, call);
52
+ if (stated === null || (stated.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Void)) !== 0)
53
+ return null;
54
+ return { call, read, receiver: receiver.expression, stated };
55
+ };
@@ -2498,11 +2498,33 @@ export const containsUnstatedPosition = (checker, anchor, declared, depth = 0) =
2498
2498
  }
2499
2499
  if ((declared.flags & ts.TypeFlags.Object) === 0)
2500
2500
  return false;
2501
+ // Checked before the reference: `Record<string, V>` is a mapped-type
2502
+ // instantiation that carries a `target` but no type arguments. A table whose
2503
+ // value is `any` itself (`{ [key: string]: any }`) is the open Document
2504
+ // carrier, a stated choice rather than an open position: counting it let a
2505
+ // `WireDocument[]` binding narrow to the `{}` records it was initialized with.
2506
+ const dictionary = pureDictionaryIndexesOf(checker, declared);
2507
+ if (dictionary !== null)
2508
+ return dictionary.some((index) => (index.type.flags & ts.TypeFlags.Any) === 0 && containsUnstatedPosition(checker, anchor, index.type, depth + 1));
2501
2509
  const reference = declared;
2502
2510
  if (reference.target === undefined)
2503
2511
  return false;
2504
2512
  return checker.getTypeArguments(reference).some((part) => containsUnstatedPosition(checker, anchor, part, depth + 1));
2505
2513
  };
2514
+ /**
2515
+ * The index signatures of an object type that is NOTHING but index
2516
+ * signatures -- `Record<string, V>` and `{ [key: string]: V }`, which the
2517
+ * checker resolves to an anonymous type rather than a reference with type
2518
+ * arguments -- or `null` for any other type.
2519
+ */
2520
+ const pureDictionaryIndexesOf = (checker, type) => {
2521
+ if ((type.flags & ts.TypeFlags.Object) === 0 || type.isUnion() || type.isIntersection())
2522
+ return null;
2523
+ if (type.getProperties().length > 0 || type.getCallSignatures().length > 0 || type.getConstructSignatures().length > 0)
2524
+ return null;
2525
+ const indexes = checker.getIndexInfosOfType(type);
2526
+ return indexes.length > 0 ? indexes : null;
2527
+ };
2506
2528
  /**
2507
2529
  * WHETHER A STATED TYPE AND THE TYPE THAT ACTUALLY FLOWS INTO IT DIFFER ONLY
2508
2530
  * WHERE THE STATEMENT SAID NOTHING.
@@ -2553,6 +2575,24 @@ export const narrowsOnlyUnstatedPositions = (checker, anchor, declared, actual,
2553
2575
  .getIndexInfosOfType(declared)
2554
2576
  .some((index) => !actualIndexes.some((candidate) => checker.isTypeAssignableTo(index.keyType, candidate.keyType))))
2555
2577
  return false;
2578
+ // `Record<string, unknown>` fed a `Record<string, Node>`: a dictionary's one
2579
+ // stated thing besides its key is its value, and that is compared position
2580
+ // by position like a reference's type arguments below. The actual must be
2581
+ // a dictionary over the same keys and nothing else -- asked BEFORE the
2582
+ // mutual-assignability shortcut, which calls `{}` and `{ [key: string]: any }`
2583
+ // one type and so narrowed a stated `WireDocument[]` to empty records.
2584
+ const declaredIndexes = pureDictionaryIndexesOf(checker, declared);
2585
+ if (declaredIndexes !== null) {
2586
+ const actualDictionary = pureDictionaryIndexesOf(checker, actual);
2587
+ if (actualDictionary === null || actualDictionary.length !== declaredIndexes.length)
2588
+ return false;
2589
+ return declaredIndexes.every((index) => {
2590
+ const other = actualDictionary.find((candidate) => candidate.keyType === index.keyType);
2591
+ return (other !== undefined &&
2592
+ other.isReadonly === index.isReadonly &&
2593
+ narrowsOnlyUnstatedPositions(checker, anchor, index.type, other.type, depth + 1));
2594
+ });
2595
+ }
2556
2596
  // Two spellings of one type -- an alias and its expansion, `Params` and
2557
2597
  // `Record<string, string>` -- state the identical thing at every position.
2558
2598
  if (checker.isTypeAssignableTo(actual, declared) && checker.isTypeAssignableTo(declared, actual))