@geastack/compiler 1.0.43 → 1.0.44

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.
@@ -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,
@@ -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
+ };
@@ -1,7 +1,7 @@
1
1
  import { proxyArmWithoutHome } from '../../representation/proxy-carriers.js';
2
2
  import { operationNativeCallReceiverText } from './emit-native-method.js';
3
3
  import { genericNativeLogicalReceiverOf, hostConstructFrameOf, receivableArguments } from '../../ir/call-entry.js';
4
- import { stableBorrowEntryAccepts } from './borrowed-call-entry.js';
4
+ import { stableBorrowEntryAccepts, stableBorrowEntryCopies } from './borrowed-call-entry.js';
5
5
  import { callableMemberAlternateSlot, callableMemberSlot } from '../../ir/callable-member-candidates.js';
6
6
  import { transferOf } from '../../ir/transfer.js';
7
7
  import { boxedValueText } from './emit-dynamic-properties.js';
@@ -41,7 +41,7 @@ import { nativePromiseBaseInitializeStatements } from './native-promise-base.js'
41
41
  import { emitArrayBufferConstruct, emitSharedArrayBufferConstruct, emitTextCodecConstruct, emitDataViewConstruct, emitTypedArrayBufferConstruct, typedArrayTargetSpelling } from './emit-buffers.js';
42
42
  import { armAt, armIs } from './emit-union-properties.js';
43
43
  import { constructorStateText, genericStaticOwnerOf } from './class-properties/emit-class-properties.js';
44
- import { cppAbiType, cppBodyName, cppBoxedType, cppCallableDeclarationTagName, cppClassName, cppConstructName, cppInitializeName, cppRecordFieldName, cppRecordFieldPresenceName, cppRefcountedReceiver, cppStringLiteral, cppTypeOf, cppResultTypeOf, cppUndefinedValue } from './types.js';
44
+ import { cppAbiType, cppBodyName, cppBoxedType, cppCallableDeclarationTagName, cppClassName, cppConstructName, cppInitializeName, cppRecordFieldName, cppRecordFieldPresenceName, cppRefcountedReceiver, cppStringLiteral, cppAbiParameterType, cppTypeOf, cppResultTypeOf, cppUndefinedValue } from './types.js';
45
45
  /** `Function.prototype.bind` preserves the native call ABI and captures only evaluated prefix values. */
46
46
  export const emitBindCallable = (ctx, lines, operation) => {
47
47
  if (operation.result.representation.kind !== 'function-value-dispatch') {
@@ -498,6 +498,36 @@ const restPackedArguments = (ctx, held, body, operation) => {
498
498
  `gea::arrayOf<${cppTypeOf(rest.element)}>({${elements.join(', ')}})`
499
499
  ];
500
500
  };
501
+ /** Which arguments of `operation` may move, and which name a slot no callee can write -- the evidence a borrowed entry is admitted on. */
502
+ const borrowEvidenceOf = (ctx, operation) => {
503
+ const potentiallyMovingArguments = new Set(operation.arguments
504
+ .filter((argument) => transferOf(ctx.dyingArguments, ctx.ownedValues, ctx.transferDyingValues, argument.value, ctx.receiverRenames) === 'move')
505
+ .map((argument) => argument.value));
506
+ // `stableBorrowActualsOf` leaves out every value an operation computes, because
507
+ // the printer may withhold one as an expression naming mutable storage. By the
508
+ // time a call renders, every argument's own definition has rendered, so that
509
+ // choice is settled: an owned SSA temporary the printer declared a local of its
510
+ // own (`defineValue`) and did not withhold is a slot of this frame no callee can
511
+ // name, exactly like a private cell. `setNativeUniformValue(u, gl, v.value, t)`
512
+ // sent its freshly read uniform value through the owning wrapper, copying the
513
+ // seq element union and the optional texture table into by-value formals per
514
+ // uniform per draw.
515
+ // A repeated conversion spelled as an earlier one's storage (`repeatedConversions`) is that storage.
516
+ const storageOf = (value) => ctx.repeatedConversions.get(value) ?? value;
517
+ const stableActuals = new Set(operation.arguments
518
+ .map((argument) => argument.value)
519
+ .filter((value) => ctx.stableBorrowActuals.has(value) || (ctx.ownedValues.has(storageOf(value)) && !isDeferredValue(ctx, storageOf(value)))));
520
+ return { potentiallyMovingArguments, stableActuals };
521
+ };
522
+ /** The arguments of a call into `entry`, each position `stableBorrowEntryCopies` named copied into its formal's own carrier. */
523
+ const copiedBorrowArguments = (padded, offset, entry, copies) => entry === undefined || copies === null || copies.size === 0
524
+ ? padded
525
+ : padded.map((text, index) => {
526
+ const parameter = entry.abi.parameters[index - offset];
527
+ return index >= offset && copies.has(index - offset) && parameter !== undefined
528
+ ? `static_cast<${cppAbiParameterType(parameter)}>(${text})`
529
+ : text;
530
+ });
501
531
  const emitUnionMethodCall = (ctx, lines, operation) => {
502
532
  const read = ctx.unionMethodReads.get(operation.callee.value);
503
533
  if (read === undefined)
@@ -510,6 +540,7 @@ const emitUnionMethodCall = (ctx, lines, operation) => {
510
540
  // paths the claim recorded are indices into the carrier, and `armAt`/`armIs`
511
541
  // turn them into text against a receiver that has a name by now.
512
542
  const receiverText = operandText(ctx, read.receiver);
543
+ const evidence = borrowEvidenceOf(ctx, operation);
513
544
  const branches = arms.map((arm, index) => {
514
545
  const tests = [];
515
546
  let armText = receiverText;
@@ -546,9 +577,18 @@ const emitUnionMethodCall = (ctx, lines, operation) => {
546
577
  throw createCppEmitBlockedError(`conversion:${representationKey(arm.receiverRepresentation)}->${representationKey(abi.receiver)}`, `a deferred tagged-union method receiver cannot convert from ${representationKey(arm.receiverRepresentation)} to ${representationKey(abi.receiver)}`);
547
578
  }
548
579
  const heldAbi = abiOfCallee(operation.callee.representation);
549
- const supplied = (heldAbi === null ? null : restPackedArguments(ctx, heldAbi, abi, operation)) ??
550
- receivableArguments(abi, operation.arguments).map((argument, position) => argumentText(ctx, abi, position, argument));
551
- const invocation = `${cppBodyName(arm.callable)}(${paddedArguments(abi, [...(receiver === null ? [] : [receiver]), ...supplied], 'union method call').join(', ')})`;
580
+ const packed = heldAbi === null ? null : restPackedArguments(ctx, heldAbi, abi, operation);
581
+ const supplied = packed ?? receivableArguments(abi, operation.arguments).map((argument, position) => argumentText(ctx, abi, position, argument));
582
+ const padded = paddedArguments(abi, [...(receiver === null ? [] : [receiver]), ...supplied], 'union method call');
583
+ // Each arm names its body, so it may enter that body's borrowed entry on the
584
+ // same evidence a direct call does.
585
+ const entry = packed === null ? ctx.stableBorrowEntries.get(cppBodyName(arm.callable)) : undefined;
586
+ const copies = entry === undefined
587
+ ? null
588
+ : stableBorrowEntryCopies(entry, operation.arguments, evidence.stableActuals, evidence.potentiallyMovingArguments);
589
+ const invocation = entry === undefined || copies === null
590
+ ? `${cppBodyName(arm.callable)}(${padded.join(', ')})`
591
+ : `${entry.name}(${copiedBorrowArguments(padded, receiver === null ? 0 : 1, entry, copies).join(', ')})`;
552
592
  let body;
553
593
  if (operation.result === null || operation.result.representation.kind === 'void') {
554
594
  body = `${invocation}; return;`;
@@ -1370,32 +1410,21 @@ export const emitCall = (ctx, lines, operation) => {
1370
1410
  const candidate = memberSlot === undefined ? undefined : ctx.callableMemberCandidates.get(memberSlot);
1371
1411
  const alternate = memberSlot === undefined ? undefined : ctx.callableMemberCandidates.get(callableMemberAlternateSlot(memberSlot));
1372
1412
  const stableCandidate = ctx.stableBorrowEntries.get(direct ?? (candidate === undefined ? '' : cppBodyName(candidate)));
1373
- const potentiallyMovingArguments = new Set(operation.arguments
1374
- .filter((argument) => transferOf(ctx.dyingArguments, ctx.ownedValues, ctx.transferDyingValues, argument.value, ctx.receiverRenames) === 'move')
1375
- .map((argument) => argument.value));
1376
- // `stableBorrowActualsOf` leaves out every value an operation computes, because
1377
- // the printer may withhold one as an expression naming mutable storage. By the
1378
- // time a call renders, every argument's own definition has rendered, so that
1379
- // choice is settled: an owned SSA temporary the printer declared a local of its
1380
- // own (`defineValue`) and did not withhold is a slot of this frame no callee can
1381
- // name, exactly like a private cell. `setNativeUniformValue(u, gl, v.value, t)`
1382
- // sent its freshly read uniform value through the owning wrapper, copying the
1383
- // seq element union and the optional texture table into by-value formals per
1384
- // uniform per draw.
1385
- // A repeated conversion spelled as an earlier one's storage (`repeatedConversions`) is that storage.
1386
- const storageOf = (value) => ctx.repeatedConversions.get(value) ?? value;
1387
- const stableActuals = new Set(operation.arguments
1388
- .map((argument) => argument.value)
1389
- .filter((value) => ctx.stableBorrowActuals.has(value) || (ctx.ownedValues.has(storageOf(value)) && !isDeferredValue(ctx, storageOf(value)))));
1390
- const stableEntry = stableCandidate !== undefined &&
1391
- stableBorrowEntryAccepts(stableCandidate, operation.arguments, stableActuals, potentiallyMovingArguments)
1392
- ? stableCandidate
1393
- : undefined;
1413
+ const { potentiallyMovingArguments, stableActuals } = borrowEvidenceOf(ctx, operation);
1414
+ // A narrowed integer formal is spelled alike by both entries only for a call
1415
+ // that names the body; a carrier adapter passes the unnarrowed ABI.
1416
+ const stableCopies = stableCandidate === undefined || (direct === undefined && stableCandidate.narrowedNumericAbi)
1417
+ ? null
1418
+ : stableBorrowEntryCopies(stableCandidate, operation.arguments, stableActuals, potentiallyMovingArguments);
1419
+ const stableEntry = stableCopies === null ? undefined : stableCandidate;
1420
+ const stableArguments = copiedBorrowArguments(padded, declaredReceiverOperand ? 1 : 0, stableEntry, stableCopies);
1394
1421
  // A candidate's borrowed entry for this call, when it has one: the stable
1395
1422
  // entry its arguments are accepted by, or its borrowable body.
1396
1423
  const borrowedEntryOf = (target) => {
1397
1424
  const stable = ctx.stableBorrowEntries.get(cppBodyName(target));
1398
- if (stable !== undefined && stableBorrowEntryAccepts(stable, operation.arguments, stableActuals, potentiallyMovingArguments))
1425
+ if (stable !== undefined &&
1426
+ !stable.narrowedNumericAbi &&
1427
+ stableBorrowEntryAccepts(stable, operation.arguments, stableActuals, potentiallyMovingArguments))
1399
1428
  return stable.name;
1400
1429
  return ctx.borrowableMemberBodies.has(target) ? cppBodyName(target) : undefined;
1401
1430
  };
@@ -1416,6 +1445,10 @@ export const emitCall = (ctx, lines, operation) => {
1416
1445
  const flowKnown = candidate === undefined && direct === undefined && dispatched === undefined && calleeOperand.value === operation.callee.value
1417
1446
  ? flowKnownText(ctx, operation.callee)
1418
1447
  : null;
1448
+ const candidateEntersStableEntry = candidate !== undefined &&
1449
+ !(firstEntry !== undefined && alternate !== undefined && alternateEntry !== undefined) &&
1450
+ !alternateOnly &&
1451
+ stableEntry !== undefined;
1419
1452
  const callMember = candidate === undefined
1420
1453
  ? flowKnown !== null
1421
1454
  ? `${stableCallee ? 'callStableKnown' : 'callKnown'}<${flowKnown}>`
@@ -1483,14 +1516,14 @@ export const emitCall = (ctx, lines, operation) => {
1483
1516
  const invocation = dispatched !== undefined
1484
1517
  ? `${virtualPadded[0]}->${dispatched.member}(${virtualPadded.slice(1).join(', ')})`
1485
1518
  : direct !== undefined
1486
- ? `${stableEntry?.name ?? direct}(${padded.join(', ')})`
1519
+ ? `${stableEntry?.name ?? direct}(${stableArguments.join(', ')})`
1487
1520
  : abi.receiver === null && logicalThis !== null
1488
1521
  ? lazyLogicalReceiver(logicalThis)
1489
1522
  ? `${operandText(ctx, calleeOperand)}.callWithLazyReceiver(${[`[&]() -> gea::NativeCallReceiver { return ${operationNativeCallReceiverText(ctx, operation, logicalThis.representation, operandText(ctx, logicalThis))}; }`, ...padded].join(', ')})`
1490
1523
  : `${operandText(ctx, calleeOperand)}.callWithReceiver(${[operationNativeCallReceiverText(ctx, operation, logicalThis.representation, operandText(ctx, logicalThis)), ...padded].join(', ')})`
1491
1524
  : guardable
1492
1525
  ? guardedInvocation()
1493
- : `${operandText(ctx, calleeOperand)}.${callMember}(${padded.join(', ')})`;
1526
+ : `${operandText(ctx, calleeOperand)}.${callMember}(${(candidateEntersStableEntry ? stableArguments : padded).join(', ')})`;
1494
1527
  // A result the integer census narrowed from the candidate body's returns is
1495
1528
  // checked where it lands, on every path the call can take: the guard above
1496
1529
  // may miss and run whatever callable the member holds.