@geastack/compiler 1.0.43 → 1.0.45

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 (35) hide show
  1. package/dist/cli.js +8 -2
  2. package/dist/ir/callable-class-flow.js +87 -29
  3. package/dist/ir/construction-only-fields.d.ts +1 -1
  4. package/dist/ir/construction-only-fields.js +3 -1
  5. package/dist/ir/lower-operands.js +6 -1
  6. package/dist/ir/native-callable-data-owner.js +13 -1
  7. package/dist/ir/native-callable-data-write.d.ts +0 -4
  8. package/dist/ir/native-callable-data-write.js +9 -0
  9. package/dist/ir/shake.js +21 -0
  10. package/dist/semantics/frontend.js +18 -14
  11. package/dist/semantics/normalize/field-bindings.d.ts +2 -0
  12. package/dist/semantics/normalize/field-bindings.js +669 -13
  13. package/dist/semantics/normalize/flow/component-solver.js +37 -2
  14. package/dist/semantics/normalize/flow/source-value-session.d.ts +3 -0
  15. package/dist/semantics/normalize/flow/source-value-session.js +343 -138
  16. package/dist/semantics/normalize/global-host-mutations.js +14 -6
  17. package/dist/semantics/normalize/implicit-arguments-tuple.d.ts +11 -10
  18. package/dist/semantics/normalize/implicit-arguments-tuple.js +15 -3
  19. package/dist/semantics/normalize/parameter-bindings.js +18 -0
  20. package/dist/semantics/normalize/producers/object-assignment.js +7 -1
  21. package/dist/semantics/normalize/stated-dynamic-value.d.ts +11 -0
  22. package/dist/semantics/normalize/stated-dynamic-value.js +36 -0
  23. package/dist/semantics/normalize/structural-mutable-method.js +88 -2
  24. package/dist/targets/cpp/borrowed-call-entry.d.ts +41 -2
  25. package/dist/targets/cpp/borrowed-call-entry.js +91 -6
  26. package/dist/targets/cpp/emit-callable.js +62 -29
  27. package/dist/targets/cpp/emit.js +106 -10
  28. package/dist/targets/cpp/host/emit-host-object.js +69 -2
  29. package/dist/targets/cpp/records.d.ts +1 -0
  30. package/dist/targets/cpp/records.js +1 -1
  31. package/dist/targets/cpp/translation-unit.js +59 -22
  32. package/dist/targets/cpp/virtual-methods.js +9 -4
  33. package/package.json +1 -1
  34. package/src/targets/cpp/runtime/gea_dynamic_proxy.h +121 -0
  35. package/src/targets/cpp/runtime/gea_runtime.h +218 -28
@@ -1009,6 +1009,15 @@ staticCommonJsRequireOutcomeOf = () => null, trustSeed = initialCensusSeed) => {
1009
1009
  */
1010
1010
  const isDefinitelyProgramSymbolElementKey = (expression) => ts.isElementAccessExpression(expression) && isProgramSymbolKeyExpression(expression.argumentExpression);
1011
1011
  const overwrittenIntrinsicSymbols = new Set();
1012
+ // Every declaration of an overwritten symbol, so `intrinsicSymbolIsOverwritten`
1013
+ // asks of a symbol's own declarations rather than scanning every assignment
1014
+ // target of the program on each question.
1015
+ const overwrittenDeclarations = new Set();
1016
+ const overwriteIntrinsicSymbol = (symbol) => {
1017
+ overwrittenIntrinsicSymbols.add(symbol);
1018
+ for (const declaration of symbol.declarations ?? [])
1019
+ overwrittenDeclarations.add(declaration);
1020
+ };
1012
1021
  const propertyKeyDomains = createPropertyKeyDomains(checker, flow, flowSiteIsReachable, publishedTypeAt);
1013
1022
  // A computed key set, with Object.prototype's possible enumerable keys
1014
1023
  // added when it leans on them; its assumptions are checked at the end.
@@ -1136,8 +1145,7 @@ staticCommonJsRequireOutcomeOf = () => null, trustSeed = initialCensusSeed) => {
1136
1145
  return true;
1137
1146
  if ([...computedIntrinsicKeys].some((domain) => propertyKeyDomains.mayName(domain, symbol.name)))
1138
1147
  return true;
1139
- const declarations = new Set(symbol.declarations ?? []);
1140
- const overwritten = [...overwrittenIntrinsicSymbols].some((candidate) => (candidate.declarations ?? []).some((declaration) => declarations.has(declaration)));
1148
+ const overwritten = (symbol.declarations ?? []).some((declaration) => overwrittenDeclarations.has(declaration));
1141
1149
  if (!overwritten)
1142
1150
  trustedIntrinsicNames.add(symbol.name);
1143
1151
  return overwritten;
@@ -1376,13 +1384,13 @@ staticCommonJsRequireOutcomeOf = () => null, trustSeed = initialCensusSeed) => {
1376
1384
  }
1377
1385
  const symbol = actualSymbol(checker.getPropertyOfType(checker.getTypeAtLocation(target), key));
1378
1386
  if (symbol)
1379
- overwrittenIntrinsicSymbols.add(symbol);
1387
+ overwriteIntrinsicSymbol(symbol);
1380
1388
  };
1381
1389
  for (const node of nodes) {
1382
1390
  if (ts.isIdentifier(node) && isDirectAssignmentTarget(node)) {
1383
1391
  const symbol = actualSymbol(checker.getSymbolAtLocation(node));
1384
1392
  if (symbol)
1385
- overwrittenIntrinsicSymbols.add(symbol);
1393
+ overwriteIntrinsicSymbol(symbol);
1386
1394
  continue;
1387
1395
  }
1388
1396
  if ((ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) && isDirectAssignmentTarget(node)) {
@@ -1412,7 +1420,7 @@ staticCommonJsRequireOutcomeOf = () => null, trustSeed = initialCensusSeed) => {
1412
1420
  intrinsicSurfaceMemberReplaced = true;
1413
1421
  const symbol = memberSymbolOf(node);
1414
1422
  if (symbol)
1415
- overwrittenIntrinsicSymbols.add(symbol);
1423
+ overwriteIntrinsicSymbol(symbol);
1416
1424
  else if (staticKeyOf(node) === null &&
1417
1425
  !isDefinitelyNumericElementKey(node) &&
1418
1426
  !isDefinitelyProgramSymbolElementKey(node) &&
@@ -1424,7 +1432,7 @@ staticCommonJsRequireOutcomeOf = () => null, trustSeed = initialCensusSeed) => {
1424
1432
  continue;
1425
1433
  const member = actualSymbol(checker.getPropertyOfType(checker.getTypeAtLocation(node.expression), key.name));
1426
1434
  if (member)
1427
- overwrittenIntrinsicSymbols.add(member);
1435
+ overwriteIntrinsicSymbol(member);
1428
1436
  }
1429
1437
  continue;
1430
1438
  }
@@ -11,17 +11,18 @@ import { type ImplicitArgumentsSlot } from './implicit-arguments.js';
11
11
  *
12
12
  * - `tuple`: every read names a FIXED position -- a literal index, or a final
13
13
  * `...arguments` spread into a callee convention with no rest formal, which
14
- * reads positions `0..n-1` exactly. Each position is then its own fact,
15
- * joined over the closed callers that fill it. This is the shape WebGL
16
- * forwarding shims need: `texImage3D()` is called with numbers in its
17
- * leading positions and `ArrayBufferView | null` in its last, and one element
18
- * type over all ten positions could only be a union no caller wrote.
19
- * Positions from `required` on are ones some closed caller omits, so they
20
- * are optional: a read there is `T | undefined`, and the rest slot leaves
21
- * the field absent rather than inventing a value.
14
+ * reads positions `0..n-1` exactly -- or reads the frame's `length`. Each
15
+ * position is then its own fact, joined over the closed callers that fill
16
+ * it. This is the shape WebGL forwarding shims need: `texImage3D()` is
17
+ * called with numbers in its leading positions and `ArrayBufferView | null`
18
+ * in its last, and one element type over all ten positions could only be a
19
+ * union no caller wrote. Positions from `required` on are ones some closed
20
+ * caller omits, so they are optional: a read there is `T | undefined`, the
21
+ * rest slot leaves the field absent rather than inventing a value, and the
22
+ * frame's length counts the fields present.
22
23
  * - `array`: the body reads a position only known at run time
23
- * (`arguments[i]`, `arguments.length`), reads its own element back through
24
- * a recursive call, or declares parameters in front of the phantom slot.
24
+ * (`arguments[i]`), reads its own element back through a recursive call,
25
+ * or declares parameters in front of the phantom slot.
25
26
  * The frame is then a runtime-sized Array of one element type joined over
26
27
  * every supplied position -- the frame this fact published before positions
27
28
  * existed.
@@ -64,8 +64,12 @@ const useOf = (checker, use) => {
64
64
  const access = use.parent;
65
65
  if (ts.isElementAccessExpression(access) && access.expression === use)
66
66
  return { read: fixedPositionOf(checker, access) === null ? 'indexed' : 'fixed', access };
67
+ // The count of arguments a call passed is the tuple's own length: the
68
+ // positions from `required` on are optional elements, present exactly when
69
+ // the caller wrote them (an explicit `undefined` included), so a body that
70
+ // picks a call form by `arguments.length` keeps its positional frame.
67
71
  if (ts.isPropertyAccessExpression(access) && access.expression === use && access.name.text === 'length')
68
- return { read: 'indexed', access };
72
+ return { read: 'length', access };
69
73
  if (ts.isSpreadElement(access) && access.expression === use) {
70
74
  const call = access.parent;
71
75
  if ((ts.isCallExpression(call) || ts.isNewExpression(call)) && call.arguments) {
@@ -86,6 +90,7 @@ const useOf = (checker, use) => {
86
90
  export const inferImplicitArgumentsTuple = (evidence) => {
87
91
  const { checker, owner, slot, uses } = evidence;
88
92
  let indexed = slot.ordinal > 0;
93
+ let readsLength = false;
89
94
  for (const use of uses) {
90
95
  // A lexical arguments capture needs a frame identity shared with its
91
96
  // outer function; a local ordinal alone cannot establish that identity.
@@ -98,6 +103,8 @@ export const inferImplicitArgumentsTuple = (evidence) => {
98
103
  return { refused: 'implicit-arguments-object-escapes' };
99
104
  if (reading.read === 'indexed')
100
105
  indexed = true;
106
+ if (reading.read === 'length')
107
+ readsLength = true;
101
108
  // The shared write inventory already includes parenthesized targets,
102
109
  // destructuring, updates, loops and deletes. Do not invent a second
103
110
  // assignment classifier for this one binding.
@@ -146,10 +153,15 @@ export const inferImplicitArgumentsTuple = (evidence) => {
146
153
  for (const [position, written] of Array.from(positions, (entry) => entry ?? []).entries()) {
147
154
  const element = written.length > 0 ? (joinOfWrites(checker, written) ?? disjointUnionTypeOf(checker, written)) : null;
148
155
  if (!element)
149
- return { refused: 'implicit-arguments-disjoint-position' };
156
+ break;
150
157
  elements[position] = element;
151
158
  }
152
- return { tuple: { frame: 'tuple', elements, required: Math.min(required, elements.length), sourcePositions } };
159
+ if (elements.length === positions.length)
160
+ return { tuple: { frame: 'tuple', elements, required: Math.min(required, elements.length), sourcePositions } };
161
+ // A length read was an Array frame's before it was a tuple's; a position
162
+ // with no join keeps that frame rather than refusing the owner.
163
+ if (!readsLength)
164
+ return { refused: 'implicit-arguments-disjoint-position' };
153
165
  }
154
166
  // An annotation can supply a common upper bound absent from the
155
167
  // observed subclasses. It is only a candidate: every supplied position,
@@ -16,6 +16,7 @@ import { callbackContractParameterType, inlineJsxCallbackParameterType, callback
16
16
  import { declaredClosedTupleRestElementsOf, impliedPatternElementOfArms, impliedPatternPositionPresentEverywhere } from './parameter-slot.js';
17
17
  import { iteratorYieldTypesOf } from './producers/iteration-yield.js';
18
18
  import { annotationStatesNothing, exactEmptyObjectLiteralType, isNullishType, containsUnstatedPosition, derivedExpressionType, indexAliasEvidence, indexedTypeOf, explicitThisCallReturnType, overloadInvariantReturnTypeAt, arrayFromCopyTypeAt, indexNamedCallables, isStandardInterfaceType, isBindingOnlyReference, isCalleeOf, isTrackedCallable, isUnusableEvidence as statesNoStorage, carriesNoEvidence, disjointUnionMembersOf, disjointUnionTypeOf, joinOfWrites, jsDocTypeStatesNothing, literalMemberNameOf, narrowsOnlyUnstatedPositions, isStructuralConstructorType, narrowsStructuralConstructorToClasses, narrowsArrayBufferViewToViews, statesAnArrayBufferView, isLibArrayBufferViewType, withoutUndefinedMember, memberTypeOf, objectAssignTargetType, nameOfCallable, synthesizedUnionArmsAt, readsWholeSynthesizedCell, widestOf, impliedPatternElementRootOf, impliedPatternParameterOf } from './derived-expression-type.js';
19
+ import { readsStatedDynamicValue } from './stated-dynamic-value.js';
19
20
  import { isUnreducedTypeForm } from './unreduced-type-form.js';
20
21
  import { noHostProvidedNames, valueSymbolAt } from './unresolvable-names.js';
21
22
  import { isHomelessRecordArm, recordArmUnionStatementOf, recordHomeArmsAtRead } from './record-home-arms.js';
@@ -1573,6 +1574,10 @@ hostProvided = noHostProvidedNames) => {
1573
1574
  return cached;
1574
1575
  if (resolving.has(node))
1575
1576
  return null;
1577
+ if (readsStatedDynamicValue(upstream.statedTypeAt, node)) {
1578
+ memo.set(node, null);
1579
+ return null;
1580
+ }
1576
1581
  resolving.add(node);
1577
1582
  const answer = compute(node);
1578
1583
  resolving.delete(node);
@@ -1603,6 +1608,11 @@ hostProvided = noHostProvidedNames) => {
1603
1608
  const argument = implicitArgumentsReadTypeAt(checker, node, (owner) => upstream.implicitArgumentsTupleAt?.(owner) ?? null);
1604
1609
  if (argument)
1605
1610
  return argument;
1611
+ // A read of a field the prior round widened to `any` (and of anything
1612
+ // read off it) is typed by the checker from the field's narrow inference;
1613
+ // it carries whatever the field holds, exactly as an `any` read does.
1614
+ if (readsStatedDynamicValue(upstream.statedTypeAt, node))
1615
+ return null;
1606
1616
  const type = (node.kind === ts.SyntaxKind.ThisKeyword ? concreteThisTypeOf(node) : null) ??
1607
1617
  objectAssignTargetType(checker, node) ??
1608
1618
  checker.getTypeAtLocation(node);
@@ -2384,6 +2394,14 @@ hostProvided = noHostProvidedNames) => {
2384
2394
  record(argument);
2385
2395
  continue;
2386
2396
  }
2397
+ // A read of a field the prior round widened supplies whatever the
2398
+ // field holds, although the checker still types it from the field's
2399
+ // narrow inference.
2400
+ if (skipSilentSites && !resolved && readsStatedDynamicValue(upstream.statedTypeAt, argument)) {
2401
+ passed.push(checker.getAnyType());
2402
+ record(argument);
2403
+ continue;
2404
+ }
2387
2405
  if (skipSilentSites && !resolved && isSuppliedDynamic(argument)) {
2388
2406
  passed.push(supplied);
2389
2407
  record(argument);
@@ -98,7 +98,13 @@ export const contributeObjectAssignmentElement = (context, candidate, node) => {
98
98
  const rawMember = memberTypeOf(context.checker, rawSource, key, node) ?? context.checker.getIndexTypeOfType(rawSource, ts.IndexKind.String);
99
99
  // The extracted property's type belongs to the source, not to the target
100
100
  // slot. A real conversion between those two is audited at the store.
101
- const extractedType = context.types.typeOf(rawMember ?? ((rawSource.flags & ts.TypeFlags.Any) !== 0 ? rawSource : context.checker.getUndefinedType()));
101
+ // A member the source DECLARES but the checker types `any` -- a JavaScript
102
+ // field assigned from an unannotated parameter -- is unusable evidence to
103
+ // `memberTypeOf`, never an absent one: reading it as `undefined` made the
104
+ // store's value a dead `unreachableValue` that threw on the first run.
105
+ // It reads as the dynamic value it is, and the store converts it.
106
+ const declared = (rawSource.flags & ts.TypeFlags.Any) !== 0 || context.checker.getPropertyOfType(rawSource, key) !== undefined;
107
+ const extractedType = context.types.typeOf(rawMember ?? (declared ? context.checker.getAnyType() : context.checker.getUndefinedType()));
102
108
  const sourceResult = semanticResultId(operationId(context.identities.nodeIdOf(pattern), 'destructuring', 0), 'value');
103
109
  const getId = mintOperationId(context.ordinals, candidate.id, 'destructuring');
104
110
  const get = {
@@ -0,0 +1,11 @@
1
+ import ts from '#typescript';
2
+ /**
3
+ * Whether `node` evaluates to a value a census STATED dynamic although the
4
+ * checker types it -- a read of a field widened by `widenDynamicallyWrittenFields`,
5
+ * a cell holding one, or a member read or method result off one. The checker
6
+ * still answers such a node from the field's narrow inference, so every
7
+ * consumer that asks the checker first must ask this beside it, or it lays out
8
+ * a typed slot for the boxed value and converts it through the same checked
9
+ * unbox the widening removed from the field.
10
+ */
11
+ export declare const readsStatedDynamicValue: (statedTypeAt: (node: ts.Node) => ts.Type | null, node: ts.Node, depth?: number) => boolean;
@@ -0,0 +1,36 @@
1
+ import ts from '#typescript';
2
+ /**
3
+ * Whether `node` evaluates to a value a census STATED dynamic although the
4
+ * checker types it -- a read of a field widened by `widenDynamicallyWrittenFields`,
5
+ * a cell holding one, or a member read or method result off one. The checker
6
+ * still answers such a node from the field's narrow inference, so every
7
+ * consumer that asks the checker first must ask this beside it, or it lays out
8
+ * a typed slot for the boxed value and converts it through the same checked
9
+ * unbox the widening removed from the field.
10
+ */
11
+ export const readsStatedDynamicValue = (statedTypeAt, node, depth = 0) => {
12
+ if (depth > 16)
13
+ return false;
14
+ const stated = statedTypeAt(node);
15
+ if (stated)
16
+ return (stated.flags & ts.TypeFlags.Any) !== 0;
17
+ if (ts.isParenthesizedExpression(node) || ts.isNonNullExpression(node))
18
+ return readsStatedDynamicValue(statedTypeAt, node.expression, depth + 1);
19
+ if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node))
20
+ return readsStatedDynamicValue(statedTypeAt, node.expression, depth + 1);
21
+ if (ts.isCallExpression(node))
22
+ return ((ts.isPropertyAccessExpression(node.expression) || ts.isElementAccessExpression(node.expression)) &&
23
+ readsStatedDynamicValue(statedTypeAt, node.expression.expression, depth + 1));
24
+ if (ts.isConditionalExpression(node))
25
+ return (readsStatedDynamicValue(statedTypeAt, node.whenTrue, depth + 1) || readsStatedDynamicValue(statedTypeAt, node.whenFalse, depth + 1));
26
+ if (ts.isBinaryExpression(node)) {
27
+ const operator = node.operatorToken.kind;
28
+ if (operator === ts.SyntaxKind.QuestionQuestionToken ||
29
+ operator === ts.SyntaxKind.BarBarToken ||
30
+ operator === ts.SyntaxKind.AmpersandAmpersandToken ||
31
+ // `+` over a dynamic operand is a string or a number, decided at run time.
32
+ operator === ts.SyntaxKind.PlusToken)
33
+ return readsStatedDynamicValue(statedTypeAt, node.left, depth + 1) || readsStatedDynamicValue(statedTypeAt, node.right, depth + 1);
34
+ }
35
+ return false;
36
+ };
@@ -9,6 +9,70 @@ import { structuralCallSignatures } from './structural-callable.js';
9
9
  export const createMutableMethodResolver = (checker, table, flow, signatureOf, read, receiverTypeAt) => {
10
10
  const cache = new Map();
11
11
  const pending = new Set();
12
+ const keyOf = (node) => ts.isPropertyAccessExpression(node)
13
+ ? node.name.text
14
+ : ts.isStringLiteralLike(node.argumentExpression) || ts.isNumericLiteral(node.argumentExpression)
15
+ ? node.argumentExpression.text
16
+ : null;
17
+ const memberSymbolOf = (node, key) => checker.getSymbolAtLocation(ts.isPropertyAccessExpression(node) ? node.name : node) ??
18
+ checker.getPropertyOfType(checker.getApparentType(receiverTypeAt(node.expression)), key);
19
+ // Keys some write stores through a receiver the checker cannot resolve to a
20
+ // member (`(m as any).hook = ...`): the write lands in the method's own slot
21
+ // at run time while naming no symbol, so `writesToSymbol` never sees it.
22
+ let untypedWrites;
23
+ const untypedWriteKeys = () => {
24
+ if (untypedWrites)
25
+ return untypedWrites;
26
+ const keys = new Set();
27
+ for (const access of flow?.propertyAccesses ?? []) {
28
+ const parent = access.parent;
29
+ if (!ts.isBinaryExpression(parent) || parent.left !== access || parent.operatorToken.kind !== ts.SyntaxKind.EqualsToken)
30
+ continue;
31
+ const key = keyOf(access);
32
+ if (key !== null && checker.getSymbolAtLocation(ts.isPropertyAccessExpression(access) ? access.name : access) === undefined)
33
+ keys.add(key);
34
+ }
35
+ return (untypedWrites = keys);
36
+ };
37
+ // Every call spelled as a member call, by key, so a method's surplus
38
+ // arguments are found without rescanning the program per method.
39
+ let memberCalls;
40
+ const memberCallsOf = (key) => {
41
+ if (!memberCalls) {
42
+ const byKey = new Map();
43
+ for (const site of flow?.calls ?? []) {
44
+ const call = site.call;
45
+ if (!ts.isCallExpression(call))
46
+ continue;
47
+ const callee = call.expression;
48
+ if (!ts.isPropertyAccessExpression(callee) && !ts.isElementAccessExpression(callee))
49
+ continue;
50
+ const name = keyOf(callee);
51
+ if (name === null)
52
+ continue;
53
+ const list = byKey.get(name) ?? [];
54
+ list.push(call);
55
+ byKey.set(name, list);
56
+ }
57
+ memberCalls = byKey;
58
+ }
59
+ return memberCalls.get(key) ?? [];
60
+ };
61
+ /** The most arguments any call of this method passes, or null when one spreads them. */
62
+ const suppliedArity = (symbol) => {
63
+ let widest = 0;
64
+ for (const call of memberCallsOf(symbol.name)) {
65
+ const callee = call.expression;
66
+ // A property read can resolve to a transient (instantiated) symbol of the same declaration.
67
+ const resolved = memberSymbolOf(callee, symbol.name);
68
+ if (resolved !== symbol && !resolved?.declarations?.some((declaration) => symbol.declarations?.includes(declaration)))
69
+ continue;
70
+ if (call.arguments.some(ts.isSpreadElement))
71
+ return null;
72
+ widest = Math.max(widest, call.arguments.length);
73
+ }
74
+ return widest;
75
+ };
12
76
  const resolve = (symbol) => {
13
77
  if (cache.has(symbol))
14
78
  return cache.get(symbol) ?? null;
@@ -30,7 +94,8 @@ export const createMutableMethodResolver = (checker, table, flow, signatureOf, r
30
94
  // and counting them re-translated a generic class's open body signature
31
95
  // outside every copy.
32
96
  const replacements = [...writes].filter((write) => (write.slot === 'whole' || write.slot === 'member') && write.edge !== 'return' && write.edge !== 'yield');
33
- if (!replacements.some((write) => write.value !== null))
97
+ const replaced = replacements.some((write) => write.value !== null);
98
+ if (!replaced && !untypedWriteKeys().has(symbol.name))
34
99
  return null;
35
100
  pending.add(symbol);
36
101
  try {
@@ -54,11 +119,32 @@ export const createMutableMethodResolver = (checker, table, flow, signatureOf, r
54
119
  }
55
120
  if (!signatures.length)
56
121
  return null;
57
- const widest = signatures.reduce((held, next) => (next.parameters.length > held.parameters.length ? next : held));
122
+ const longest = signatures.reduce((held, next) => (next.parameters.length > held.parameters.length ? next : held));
58
123
  // Rest tails have independent positional semantics; never manufacture a
59
124
  // fixed frame by truncating one. Equal frames need no new authority.
60
125
  if (signatures.some((signature) => signature.parameters.some((parameter) => parameter.rest)))
61
126
  return null;
127
+ // A call passes every argument it spells (ECMA-262 13.3.8.1), and the
128
+ // function the slot holds by then is whichever replacement was stored,
129
+ // which may bind more parameters than the declared body does. A frame
130
+ // narrower than the widest call drops the surplus before the stored
131
+ // function can bind it, so the frame carries it as an optional `any`.
132
+ const supplied = suppliedArity(symbol);
133
+ if (supplied === null)
134
+ return null;
135
+ const anyType = table.intern({ kind: 'primitive', primitive: 'any' });
136
+ const surplus = Array.from({ length: Math.max(0, supplied - longest.parameters.length) }, () => ({
137
+ type: anyType,
138
+ slot: anyType,
139
+ optional: true,
140
+ rest: false,
141
+ hasInitializer: false
142
+ }));
143
+ if (surplus.length === 0 && !replaced)
144
+ return null;
145
+ const widest = surplus.length === 0 ? longest : { ...longest, parameters: [...longest.parameters, ...surplus] };
146
+ if (surplus.length > 0)
147
+ signatures.push(widest);
62
148
  const join = (values) => {
63
149
  const members = [...new Set(values)];
64
150
  return members.length === 1 ? members[0] : table.intern({ kind: 'union', members });
@@ -1,6 +1,6 @@
1
1
  import type { FunctionId, IrValueId } from '../../identity/ids.js';
2
2
  import { type PrivateBorrowCell } from '../../ir/borrowed-call-arguments.js';
3
- import type { IrBody, IrOperand } from '../../ir/model.js';
3
+ import { type IrBody, type IrOperand } from '../../ir/model.js';
4
4
  import { type CallableAbi } from '../../representation/model.js';
5
5
  /** The original body name remains an owning entry wrapper. This additional
6
6
  * entry is internal and may be selected only with stable-actual evidence.
@@ -10,12 +10,20 @@ export interface StableBorrowEntry {
10
10
  readonly name: string;
11
11
  readonly abi: CallableAbi;
12
12
  readonly formals: ReadonlySet<number>;
13
+ /**
14
+ * Whether the body's declared signature narrows an integer formal or its
15
+ * result. The entry then spells those narrowed types exactly as the owning
16
+ * entry does, so a direct call reaches either with the same arguments; a
17
+ * carrier-level adapter (`callKnownBorrowed`) passes the unnarrowed ABI and
18
+ * must keep the thunk, which converts at that boundary.
19
+ */
20
+ readonly narrowedNumericAbi: boolean;
13
21
  }
14
22
  export declare const stableBorrowEntryOf: (body: IrBody, owner: FunctionId, privateCell: PrivateBorrowCell, originalBorrowed: ReadonlySet<number>, dyingArguments: ReadonlySet<IrValueId>, admission: {
15
23
  readonly captureFree: boolean;
16
24
  readonly synchronous: boolean;
17
25
  readonly singleBody: boolean;
18
- readonly unchangedNumericAbi: boolean;
26
+ readonly narrowedNumericAbi: boolean;
19
27
  }) => StableBorrowEntry | null;
20
28
  /** A private caller slot survives arbitrary program re-entry. All extra
21
29
  * reference formals must bind such slots; otherwise use the existing owning
@@ -28,3 +36,34 @@ export declare const stableBorrowEntryOf: (body: IrBody, owner: FunctionId, priv
28
36
  * Scalars cannot move a string/handle slot. Binding a borrowed formal does
29
37
  * not itself move from its argument. */
30
38
  export declare const stableBorrowEntryAccepts: (entry: StableBorrowEntry, actuals: readonly IrOperand[], stable: ReadonlySet<IrValueId>, dyingArguments: ReadonlySet<IrValueId>) => boolean;
39
+ /**
40
+ * The borrowed positions a call copies into a temporary of the formal's own
41
+ * carrier so that it can still enter the borrowed entry, or null when the
42
+ * entry is refused.
43
+ *
44
+ * A reference formal bound to a temporary the call itself made is as private
45
+ * as a caller-owned local: nothing else can name it, and it lives until the end
46
+ * of the full-expression, past the callee's return. So an actual that is not a
47
+ * stable slot -- a field or element read the printer may withhold as a
48
+ * reference into mutable storage, or a value converted on the way in -- is
49
+ * copied by itself, which is exactly the copy the owning entry's by-value
50
+ * formal made. Refusing the whole entry for it sent every other argument of
51
+ * the call through by-value formals too: one union read from a field cost a
52
+ * copy and release of each handle beside it, and a move of each local.
53
+ *
54
+ * Mixed move/borrow evaluation is still refused, for `stableBorrowEntryAccepts`'s
55
+ * reason: an owning sibling's `std::move` may be evaluated before a copy or a
56
+ * reference of the same slot is taken.
57
+ */
58
+ export declare const stableBorrowEntryCopies: (entry: StableBorrowEntry, actuals: readonly IrOperand[], stable: ReadonlySet<IrValueId>, dyingArguments: ReadonlySet<IrValueId>) => ReadonlySet<number> | null;
59
+ /**
60
+ * Dying argument reads a call hands to a position its callee's borrowed entry
61
+ * takes by reference -- a direct call's, or every arm's of a union dispatch: the entry binds them in place, so they move
62
+ * nothing. Only a call that will enter the entry counts -- one where no other
63
+ * position moves a handle (`stableBorrowEntryCopies`' refusal) -- and only an
64
+ * argument already carried as the formal, since a conversion builds a
65
+ * temporary of its own and the move feeds that.
66
+ */
67
+ export declare const borrowForwardedArgumentsOf: (bodies: readonly IrBody[], entries: ReadonlyMap<string, StableBorrowEntry>, dyingArguments: ReadonlySet<IrValueId>) => ReadonlySet<IrValueId>;
68
+ /** `dying` without `released`, keeping the sunk stores of the reads that remain. */
69
+ export declare const withoutDyingArguments: (dying: ReadonlySet<IrValueId>, released: ReadonlySet<IrValueId>) => ReadonlySet<IrValueId>;
@@ -1,13 +1,11 @@
1
1
  import { borrowWorthy, dynamicFormalIsReadOnly, readonlyBorrowFormalsOf } from '../../ir/borrowed-call-arguments.js';
2
+ import { allOperationsOf } from '../../ir/model.js';
3
+ import { DyingArgumentSet } from '../../ir/transfer.js';
2
4
  import { representationKey } from '../../representation/model.js';
3
5
  import { cppBodyName } from './types.js';
4
6
  export const stableBorrowEntryOf = (body, owner, privateCell, originalBorrowed, dyingArguments, admission) => {
5
7
  const abi = body.abi;
6
- if (body.sourceOwner !== owner ||
7
- !admission.captureFree ||
8
- !admission.synchronous ||
9
- !admission.singleBody ||
10
- !admission.unchangedNumericAbi)
8
+ if (body.sourceOwner !== owner || !admission.captureFree || !admission.synchronous || !admission.singleBody)
11
9
  return null;
12
10
  // A receiver is not disqualifying: `signatureOf`/`bodyFormalsOf` already
13
11
  // spell a method's `this` from `borrowsReceiver`, independently of the
@@ -43,7 +41,7 @@ export const stableBorrowEntryOf = (body, owner, privateCell, originalBorrowed,
43
41
  // Never revoke an established, stronger effect-based borrow proof.
44
42
  for (const ordinal of originalBorrowed)
45
43
  formals.add(ordinal);
46
- return { owner, name: `${cppBodyName(owner)}_stable_borrow`, abi, formals };
44
+ return { owner, name: `${cppBodyName(owner)}_stable_borrow`, abi, formals, narrowedNumericAbi: admission.narrowedNumericAbi };
47
45
  };
48
46
  /** A private caller slot survives arbitrary program re-entry. All extra
49
47
  * reference formals must bind such slots; otherwise use the existing owning
@@ -70,3 +68,90 @@ export const stableBorrowEntryAccepts = (entry, actuals, stable, dyingArguments)
70
68
  !dyingArguments.has(actual.value) ||
71
69
  !(borrowWorthy(actual.representation) || actual.representation.kind === 'dynamic'));
72
70
  };
71
+ /**
72
+ * The borrowed positions a call copies into a temporary of the formal's own
73
+ * carrier so that it can still enter the borrowed entry, or null when the
74
+ * entry is refused.
75
+ *
76
+ * A reference formal bound to a temporary the call itself made is as private
77
+ * as a caller-owned local: nothing else can name it, and it lives until the end
78
+ * of the full-expression, past the callee's return. So an actual that is not a
79
+ * stable slot -- a field or element read the printer may withhold as a
80
+ * reference into mutable storage, or a value converted on the way in -- is
81
+ * copied by itself, which is exactly the copy the owning entry's by-value
82
+ * formal made. Refusing the whole entry for it sent every other argument of
83
+ * the call through by-value formals too: one union read from a field cost a
84
+ * copy and release of each handle beside it, and a move of each local.
85
+ *
86
+ * Mixed move/borrow evaluation is still refused, for `stableBorrowEntryAccepts`'s
87
+ * reason: an owning sibling's `std::move` may be evaluated before a copy or a
88
+ * reference of the same slot is taken.
89
+ */
90
+ export const stableBorrowEntryCopies = (entry, actuals, stable, dyingArguments) => {
91
+ const copies = new Set();
92
+ for (const ordinal of entry.formals) {
93
+ const actual = actuals[ordinal];
94
+ const formal = entry.abi.parameters[ordinal];
95
+ if (!formal)
96
+ return null;
97
+ // An omitted argument is padded with a temporary of the formal's carrier.
98
+ if (!actual)
99
+ continue;
100
+ if (!stable.has(actual.value) || representationKey(actual.representation) !== representationKey(formal.value))
101
+ copies.add(ordinal);
102
+ }
103
+ const siblingsStayPut = actuals.every((actual, ordinal) => entry.formals.has(ordinal) ||
104
+ !dyingArguments.has(actual.value) ||
105
+ !(borrowWorthy(actual.representation) || actual.representation.kind === 'dynamic'));
106
+ return siblingsStayPut ? copies : null;
107
+ };
108
+ /**
109
+ * Dying argument reads a call hands to a position its callee's borrowed entry
110
+ * takes by reference -- a direct call's, or every arm's of a union dispatch: the entry binds them in place, so they move
111
+ * nothing. Only a call that will enter the entry counts -- one where no other
112
+ * position moves a handle (`stableBorrowEntryCopies`' refusal) -- and only an
113
+ * argument already carried as the formal, since a conversion builds a
114
+ * temporary of its own and the move feeds that.
115
+ */
116
+ export const borrowForwardedArgumentsOf = (bodies, entries, dyingArguments) => {
117
+ const forwarded = new Set();
118
+ for (const body of bodies)
119
+ for (const block of body.blocks.values())
120
+ for (const operation of allOperationsOf(block)) {
121
+ if (operation.kind !== 'call')
122
+ continue;
123
+ const target = operation.target;
124
+ const targets = target?.kind === 'direct' ? [target.functionId] : target?.kind === 'union-arm' ? target.arms.map((arm) => arm.functionId) : [];
125
+ const callees = targets.map((functionId) => entries.get(cppBodyName(functionId)));
126
+ if (callees.length === 0)
127
+ continue;
128
+ // A union dispatch enters one arm's body, so every arm must take the position by reference.
129
+ operation.arguments.forEach((argument, ordinal) => {
130
+ if (!dyingArguments.has(argument.value))
131
+ return;
132
+ const borrowed = callees.every((entry) => {
133
+ const formal = entry?.abi.parameters[ordinal];
134
+ return (entry !== undefined &&
135
+ formal !== undefined &&
136
+ entry.formals.has(ordinal) &&
137
+ representationKey(argument.representation) === representationKey(formal.value) &&
138
+ stableBorrowEntryCopies(entry, operation.arguments, new Set(), dyingArguments) !== null);
139
+ });
140
+ if (borrowed)
141
+ forwarded.add(argument.value);
142
+ });
143
+ }
144
+ return forwarded;
145
+ };
146
+ /** `dying` without `released`, keeping the sunk stores of the reads that remain. */
147
+ export const withoutDyingArguments = (dying, released) => {
148
+ const kept = new DyingArgumentSet();
149
+ for (const value of dying)
150
+ if (!released.has(value))
151
+ kept.add(value);
152
+ if (dying instanceof DyingArgumentSet)
153
+ for (const [value, store] of dying.sunkStores)
154
+ if (!released.has(value))
155
+ kept.sunkStores.set(value, store);
156
+ return kept;
157
+ };