@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
@@ -1743,6 +1743,59 @@ const closedMemberCallableUses = (checker, flow, member, countedCalls, givenRece
1743
1743
  ? valueMode.explicitInvocationIsIntact(call)
1744
1744
  : deferredIntrinsicProtocolLedgerOf(flow)?.requirePrototypeKeys('Function', { names: [wrapper.name.text] }, call) === true;
1745
1745
  };
1746
+ /**
1747
+ * Every caller of the function value `value` holds, when the cell it
1748
+ * initializes is the function's only handle: a `const` written once, whose
1749
+ * every executable use -- in its own module or an importer's -- is an
1750
+ * entered call, or initializes another such cell. Hono exports its query
1751
+ * parser twice, `getQueryParam = _getQueryParam as (...) => ...` and a
1752
+ * wrapper calling it directly; the cast alias is one more name for the same
1753
+ * function, and its calls are this function's calls.
1754
+ */
1755
+ const closedBindingCallsOf = (value, counted, sites, depth) => {
1756
+ if (depth > 4)
1757
+ return false;
1758
+ const initializer = outermostErasureOf(value);
1759
+ const binding = initializer.parent;
1760
+ if (!ts.isVariableDeclaration(binding) ||
1761
+ binding.initializer !== initializer ||
1762
+ !ts.isIdentifier(binding.name) ||
1763
+ !localBindingWritesAreComplete(flow, binding))
1764
+ return false;
1765
+ const writes = flow.writesToDeclaration(binding).filter((write) => write.slot === 'whole');
1766
+ if (writes.length === 0 ||
1767
+ writes.some((write) => write.edge !== 'declaration-initializer' ||
1768
+ write.value === null ||
1769
+ unwrapValue(write.value) !== unwrapValue(value)))
1770
+ return false;
1771
+ const exported = isModuleExportedDeclaration(checker, binding, checker.getSymbolAtLocation(binding.name) ?? null);
1772
+ const imported = exported ? inProgramImportReferencesOf(checker, flow, binding) : [];
1773
+ if (imported === null)
1774
+ return false;
1775
+ for (const reference of new Set([...flow.referencesToDeclaration(binding), ...imported])) {
1776
+ if (reference === binding.name || isTypePositionReference(reference))
1777
+ continue;
1778
+ const parent = reference.parent;
1779
+ if (ts.isImportSpecifier(parent) || ts.isImportClause(parent) || ts.isExportSpecifier(parent))
1780
+ continue;
1781
+ const use = outermostErasureOf(reference);
1782
+ const call = use.parent;
1783
+ if (ts.isCallExpression(call) && call.expression === use) {
1784
+ if (counted.has(call))
1785
+ continue;
1786
+ const site = callsOf(flow).sites.get(call);
1787
+ if (site === undefined)
1788
+ return false;
1789
+ if (!sites.includes(site))
1790
+ sites.push(site);
1791
+ continue;
1792
+ }
1793
+ if (ts.isVariableDeclaration(call) && call.initializer === use && closedBindingCallsOf(reference, counted, sites, depth + 1))
1794
+ continue;
1795
+ return false;
1796
+ }
1797
+ return true;
1798
+ };
1746
1799
  const closedCallerSitesUncached = (declaration) => {
1747
1800
  if (ts.isConstructorDeclaration(declaration)) {
1748
1801
  const calls = constructorCallsOf(checker, flow, declaration);
@@ -1856,30 +1909,10 @@ const closedMemberCallableUses = (checker, flow, member, countedCalls, givenRece
1856
1909
  // A function expression has no declaration binding of its own. Its
1857
1910
  // exact initializer cell can nevertheless name every caller, provided
1858
1911
  // that cell never changes and every executable use is an entered call.
1859
- const value = outermostErasureOf(declaration);
1860
- const binding = value.parent;
1861
- if (!ts.isVariableDeclaration(binding) ||
1862
- binding.initializer !== value ||
1863
- !ts.isIdentifier(binding.name) ||
1864
- !flow.callableBodyIsIndexed(declaration) ||
1865
- (argumentsUsesAt(declaration)?.length ?? 0) > 0 ||
1866
- !localBindingWritesAreComplete(flow, binding) ||
1867
- isModuleExportedDeclaration(checker, binding, checker.getSymbolAtLocation(binding.name) ?? null))
1868
- return null;
1869
- const writes = flow.writesToDeclaration(binding).filter((write) => write.slot === 'whole');
1870
- if (writes.length === 0 ||
1871
- writes.some((write) => write.edge !== 'declaration-initializer' || write.value === null || unwrapValue(write.value) !== declaration))
1912
+ if (!flow.callableBodyIsIndexed(declaration) || (argumentsUsesAt(declaration)?.length ?? 0) > 0)
1872
1913
  return null;
1873
- for (const reference of flow.referencesToDeclaration(binding)) {
1874
- if (reference === binding.name || isTypePositionReference(reference))
1875
- continue;
1876
- const use = outermostErasureOf(reference);
1877
- const parent = use.parent;
1878
- if (ts.isCallExpression(parent) && parent.expression === use && counted.has(parent))
1879
- continue;
1880
- return null;
1881
- }
1882
- return calls;
1914
+ const sites = [...calls];
1915
+ return closedBindingCallsOf(declaration, counted, sites, 0) ? sites : null;
1883
1916
  }
1884
1917
  if (!ts.isFunctionDeclaration(declaration) || !declaration.name || !declaration.body)
1885
1918
  return null;
@@ -29,4 +29,6 @@ export declare const dictionaryArmIndexOf: (checker: ts.TypeChecker, type: ts.Ty
29
29
  * @semanticCategory generic-primitive
30
30
  */
31
31
  export declare const censusFreshDictionaryStorage: (checker: ts.TypeChecker, flow: ValueFlowIndex | undefined, parameters: ParameterBindingCensus) => FreshDictionaryStorageCensus;
32
+ /** `Object.create(null)` on the standard `Object`: a fresh object with no prototype and no own keys. */
33
+ export declare const isNullPrototypeCreate: (checker: ts.TypeChecker, node: ts.Expression) => node is ts.CallExpression;
32
34
  export {};
@@ -124,6 +124,7 @@ export const censusFreshDictionaryStorage = (checker, flow, parameters) => {
124
124
  const aliases = [];
125
125
  const inputs = [];
126
126
  const writes = [];
127
+ const aliasResults = new Map();
127
128
  const connect = (from, to) => {
128
129
  aliases.push({ from, to });
129
130
  if (nodes.get(from) !== nodes.get(to)) {
@@ -135,6 +136,12 @@ export const censusFreshDictionaryStorage = (checker, flow, parameters) => {
135
136
  if (fresh.has(expression))
136
137
  return expression;
137
138
  const entries = [];
139
+ if (ts.isCallExpression(expression)) {
140
+ fresh.add(expression);
141
+ nodes.set(expression, key);
142
+ origins.push({ node: expression, entries });
143
+ return expression;
144
+ }
138
145
  for (const property of expression.properties) {
139
146
  if (ts.isPropertyAssignment(property)) {
140
147
  if (ts.isComputedPropertyName(property.name) ||
@@ -160,6 +167,20 @@ export const censusFreshDictionaryStorage = (checker, flow, parameters) => {
160
167
  const target = targets?.length === 1 ? targets[0] : undefined;
161
168
  return target && flow.callableBodyIsIndexed(target) ? target : null;
162
169
  };
170
+ // A write into a table the program states as several views stores the one
171
+ // view its value fits: `results[name] = []` over `Record<string, string> |
172
+ // Record<string, string[]>` stores a `string[]`, which the `never[]` the
173
+ // checker gives the empty literal says nothing about.
174
+ const writtenEntryTypeOf = (receiver, value) => {
175
+ const declared = indexesOf(typeAt(receiver)).map((index) => index.value);
176
+ if (declared.length > 1) {
177
+ const actual = checker.getTypeAtLocation(unwrapErasedExpression(value));
178
+ const fits = declared.filter((entry) => checker.isTypeAssignableTo(actual, entry));
179
+ if (fits.length === 1)
180
+ return fits[0];
181
+ }
182
+ return entryTypeAt(value);
183
+ };
163
184
  const excludesTable = (type) => {
164
185
  if (type.isUnion())
165
186
  return type.types.every(excludesTable);
@@ -178,6 +199,12 @@ export const censusFreshDictionaryStorage = (checker, flow, parameters) => {
178
199
  return [];
179
200
  if (ts.isObjectLiteralExpression(source))
180
201
  return [makeOrigin(source, targetKey)];
202
+ // `Object.create(null)` is an empty table with no prototype to read
203
+ // through, exactly the storage a closed component lays out. Hono's
204
+ // `_getQueryParam` starts its results this way; typed `any`, it was an
205
+ // unknown input that refused the whole component.
206
+ if (isNullPrototypeCreate(checker, source))
207
+ return [makeOrigin(source, targetKey)];
181
208
  if (ts.isConditionalExpression(source))
182
209
  return [...sourcesOf(source.whenTrue, targetKey), ...sourcesOf(source.whenFalse, targetKey)];
183
210
  if (ts.isBinaryExpression(source)) {
@@ -241,10 +268,11 @@ export const censusFreshDictionaryStorage = (checker, flow, parameters) => {
241
268
  for (const source of sourcesOf(receiver, targetKey)) {
242
269
  if (source === null)
243
270
  continue;
244
- if (!write.value || (write.edge !== 'property-assignment' && write.edge !== 'index-assignment'))
271
+ if (!write.value ||
272
+ (write.edge !== 'property-assignment' && write.edge !== 'index-assignment' && write.edge !== 'logical-assignment'))
245
273
  blocked.add(source);
246
274
  else
247
- writes.push({ node: source, value: entryTypeAt(write.value) });
275
+ writes.push({ node: source, value: writtenEntryTypeOf(receiver, write.value) });
248
276
  }
249
277
  }
250
278
  for (const [node, key] of nodes) {
@@ -283,6 +311,12 @@ export const censusFreshDictionaryStorage = (checker, flow, parameters) => {
283
311
  continue;
284
312
  }
285
313
  connect(node, site.call);
314
+ // A call through a cast alias (`getQueryParam = _getQueryParam as
315
+ // (...) => ...`) selects the alias's own signature; it names the
316
+ // same function, so its result is this component's too.
317
+ const selected = checker.getResolvedSignature(site.call)?.declaration;
318
+ if (selected && selected !== node && ts.isFunctionTypeNode(selected))
319
+ aliasResults.set(selected, node);
286
320
  }
287
321
  }
288
322
  }
@@ -358,6 +392,21 @@ export const censusFreshDictionaryStorage = (checker, flow, parameters) => {
358
392
  const referenceIsAccounted = (node, reference) => {
359
393
  if (isTypePositionReference(reference))
360
394
  return true;
395
+ // A downcast to a type no table can be -- `query(url, key) as string` --
396
+ // selects the call's other arm, a checked selection the table never
397
+ // passes. Only a true downcast: an `as unknown` hop keeps the table's
398
+ // identity (`table as unknown as string[]` iterates the table itself).
399
+ for (let erased = reference; erased !== outermostErasureOf(reference);) {
400
+ const outer = erased.parent;
401
+ if (ts.isAsExpression(outer) || ts.isTypeAssertionExpression(outer)) {
402
+ const asserted = checker.getTypeFromTypeNode(outer.type);
403
+ if (asserted.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown))
404
+ break;
405
+ if (excludesTable(asserted) && checker.isTypeAssignableTo(asserted, checker.getTypeAtLocation(reference)))
406
+ return true;
407
+ }
408
+ erased = outer;
409
+ }
361
410
  const owner = ts.findAncestor(reference, ts.isFunctionLike);
362
411
  const storageOwner = ts.findAncestor(node, ts.isFunctionLike);
363
412
  if (owner && owner !== storageOwner && callable.closedCallerSitesOf?.(owner) == null)
@@ -475,13 +524,14 @@ export const censusFreshDictionaryStorage = (checker, flow, parameters) => {
475
524
  if (!proofFor(node, () => referenceIsAccounted(node, reference)))
476
525
  blocked.add(node);
477
526
  }
527
+ const exits = exitsOf(blocked, aliases, (node) => indexesOf(resultTypeOf(node)).length === 1);
478
528
  const authority = createFreshIndexedStorageAuthority({
479
529
  origins,
480
- aliases,
481
- writes,
482
- inputs,
483
- blocked: [...blocked],
484
- nodes: [...nodes.keys()]
530
+ aliases: aliases.filter((alias) => !exits.has(alias.to)),
531
+ writes: writes.filter((write) => !exits.has(write.node)),
532
+ inputs: inputs.filter((input) => !exits.has(input.node)),
533
+ blocked: [...blocked].filter((node) => !exits.has(node)),
534
+ nodes: [...nodes.keys()].filter((node) => !exits.has(node))
485
535
  });
486
536
  const published = new Set();
487
537
  const factOf = (node) => {
@@ -500,7 +550,7 @@ export const censusFreshDictionaryStorage = (checker, flow, parameters) => {
500
550
  return { key, component };
501
551
  };
502
552
  return {
503
- resultOf: factOf,
553
+ resultOf: (declaration) => factOf(aliasResults.get(declaration) ?? declaration),
504
554
  storageAt: (node) => {
505
555
  if (nodes.has(node))
506
556
  return factOf(node);
@@ -528,3 +578,60 @@ export const censusFreshDictionaryStorage = (checker, flow, parameters) => {
528
578
  }
529
579
  };
530
580
  };
581
+ /** `Object.create(null)` on the standard `Object`: a fresh object with no prototype and no own keys. */
582
+ export const isNullPrototypeCreate = (checker, node) => {
583
+ if (!ts.isCallExpression(node) || node.arguments.length !== 1 || node.arguments[0]?.kind !== ts.SyntaxKind.NullKeyword)
584
+ return false;
585
+ const callee = unwrapErasedExpression(node.expression);
586
+ return (ts.isPropertyAccessExpression(callee) && callee.name.text === 'create' && isStandardGlobalValue(checker, callee.expression, 'Object'));
587
+ };
588
+ /**
589
+ * Blocked nodes the table only flows INTO, each stating one table view.
590
+ *
591
+ * A component reaching a public method is the ordinary case, not the
592
+ * exception: hono's `HonoRequest.query()` returns the query parser's table to
593
+ * whatever the application does with it -- `JSON.stringify`, a field, a
594
+ * callback -- and no closed proof covers that. Blocking such a consumer
595
+ * refused the whole component, and the parser's one null-prototype object
596
+ * fell back to a sum of two dictionaries no write could fill. A consumer that
597
+ * never hands a table back keeps its declared single view and receives the
598
+ * table through a dictionary VIEW at the edge -- the same object, read and
599
+ * written through its own entry carrier -- so nothing downstream needs the
600
+ * component's storage. Its whole downstream must be single-view too, or the
601
+ * view would have to widen back into a table of several views.
602
+ */
603
+ const exitsOf = (blocked, aliases, singleView) => {
604
+ const downstream = new Map();
605
+ const upstream = new Map();
606
+ for (const { from, to } of aliases) {
607
+ if (from === to)
608
+ continue;
609
+ downstream.set(from, [...(downstream.get(from) ?? []), to]);
610
+ upstream.set(to, [...(upstream.get(to) ?? []), from]);
611
+ }
612
+ const exits = new Set();
613
+ for (const start of blocked) {
614
+ if (exits.has(start) || !singleView(start) || !upstream.has(start))
615
+ continue;
616
+ const closure = new Set([start]);
617
+ const pending = [start];
618
+ let closed = true;
619
+ while (closed && pending.length > 0) {
620
+ for (const next of downstream.get(pending.pop()) ?? []) {
621
+ if (closure.has(next))
622
+ continue;
623
+ if (!singleView(next))
624
+ closed = false;
625
+ closure.add(next);
626
+ pending.push(next);
627
+ }
628
+ }
629
+ if (!closed)
630
+ continue;
631
+ // Every edge into the closure from outside it is a view boundary; an
632
+ // edge out of the closure back into the component would widen.
633
+ for (const node of closure)
634
+ exits.add(node);
635
+ }
636
+ return exits;
637
+ };
@@ -1,5 +1,5 @@
1
1
  import ts from 'typescript';
2
- import { annotationStatesNothing, exactEmptyObjectLiteralType, derivedExpressionType, disjointUnionMembersOf, indexedTypeOf, explicitThisCallReturnType, overloadInvariantReturnTypeAt, joinOfWrites as sharedJoinOfWrites, jsDocTypeStatesNothing, literalMemberNameOf, memberTypeOf, normalizedArrayConditionalType, objectAssignCellTargetType, objectAssignTargetType, isEmptyObjectType, synthesizedUnionArmsAt, unwrapExplicitThisCall, withoutUndefinedMember, widestOf } from './derived-expression-type.js';
2
+ import { annotationStatesNothing, exactEmptyObjectLiteralType, arrayPredicateNarrowedElementTypeOf, derivedExpressionType, disjointUnionMembersOf, indexedTypeOf, explicitThisCallReturnType, overloadInvariantReturnTypeAt, joinOfWrites as sharedJoinOfWrites, jsDocTypeStatesNothing, literalMemberNameOf, memberTypeOf, normalizedArrayConditionalType, objectAssignCellTargetType, objectAssignTargetType, isEmptyObjectType, synthesizedUnionArmsAt, unwrapExplicitThisCall, withoutUndefinedMember, widestOf } from './derived-expression-type.js';
3
3
  import { emptyParameterBindingCensus } from './parameter-bindings.js';
4
4
  import { emptyCollectionBindingCensus } from './collection-bindings.js';
5
5
  import { emptyObjectBagCensus } from './object-bag-bindings.js';
@@ -1593,6 +1593,13 @@ moduleRecords = emptyCommonJsModuleRecordCensus) => {
1593
1593
  const upstream = parameters.typeAt(node);
1594
1594
  if (upstream)
1595
1595
  return upstream;
1596
+ // `Array.isArray(pattern) ? pattern[0] : p` reads the tuple the
1597
+ // predicate narrowed to, not the receiver's declared union: resolving
1598
+ // the receiver through its declaration loses the narrowing, and hono's
1599
+ // trie-router `key` stayed `any` and was boxed into every lookup.
1600
+ const predicateNarrowed = arrayPredicateNarrowedElementTypeOf(checker, node);
1601
+ if (predicateNarrowed)
1602
+ return predicateNarrowed;
1596
1603
  const receiver = knownOrResolve(node.expression);
1597
1604
  if (!receiver)
1598
1605
  return collections.arrayElementForRead(node.expression) ?? bags.slotTypeAt(node);
@@ -1,8 +1,8 @@
1
1
  import ts from 'typescript';
2
2
  import { normalCompletion, pureEffects } from '../../model/operands.js';
3
- import { assertsType, unwrapErased } from './erasure.js';
3
+ import { assertsType, unwrapErasedExpression } from './erasure.js';
4
4
  import { blocked, mintOperationId, mintResult, operand } from './mint.js';
5
- import { logicalMergeTypeOf } from './logical-merge-type.js';
5
+ import { citedValueTypeAt } from './cited-value-type.js';
6
6
  import { citeExpressionResult } from './references.js';
7
7
  import { valueEdgesInto } from './shared.js';
8
8
  /**
@@ -28,29 +28,10 @@ export const resolveExpressionOperand = (context, node) => {
28
28
  return null;
29
29
  return {
30
30
  source: cited.source,
31
- type: citedTypeAt(context, unwrapErased(node)),
31
+ type: citedValueTypeAt(context, unwrapErasedExpression(node)),
32
32
  ...(assertsType(node, context.checker) ? { asserted: true } : {})
33
33
  };
34
34
  };
35
- /**
36
- * The type a citation of `node`'s published value carries: the checker's view
37
- * of the node, except for a logical merge, whose result `computations.ts`
38
- * publishes under `logicalMergeTypeOf` -- and a citation must name the value
39
- * that result actually holds, not a second checker query at the same node.
40
- */
41
- const citedTypeAt = (context, node) => {
42
- if (ts.isBinaryExpression(node)) {
43
- const operator = node.operatorToken.kind;
44
- if (operator === ts.SyntaxKind.QuestionQuestionToken ||
45
- operator === ts.SyntaxKind.BarBarToken ||
46
- operator === ts.SyntaxKind.AmpersandAmpersandToken) {
47
- const merged = logicalMergeTypeOf(context, ts.tokenToString(operator) ?? '', node, context.types.typeAt(node.left), context.types.typeAt(node.right));
48
- if (merged !== null)
49
- return merged;
50
- }
51
- }
52
- return context.types.typeAt(node);
53
- };
54
35
  /**
55
36
  * Catch clauses: the one candidate family `'boundary'` receives from the
56
37
  * census (`census.ts` assigns every other boundary concept -- the exception
@@ -0,0 +1,19 @@
1
+ import ts from 'typescript';
2
+ import type { StructuralTypeId } from '../../../identity/ids.js';
3
+ import type { ProducerContext } from '../producer-context.js';
4
+ /**
5
+ * The type an operand citing `node`'s published value carries: the checker's
6
+ * view of the node, except where a producer publishes that value under a type
7
+ * of its own, which a second checker query at the same node cannot see.
8
+ *
9
+ * - A logical merge, whose result `computations.ts` publishes under
10
+ * `logicalMergeTypeOf`.
11
+ * - An `Object.create(null)` call, which publishes the carrier
12
+ * `objectCreateResultOverride` mints rather than the ambient `any`.
13
+ *
14
+ * A citation that re-asked the checker boxed the value at the citation: hono's
15
+ * trie-router `Node` does `this.#children = children || Object.create(null)`;
16
+ * the merge cited the call as `any` and the field write cited the merge as
17
+ * `any`, so the optional parameter was boxed and unboxed into the field.
18
+ */
19
+ export declare const citedValueTypeAt: (context: ProducerContext, node: ts.Expression) => StructuralTypeId;
@@ -0,0 +1,38 @@
1
+ import ts from 'typescript';
2
+ import { unwrapErased } from './erasure.js';
3
+ import { objectCreateResultOverride } from './invocations.js';
4
+ import { logicalMergeTypeOf } from './logical-merge-type.js';
5
+ /**
6
+ * The type an operand citing `node`'s published value carries: the checker's
7
+ * view of the node, except where a producer publishes that value under a type
8
+ * of its own, which a second checker query at the same node cannot see.
9
+ *
10
+ * - A logical merge, whose result `computations.ts` publishes under
11
+ * `logicalMergeTypeOf`.
12
+ * - An `Object.create(null)` call, which publishes the carrier
13
+ * `objectCreateResultOverride` mints rather than the ambient `any`.
14
+ *
15
+ * A citation that re-asked the checker boxed the value at the citation: hono's
16
+ * trie-router `Node` does `this.#children = children || Object.create(null)`;
17
+ * the merge cited the call as `any` and the field write cited the merge as
18
+ * `any`, so the optional parameter was boxed and unboxed into the field.
19
+ */
20
+ export const citedValueTypeAt = (context, node) => {
21
+ const unwrapped = unwrapErased(node);
22
+ if (ts.isCallExpression(unwrapped)) {
23
+ const created = objectCreateResultOverride(context, unwrapped, unwrapErased(unwrapped.expression));
24
+ if (created !== null)
25
+ return created;
26
+ }
27
+ if (ts.isBinaryExpression(unwrapped)) {
28
+ const operator = unwrapped.operatorToken.kind;
29
+ if (operator === ts.SyntaxKind.QuestionQuestionToken ||
30
+ operator === ts.SyntaxKind.BarBarToken ||
31
+ operator === ts.SyntaxKind.AmpersandAmpersandToken) {
32
+ const merged = logicalMergeTypeOf(context, ts.tokenToString(operator) ?? '', unwrapped, citedValueTypeAt(context, unwrapped.left), citedValueTypeAt(context, unwrapped.right));
33
+ if (merged !== null)
34
+ return merged;
35
+ }
36
+ }
37
+ return context.types.typeAt(node);
38
+ };
@@ -7,7 +7,7 @@ import { blocked, mintOperationId, mintResult, operand } from './mint.js';
7
7
  import { isAssignmentOperatorKind, logicalAssignmentOperators, sourceForValue, symbolMemberKeyOf, unwrapErased, valueEdgesInto } from './shared.js';
8
8
  import { normalCompletion, pureEffects, throwingCompletion } from '../../model/operands.js';
9
9
  import { propertyExpressionValueTypeAt } from './properties.js';
10
- import { objectCreateResultOverride } from './invocations.js';
10
+ import { citedValueTypeAt } from './cited-value-type.js';
11
11
  import { ordinaryObjectDataWriteIsAbsent } from '../callable-data-write.js';
12
12
  const tokenText = (kind) => ts.tokenToString(kind) ?? ts.SyntaxKind[kind];
13
13
  /**
@@ -129,7 +129,33 @@ const finishComputation = (context, candidate, node, form, operatorText, operand
129
129
  const second = branches[1];
130
130
  if (!first || !second)
131
131
  throw new Error('a conditional computation must carry consequent and alternate operands');
132
- return first.type === second.type ? first.type : context.table.intern({ kind: 'union', members: [first.type, second.type] });
132
+ if (first.type === second.type)
133
+ return first.type;
134
+ // An element-less array arm (`never[]`, or the zero-length tuple) beside
135
+ // an array arm is already a value of that array: 13.2.4.2 gives it
136
+ // length 0, and with no element it disagrees with no element type. The
137
+ // checker subtype-reduces `cond ? xs.map(f) : []` to the populated arm
138
+ // for the same reason, and `structural.ts` drops the identical arm from
139
+ // a checker union. Kept as a second arm, the merge was a tagged union of
140
+ // two arrays the binding had to select from (hono's RegExpRouter
141
+ // `ownRoute`), where `mergeIncoming` builds the empty literal directly
142
+ // in the populated arm's carrier.
143
+ const shapeOf = (id) => (context.table.isOpen(id) ? undefined : context.table.get(id).shape);
144
+ const elementless = (id) => {
145
+ const shape = shapeOf(id);
146
+ if (shape?.kind === 'tuple')
147
+ return shape.elements.length === 0;
148
+ if (shape?.kind !== 'array')
149
+ return false;
150
+ const element = shapeOf(shape.element);
151
+ return element?.kind === 'primitive' && element.primitive === 'never';
152
+ };
153
+ const populatedArray = (id) => shapeOf(id)?.kind === 'array' && !elementless(id);
154
+ if (elementless(second.type) && populatedArray(first.type))
155
+ return first.type;
156
+ if (elementless(first.type) && populatedArray(second.type))
157
+ return second.type;
158
+ return context.table.intern({ kind: 'union', members: [first.type, second.type] });
133
159
  }
134
160
  if (form === 'binary' &&
135
161
  ts.isBinaryExpression(node) &&
@@ -209,8 +235,8 @@ const contributeLogical = (context, candidate, node, kind) => {
209
235
  };
210
236
  }
211
237
  const takenWhen = kind === ts.SyntaxKind.AmpersandAmpersandToken ? 'truthy' : kind === ts.SyntaxKind.BarBarToken ? 'falsy' : 'nullish';
212
- const left = operand('left', 0, leftSource, context.types.typeAt(node.left));
213
- const right = operand('right', 0, sourceForValue(context, node.right), context.types.typeAt(node.right), {
238
+ const left = operand('left', 0, leftSource, citedValueTypeAt(context, node.left));
239
+ const right = operand('right', 0, sourceForValue(context, node.right), citedValueTypeAt(context, node.right), {
214
240
  kind: 'conditional',
215
241
  guard: leftSource.result,
216
242
  takenWhen
@@ -317,7 +343,7 @@ const contributeConditional = (context, candidate, node) => {
317
343
  const condition = operand('condition', 0, conditionSource, context.types.typeAt(node.condition));
318
344
  const branchValueTypeAt = (branch) => ts.isPropertyAccessExpression(branch) || ts.isElementAccessExpression(branch)
319
345
  ? propertyExpressionValueTypeAt(context, branch)
320
- : context.types.typeAt(branch);
346
+ : citedValueTypeAt(context, branch);
321
347
  const consequent = operand('consequent', 0, sourceForValue(context, node.whenTrue), branchValueTypeAt(node.whenTrue), {
322
348
  kind: 'conditional',
323
349
  guard: conditionSource.result,
@@ -479,9 +505,6 @@ const contributeBinary = (context, candidate, node) => {
479
505
  // it (a name's GetValue, a property's [[Get]]), and this cites it, so the
480
506
  // value combined is the same one any other consumer of that target sees.
481
507
  const assignedObjectTarget = compound === null ? objectAssignTargetType(context.checker, node.right) : null;
482
- const createdObjectTarget = compound === null && assignedObjectTarget === null && ts.isCallExpression(node.right)
483
- ? objectCreateResultOverride(context, node.right, unwrapErased(node.right.expression))
484
- : null;
485
508
  const operands = compound
486
509
  ? [
487
510
  operand('left', 0, sourceForValue(context, node.left), context.types.typeAt(node.left)),
@@ -492,9 +515,7 @@ const contributeBinary = (context, candidate, node) => {
492
515
  // PutValue. This operation carries the value; the write is published
493
516
  // below, or by the property family when the target is a property.
494
517
  [
495
- operand('value', 0, sourceForValue(context, node.right), assignedObjectTarget !== null
496
- ? context.types.typeOf(assignedObjectTarget)
497
- : (createdObjectTarget ?? context.types.typeAt(node.right)))
518
+ operand('value', 0, sourceForValue(context, node.right), assignedObjectTarget !== null ? context.types.typeOf(assignedObjectTarget) : citedValueTypeAt(context, node.right))
498
519
  ];
499
520
  const computed = finishComputation(context, candidate, node, compound ? 'binary' : 'assignment', compound ?? tokenText(kind), operands, throwingCompletion, { readsMutableState: compound !== null, writesMutableState: true, allocates: false, callsUserCode: true });
500
521
  if (computed.kind !== 'operations')
@@ -954,9 +954,19 @@ export const objectCreateResultOverride = (context, node, calleeUnwrapped) => {
954
954
  }
955
955
  if (node.arguments.length !== 1 || node.arguments[0]?.kind !== ts.SyntaxKind.NullKeyword)
956
956
  return null;
957
+ // The first allocation of a closed table component is laid out at the
958
+ // component's common entry storage (`fresh-dictionary-storage.ts`).
959
+ const storage = context.types.indexedStorageTypeAt(node);
960
+ if (storage !== null)
961
+ return storage;
957
962
  const assertion = enclosingTypeAssertion(node);
958
963
  if (assertion)
959
964
  return context.types.typeAt(assertion);
965
+ // Part of a stated-`any` binding's one object, laid out at the type its
966
+ // consumer wants rather than the annotation's open positions.
967
+ const consumerLayout = context.types.statedAnyBindingLayoutAt(node);
968
+ if (consumerLayout !== null)
969
+ return consumerLayout;
960
970
  // Contextual typing reaches destinations an immediate parent check cannot:
961
971
  // an object-literal field, an argument slot, and an indexed assignment are
962
972
  // all real declarations of the carrier this fresh null-prototype object
@@ -157,6 +157,13 @@ const isScopeBoundary = (node) => isReturnCandidateKind(node) ||
157
157
  ts.isClassStaticBlockDeclaration(node);
158
158
  /** Duplicated from `parameter-bindings.ts` (not exported there): `any` is the absence this module exists to fill. */
159
159
  const isAnyType = (type) => (type.flags & ts.TypeFlags.Any) !== 0;
160
+ /** The class a type is an instance of, or `null` for anything that is not one class's instance type. */
161
+ const classDeclarationOf = (type) => {
162
+ if (type.isUnionOrIntersection())
163
+ return null;
164
+ const declarations = type.getSymbol()?.getDeclarations()?.filter(ts.isClassLike) ?? [];
165
+ return declarations.length === 1 ? declarations[0] : null;
166
+ };
160
167
  /**
161
168
  * A refusal's `owner`, rendered -- the declaration's own name where the
162
169
  * declaration syntax carries one (a function/method/getter's own name, or the
@@ -1035,11 +1042,50 @@ moduleRecords = emptyCommonJsModuleRecordCensus) => {
1035
1042
  * `x as any` therefore still refuses -- the cast said `any`, and honouring
1036
1043
  * a statement is not the same as improving on it.
1037
1044
  */
1045
+ /**
1046
+ * `return this as any` from an unannotated function expression written
1047
+ * into a slot whose every signature returns a type the operand already is:
1048
+ * the assertion changes only the checker's view, so the function returns
1049
+ * the operand's own type, exactly as `physicalAssertionReturns` reads an
1050
+ * `as unknown as T` past its assertion. Hono's constructor installs
1051
+ * `this[method] = (...) => { ...; return this as any }` under overloaded
1052
+ * `HandlerInterface`s that all return the app; laid out as `any`, each
1053
+ * return boxed the app and published its whole router to dynamic code.
1054
+ */
1055
+ const anyAssertionReturnOf = (assertion, owner) => {
1056
+ if (assertion.type.kind !== ts.SyntaxKind.AnyKeyword)
1057
+ return null;
1058
+ if (!ts.isArrowFunction(owner) && !ts.isFunctionExpression(owner))
1059
+ return null;
1060
+ const contextual = checker.getContextualType(owner);
1061
+ const signatures = contextual ? checker.getNonNullableType(contextual).getCallSignatures() : [];
1062
+ if (signatures.length === 0)
1063
+ return null;
1064
+ const operand = knownOrResolve(assertion.expression, owner);
1065
+ if (operand === null || isAnyType(operand))
1066
+ return null;
1067
+ if (signatures.every((signature) => checker.isTypeAssignableTo(operand, checker.getReturnTypeOfSignature(signature))))
1068
+ return operand;
1069
+ // The slot's signatures may name the operand's own class at other type
1070
+ // arguments -- hono's return `HonoBase<E, S & ToSchema<...>, BasePath>`
1071
+ // while `this` is `HonoBase<E, S, BasePath>`, which is why the source
1072
+ // needed the assertion at all. The value is still that one instance of
1073
+ // that one class; the type arguments are the checker's bookkeeping.
1074
+ const instance = checker.getApparentType(operand);
1075
+ const declaration = classDeclarationOf(instance);
1076
+ return declaration !== null &&
1077
+ signatures.every((signature) => classDeclarationOf(checker.getApparentType(checker.getReturnTypeOfSignature(signature))) === declaration)
1078
+ ? instance
1079
+ : null;
1080
+ };
1038
1081
  const knownOrResolve = (node, owner) => {
1039
1082
  const unwrapped = unwrapParens(node);
1040
1083
  if (ts.isAsExpression(unwrapped) || ts.isTypeAssertionExpression(unwrapped)) {
1041
1084
  const physical = physicalAssertionReturns.has(owner) ? sourcePastUnknownAssertion(checker, unwrapped) : null;
1042
- return physical ? knownOrResolve(physical, owner) : known(unwrapped);
1085
+ if (physical)
1086
+ return knownOrResolve(physical, owner);
1087
+ const erased = anyAssertionReturnOf(unwrapped, owner);
1088
+ return erased ?? known(unwrapped);
1043
1089
  }
1044
1090
  // A CELL A CENSUS NARROWED WITHIN ITS OWN STATEMENT OUTRANKS THE CHECKER
1045
1091
  // here, for the reason `field-bindings.ts` states at the identical hop:
@@ -0,0 +1,34 @@
1
+ import ts from 'typescript';
2
+ import type { StructuralTypeId } from '../../identity/ids.js';
3
+ import type { ValueFlowIndex } from './flow/model.js';
4
+ import type { IdentityTable, SpecializationPath } from './identities.js';
5
+ import type { SpecializationCensus } from './specialization.js';
6
+ /**
7
+ * A `const` whose stated type leaves positions open (`Matcher<any>`) and whose
8
+ * every use hands it, whole, to one concrete slot is laid out as that slot.
9
+ *
10
+ * Hono's RegExpRouter states `const nullMatcher: Matcher<any> = [/^$/, [],
11
+ * Object.create(null)]` and only ever `return`s it from
12
+ * `buildMatcherFromPreprocessedRoutes<T>(): Matcher<T>`. Laid out as written,
13
+ * the binding is a record of arrays of `[any, ParamIndexMap]` tuples that the
14
+ * return must turn into arrays of `[T, ParamIndexMap]` tuples -- a mutable
15
+ * container of mutable records at another layout, which has no view (a tuple
16
+ * written through it would have to be copied into the other layout) and which
17
+ * no copy may stand in for (the binding is one object, returned every time).
18
+ * The `any` is never used as `any`: the program states it and never reads it
19
+ * dynamically, so the binding takes its one consumer's layout and the return
20
+ * is the identity.
21
+ *
22
+ * Fail-closed: any use other than a `return` of the whole binding from a
23
+ * function with a stated, non-async, non-generator return, or consumers that
24
+ * resolve to more than one layout across every specialization copy of their
25
+ * functions, leaves the binding at its stated layout.
26
+ */
27
+ export interface AnyBindingConsumerInputs {
28
+ readonly checker: ts.TypeChecker;
29
+ readonly identities: IdentityTable;
30
+ readonly specializations: SpecializationCensus;
31
+ readonly flow: ValueFlowIndex | undefined;
32
+ readonly layoutAt: (path: SpecializationPath, type: ts.Type) => StructuralTypeId;
33
+ }
34
+ export declare const createAnyBindingConsumerLayout: (inputs: AnyBindingConsumerInputs) => (node: ts.Node) => StructuralTypeId | null;