@geastack/compiler 1.0.42 → 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.
Files changed (58) hide show
  1. package/dist/cli.js +8 -2
  2. package/dist/conversion/nodes.js +5 -2
  3. package/dist/ir/callable-class-flow.js +48 -13
  4. package/dist/ir/certify.js +1 -1
  5. package/dist/ir/host-template-conversions.d.ts +2 -2
  6. package/dist/ir/host-template-conversions.js +73 -2
  7. package/dist/ir/lower-destructuring.js +22 -3
  8. package/dist/ir/lower-operands.js +30 -1
  9. package/dist/ir/native-field-view-facts.d.ts +8 -1
  10. package/dist/ir/native-field-view-facts.js +13 -3
  11. package/dist/ir/operation-conversions.js +1 -1
  12. package/dist/ir/program-conversions.d.ts +1 -1
  13. package/dist/ir/program-conversions.js +68 -1
  14. package/dist/ir/property-read-conversions.js +7 -1
  15. package/dist/ir/publish-native-field-view-facts.js +4 -0
  16. package/dist/ir/reflection-demand.js +29 -3
  17. package/dist/ir/shake.js +21 -0
  18. package/dist/projection/dispatch.d.ts +19 -1
  19. package/dist/projection/dispatch.js +34 -0
  20. package/dist/representation/value-records.js +182 -13
  21. package/dist/semantics/frontend.js +18 -14
  22. package/dist/semantics/normalize/collection-bindings.d.ts +7 -0
  23. package/dist/semantics/normalize/collection-bindings.js +35 -1
  24. package/dist/semantics/normalize/derived-expression-type.js +49 -0
  25. package/dist/semantics/normalize/field-bindings.js +6 -1
  26. package/dist/semantics/normalize/flow/component-solver.js +37 -2
  27. package/dist/semantics/normalize/flow/source-value-session.d.ts +12 -2
  28. package/dist/semantics/normalize/flow/source-value-session.js +861 -212
  29. package/dist/semantics/normalize/global-host-mutations.js +14 -6
  30. package/dist/semantics/normalize/implicit-arguments-tuple.d.ts +11 -10
  31. package/dist/semantics/normalize/implicit-arguments-tuple.js +15 -3
  32. package/dist/semantics/normalize/local-bindings.js +23 -1
  33. package/dist/semantics/normalize/producers/references.js +26 -18
  34. package/dist/semantics/normalize/structural-array-element.d.ts +7 -0
  35. package/dist/semantics/normalize/structural-array-element.js +24 -1
  36. package/dist/semantics/normalize/structural-layout-type.js +5 -1
  37. package/dist/semantics/normalize/structural-mutable-method.js +88 -2
  38. package/dist/semantics/normalize/structural-parts.js +13 -8
  39. package/dist/semantics/normalize/structural.js +25 -1
  40. package/dist/targets/cpp/borrowed-call-entry.d.ts +41 -2
  41. package/dist/targets/cpp/borrowed-call-entry.js +91 -6
  42. package/dist/targets/cpp/class-properties/emit-class-properties.js +5 -1
  43. package/dist/targets/cpp/emit-callable.js +81 -39
  44. package/dist/targets/cpp/emit-native-field-view.d.ts +2 -0
  45. package/dist/targets/cpp/emit-native-field-view.js +1 -1
  46. package/dist/targets/cpp/emit-properties.js +114 -12
  47. package/dist/targets/cpp/host/emit-host-invoke.js +16 -2
  48. package/dist/targets/cpp/host/emit-host-object.js +69 -2
  49. package/dist/targets/cpp/host/host-members.js +4 -0
  50. package/dist/targets/cpp/prototype/emit-prototype-array.d.ts +42 -0
  51. package/dist/targets/cpp/prototype/emit-prototype-array.js +31 -9
  52. package/dist/targets/cpp/records.d.ts +1 -0
  53. package/dist/targets/cpp/records.js +40 -17
  54. package/dist/targets/cpp/translation-unit.js +82 -24
  55. package/dist/targets/cpp/virtual-methods.js +9 -4
  56. package/package.json +1 -1
  57. package/src/targets/cpp/runtime/gea_dynamic_proxy.h +17 -1
  58. package/src/targets/cpp/runtime/gea_runtime.h +485 -64
@@ -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
+ };
@@ -590,7 +590,11 @@ export const computedClassPrototypeMethodText = (ctx, operation) => {
590
590
  if (branches.length === 0)
591
591
  return null;
592
592
  const keyBinding = staticKey === undefined ? `const std::string& gea_method_key = ${operandText(ctx, operation.key)}; ` : '';
593
- return { text: `([&]() -> ${type} { ${keyBinding}${branches.join(' ')} return gea::Value(); })()`, spelling: type, carrier: result };
593
+ // A key naming no method can still name an accessor up the prototype
594
+ // chain (`Material.setValues`'s `this[ key ]` for `alphaTest`); the
595
+ // runtime's own [[Get]] reaches it through the class's prototype hook.
596
+ const miss = staticKey === undefined ? `gea::nativeDynamicGet(${object}, gea::PropertyKey::string(gea_method_key))` : 'gea::Value()';
597
+ return { text: `([&]() -> ${type} { ${keyBinding}${branches.join(' ')} return ${miss}; })()`, spelling: type, carrier: result };
594
598
  }
595
599
  if (staticKey !== undefined)
596
600
  return null;
@@ -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.
@@ -2098,20 +2131,29 @@ const emitTypedArrayConstruct = (ctx, lines, operation, result) => {
2098
2131
  return;
2099
2132
  }
2100
2133
  // A BOXED argument. The overload this dispatch reads off a carrier is read
2101
- // off the BOX'S TAG instead, and the tag can pick exactly one: `Tag::Number`
2102
- // is the `length` overload. `unboxedLoadText` renders that as the
2103
- // tag-and-payload-checked read, so a box holding anything else aborts by
2104
- // name at the construction rather than being reinterpreted as a length --
2105
- // the same discipline every other boxed read in this backend keeps, and the
2106
- // reason `preflight/invocation-arguments.ts` can state `scalar(number)` as
2107
- // this argument's target without over-claiming.
2134
+ // off the BOX'S TAG instead, at run time, as ECMA-262 23.2.5.1 itself reads
2135
+ // it off the value: `Tag::Number` is the `length` overload, and anything
2136
+ // else is the numeric-Array copy `isNumericArrayCarrier` takes below.
2137
+ // The checker cannot pick for us: an `any` argument resolves to the first
2138
+ // declared overload, `length: number`, so `new Float32Array(out[k])` with
2139
+ // `k` from a `string[]` reached here as a length while the box held an
2140
+ // `ArrayObject<double>`, and the length read aborted.
2141
+ // `unboxedLoadText` renders both reads checked, so a box holding anything
2142
+ // else (a string, `undefined`, a boxed typed array or buffer, a non-number
2143
+ // element) aborts by name rather than being reinterpreted.
2108
2144
  //
2109
2145
  // `new Int32Array( n )` and `new Float32Array( flatSize )` in untyped
2110
2146
  // JavaScript are both a length through a parameter the source never typed.
2111
2147
  if (carrier.kind === 'dynamic') {
2112
- const length = unboxedLoadText({ kind: 'scalar', domain: 'number' }, operandText(ctx, argument));
2113
- if (length !== null) {
2114
- lines.push(`${name} = gea::makeRef<${target}>(gea::detail::typedArrayLengthIndex(gea::detail::toIntegerOrInfinity(${length})));`);
2148
+ const box = 'gea_typed_source';
2149
+ const number = { kind: 'scalar', domain: 'number' };
2150
+ const length = unboxedLoadText(number, box);
2151
+ const values = unboxedLoadText({ kind: 'array-object', element: number, ownership: 'shared-refcount', extension: null }, box);
2152
+ if (length !== null && values !== null) {
2153
+ lines.push(`${name} = ([&]() -> ${cppTypeOf(result)} { const gea::Value& ${box} = ${operandText(ctx, argument)}; ` +
2154
+ `if (${box}.tag() == gea::Value::Tag::Number) ` +
2155
+ `return gea::makeRef<${target}>(gea::detail::typedArrayLengthIndex(gea::detail::toIntegerOrInfinity(${length}))); ` +
2156
+ `return gea::makeRef<${target}>(${target}::fromValues(${values})); }());`);
2115
2157
  return;
2116
2158
  }
2117
2159
  }
@@ -10,11 +10,13 @@ export declare const nativeFieldViewReadForText: (ctx: EmitContext, receiver: Ir
10
10
  readonly source: Representation;
11
11
  readonly text: string;
12
12
  readonly accessor?: true;
13
+ readonly absentReadsUndefined?: true;
13
14
  } | null, keyOperand?: IrOperand) => string;
14
15
  export declare const nativeFieldViewReadText: (ctx: EmitContext, operation: GetOperation, ordinaryReadOf: (carrier: Representation, key: string) => {
15
16
  readonly source: Representation;
16
17
  readonly text: string;
17
18
  readonly accessor?: true;
19
+ readonly absentReadsUndefined?: true;
18
20
  } | null) => string | null;
19
21
  export declare const nativeFieldViewWriteText: (ctx: EmitContext, operation: SetOperation,
20
22
  /** The receiver's ordinary store of `operation`, rendered in `bound`: what an open write's plain indexed allocation runs. */
@@ -109,7 +109,7 @@ export const nativeFieldViewReadForText = (ctx, receiver, target, receipt, ordin
109
109
  ? `return ${renderedLeaf(ctx, ordinary.conversion, concrete)};`
110
110
  : null;
111
111
  const getterAnswer = ordinary && actual?.accessor === true ? `return ${renderedLeaf(ctx, ordinary.conversion, concrete)};` : memberAnswer;
112
- const plain = ordinary && actual && actual.source.kind === 'optional'
112
+ const plain = ordinary && actual && (actual.source.kind === 'optional' || actual.absentReadsUndefined === true)
113
113
  ? `return ${renderedLeaf(ctx, ordinary.conversion, concrete)};`
114
114
  : 'gea::host::throwRuntimeError("TypeError", "a native view receiver has no admitted plain allocation");';
115
115
  const property = `${viewKeyText(key)}`;
@@ -10,12 +10,13 @@ import { cppDenseFlagName, cppDensePointerName, createCppEmitBlockedError, defin
10
10
  import { declaredHostMethodRead, emitNativeHostStore, nativeHostMemberText } from './host/emit-host-properties.js';
11
11
  import { hostResultText } from './host/emit-host-arity.js';
12
12
  import { classFamilyOverridesOf, classMemberOf, dispatchesStatically, fieldDeclaringStructOf, lazyArrowFieldGetPlanOf, lazyMaterializedFieldText, structNameOfReceiver, isConstructorViewShape } from './class-layout.js';
13
- import { cppArrayExtensionStructName, cppBodyName, cppRecordAccessorEnvironmentName, cppRecordFieldAttributesName, cppRecordFieldName, cppRecordFieldPresenceName, cppRecordStructName, cppTypeOf, cppScalarType, cppStringLiteral, cppUndefinedIn } from './types.js';
13
+ import { cppArrayExtensionStructName, cppBodyName, cppClassName, cppRecordAccessorEnvironmentName, cppRecordFieldAttributesName, cppRecordFieldName, cppRecordFieldPresenceName, cppRecordStructName, cppTypeOf, cppScalarType, cppStringLiteral, cppUndefinedIn } from './types.js';
14
14
  import { isNativeError } from './error-types.js';
15
15
  import { cppVirtualMemberName, virtualDispatchKey } from './virtual-methods.js';
16
16
  import { recordAccessorsOfShape, declaredFieldRepresentationOf, declaredRecordFieldOf, nativeBaseFieldOf, tailAwareFieldWriteText, tailAwareFieldReadText, declaredFieldCreationText, staticKeyOrderText } from './records.js';
17
17
  import { tracksKeyOrder } from './key-order-tracking.js';
18
18
  import { recordLayoutOfShapeId } from '../../projection/fields.js';
19
+ import { classFieldAccessorArmsOf } from '../../projection/dispatch.js';
19
20
  import { nativeErrorMemberText } from './prototype/emit-prototype-error.js';
20
21
  import { structuralRecordViewText } from './emit-record-view.js';
21
22
  import { classMemberText, classConstructorStaticFieldStorage, constructorStaticStateText, constructorViewFieldFor, classConstructorStaticMemberText, constructorIdentityMemberText } from './class-properties/emit-class-properties.js';
@@ -538,9 +539,19 @@ export const emitGet = (ctx, lines, operation) => {
538
539
  let read = plainFieldReadText(plain, plainOperation, key);
539
540
  if (source.value.kind === 'scalar')
540
541
  read = `static_cast<${cppTypeOf(source.value)}>(${read})`;
541
- if (!source.required)
542
- read = `(gea_field_receiver->${cppRecordFieldPresenceName(key)} ? ${read} : ${cppTypeOf(source.value)}())`;
543
- return { source: source.value, text: read };
542
+ if (source.required)
543
+ return { source: source.value, text: read };
544
+ // An absent own key reads undefined. A union spells it as its undefined
545
+ // arm and a Value or a reference as its own; their default does not.
546
+ const undefinedText = cppUndefinedIn(source.value);
547
+ const absent = undefinedText ?? (source.value.kind === 'optional' ? `${cppTypeOf(source.value)}()` : null);
548
+ if (absent === null)
549
+ return null;
550
+ return {
551
+ source: source.value,
552
+ text: `(gea_field_receiver->${cppRecordFieldPresenceName(key)} ? ${read} : ${absent})`,
553
+ ...(undefinedText === null ? {} : { absentReadsUndefined: true })
554
+ };
544
555
  });
545
556
  if (rendered === null)
546
557
  throw new Error('a published field-view read lost its receipt');
@@ -1016,7 +1027,7 @@ export const emitGet = (ctx, lines, operation) => {
1016
1027
  lines.push(`${defineValue(ctx, operation.result)} = ${rendering};`);
1017
1028
  return;
1018
1029
  }
1019
- const read = fixedFieldReadText(ctx, operation, fieldName);
1030
+ const read = accessorShadowedFieldReadText(ctx, operation, fieldName) ?? fixedFieldReadText(ctx, operation, fieldName);
1020
1031
  // A construction-only field of this body's own receiver holds one value
1021
1032
  // from the read to every use (`ctx.stableFieldReads`), so the read names
1022
1033
  // the member. Only the plain member load qualifies: a presence test or a
@@ -1192,6 +1203,97 @@ const fixedFieldReadText = (ctx, operation, fieldName) => {
1192
1203
  }
1193
1204
  return narrowedFieldReadText(ctx, operation, fieldName, fieldReadText(ctx, operation.receiver.representation, fieldName, `${receiver}${accessor}`), presence);
1194
1205
  };
1206
+ /**
1207
+ * The bodies one half of a descendant accessor that shadows a base field
1208
+ * (`classFieldAccessorArmsOf`) selects, each with the allocation test that
1209
+ * selects it -- or an empty list where no arm applies. A by-value carrier
1210
+ * holds exactly its own class, and `super.x` binds statically, so neither
1211
+ * selects.
1212
+ */
1213
+ const shadowingAccessorHalvesOf = (ctx, receiver, fieldName, half, receiverText) => {
1214
+ const representation = receiver.representation;
1215
+ if (representation.kind !== 'class-ref' || representation.ownership !== 'shared-refcount' || dispatchesStatically(ctx, receiver))
1216
+ return [];
1217
+ const halves = new Map();
1218
+ for (const { allocation, owner, accessor } of classFieldAccessorArmsOf(ctx.classes, representation.declaration, fieldName)) {
1219
+ const entry = halves.get(accessor[half]) ?? { owner, allocations: [] };
1220
+ entry.allocations.push(allocation);
1221
+ halves.set(accessor[half], entry);
1222
+ }
1223
+ return [...halves].map(([body, { owner, allocations }]) => ({
1224
+ body,
1225
+ owner,
1226
+ test: `gea::host::hasNativeClassLayoutRef<${allocations.map((allocation) => cppClassName(allocation)).join(', ')}>(${receiverText})`
1227
+ }));
1228
+ };
1229
+ /**
1230
+ * A base-typed field read whose key a descendant redeclares as an accessor:
1231
+ * those allocations answer from the getter, selected by the allocation header
1232
+ * as an overridden method value is, and the rest from the field. A spread
1233
+ * snapshot copies own properties only, so it never selects.
1234
+ */
1235
+ const accessorShadowedFieldReadText = (ctx, operation, fieldName) => {
1236
+ const receiver = operation.receiver.representation;
1237
+ const getters = operation.spreadSnapshot === true
1238
+ ? []
1239
+ : shadowingAccessorHalvesOf(ctx, operation.receiver, fieldName, 'getter', 'gea_shadowed_receiver');
1240
+ if (getters.length === 0)
1241
+ return null;
1242
+ const published = operation.result.representation;
1243
+ const refused = (reason) => createCppEmitBlockedError(`property-access:${representationKey(receiver)}:get:false`, `field "${fieldName}" ${reason}`);
1244
+ const branches = getters.map(({ body: getter, owner, test }) => {
1245
+ if (getter === null) {
1246
+ // A setter-only accessor still shadows the field; reading it is undefined.
1247
+ const absent = cppUndefinedIn(published);
1248
+ if (absent === null)
1249
+ throw refused(`is redeclared by ${owner} without a getter, and this read's carrier holds no undefined`);
1250
+ return `if (${test}) return ${absent};`;
1251
+ }
1252
+ const abi = ctx.abiOfCallable(getter);
1253
+ const instance = ctx.classes.get(owner)?.instance;
1254
+ if (abi === null || abi.receiver === null || !instance || representationKey(abi.receiver) !== representationKey(instance))
1255
+ throw refused(`is redeclared as an accessor by ${owner}, whose getter takes no native ${owner} receiver`);
1256
+ const call = `${cppBodyName(getter)}(gea::host::downcastClassRef<${cppClassName(owner)}>(gea_shadowed_receiver))`;
1257
+ const value = operationConversionText(ctx, operation, 'field-read', abi.result, published, call);
1258
+ if (value === null)
1259
+ throw refused(`is redeclared as an accessor by ${owner}, whose getter result this read cannot carry`);
1260
+ return `if (${test}) return ${value};`;
1261
+ });
1262
+ const bound = `${operation.receiver.value}:shadowed`;
1263
+ ctx.valueNames.set(bound, 'gea_shadowed_receiver');
1264
+ const field = fixedFieldReadText(ctx, { ...operation, receiver: { value: bound, representation: receiver } }, fieldName);
1265
+ return (`([&]() -> ${cppTypeOf(published)} { const auto& gea_shadowed_receiver = ${operandText(ctx, operation.receiver)}; ` +
1266
+ `${branches.join(' ')} return ${field}; })()`);
1267
+ };
1268
+ /**
1269
+ * `accessorShadowedFieldReadText`'s write half: OrdinarySet finds the
1270
+ * descendant's accessor before it would create the own data property, so those
1271
+ * allocations call the setter. A definition creates the own property instead.
1272
+ */
1273
+ const accessorShadowedFieldWriteText = (ctx, operation, fieldName, receiverText, valueText) => {
1274
+ const setters = operation.kind === 'set' ? shadowingAccessorHalvesOf(ctx, operation.receiver, fieldName, 'setter', receiverText) : [];
1275
+ if (setters.length === 0)
1276
+ return null;
1277
+ const receiver = operation.receiver.representation;
1278
+ const branches = setters.map(({ body: setter, owner, test }) => {
1279
+ if (setter === null)
1280
+ return `if (${test}) { ${operation.kind === 'set' && operation.strict ? 'gea::host::throwRuntimeError("TypeError", "Cannot set a property that has only a getter");' : ''} }`;
1281
+ const abi = ctx.abiOfCallable(setter);
1282
+ const instance = ctx.classes.get(owner)?.instance;
1283
+ const parameter = abi?.parameters.length === 1 && abi.restFrom === null ? abi.parameters[0].value : null;
1284
+ const argument = parameter === null
1285
+ ? null
1286
+ : alignedValueText(ctx, 'emit-properties.ts:shadowed-setter', operation.value.representation, parameter, valueText);
1287
+ if (abi === null ||
1288
+ abi.receiver === null ||
1289
+ !instance ||
1290
+ representationKey(abi.receiver) !== representationKey(instance) ||
1291
+ argument === null)
1292
+ throw createCppEmitBlockedError(`property-access:${representationKey(receiver)}:set:false`, `field "${fieldName}" is redeclared as an accessor by ${owner}, whose setter has no native entry for this write`);
1293
+ return `if (${test}) { ${cppBodyName(setter)}(gea::host::downcastClassRef<${cppClassName(owner)}>(${receiverText}), ${argument}); }`;
1294
+ });
1295
+ return branches.join(' else ');
1296
+ };
1195
1297
  /** The independent own-property bit for every fixed field on generated storage. */
1196
1298
  const fixedFieldPresenceText = (ctx, receiver, fieldName) => {
1197
1299
  const representation = receiver.representation;
@@ -2010,13 +2112,13 @@ const emitFieldStoreLines = (ctx, lines, operation, label) => {
2010
2112
  ? `(${present} ? (${fieldWritable} && gea::nativeOwnFieldsWritable(${receiverText})) : gea::nativeIsExtensible(${receiverText}))`
2011
2113
  : fieldWritable;
2012
2114
  const store = stores.join(' ');
2013
- if (writable === 'true')
2014
- lines.push(store);
2015
- else if (operation.kind === 'set' && operation.strict) {
2016
- lines.push(`if (!${writable}) gea::host::throwRuntimeError("TypeError", "Cannot assign to read only property"); else { ${store} }`);
2017
- }
2018
- else
2019
- lines.push(`if (${writable}) { ${store} }`);
2115
+ const statement = writable === 'true'
2116
+ ? store
2117
+ : operation.kind === 'set' && operation.strict
2118
+ ? `if (!${writable}) gea::host::throwRuntimeError("TypeError", "Cannot assign to read only property"); else { ${store} }`
2119
+ : `if (${writable}) { ${store} }`;
2120
+ const shadowed = accessorShadowedFieldWriteText(ctx, operation, fieldName, receiverText, rawValueText);
2121
+ lines.push(shadowed === null ? statement : `${shadowed} else { ${statement} }`);
2020
2122
  }
2021
2123
  if (!operation.result)
2022
2124
  return;
@@ -10,6 +10,7 @@ import { fillHostTemplate, hostMemberOf } from './host-members.js';
10
10
  import { isCompleteTemplateObjectCarrier } from '../../../representation/template-object.js';
11
11
  import { cppArrayExtensionStructName, cppConstantLiteral, cppRecordFieldName, cppRecordFieldPresenceName, cppRecordStructName, cppResultTypeOf, cppTypeOf } from '../types.js';
12
12
  import { awaitedRepresentation, coroutineAwaitStatements } from '../prototype/emit-prototype-promise.js';
13
+ import { elementAdaptedCallbackText } from '../prototype/emit-prototype-array.js';
13
14
  import { nativePromiseBaseOf } from '../class-ref-transport.js';
14
15
  import { jsonCallText } from '../emit-json.js';
15
16
  import { dateConstructorCallText } from '../prototype/emit-prototype-date.js';
@@ -1034,7 +1035,20 @@ const arrayFromText = (ctx, operation) => {
1034
1035
  const result = operation.result?.representation;
1035
1036
  const carrier = source.representation;
1036
1037
  const callback = operation.arguments[1];
1037
- const args = [operandText(ctx, source), ...(callback ? [operandText(ctx, callback)] : [])].join(', ');
1038
+ const sourceText = operandText(ctx, source);
1039
+ // `fromCall` invokes the mapper with exactly the C++ element its helper
1040
+ // holds, so a mapper declared wider than that element -- `(_, i) => ...`
1041
+ // over `{ length }`, whose `_: unknown` is a `gea::Value` -- needs the
1042
+ // conversion rendered at this boundary, as `Array.prototype.map`'s does.
1043
+ // The element is the one IR published for that pair
1044
+ // (`ir/host-template-conversions.ts`'s `arrayFromElementOf`).
1045
+ const handed = operation.conversionRecipes?.find((recipe) => recipe.role === 'prototype-callback')?.source;
1046
+ const mapper = !callback
1047
+ ? null
1048
+ : handed
1049
+ ? elementAdaptedCallbackText(ctx, 'from', '23.1.2.1', handed, callback, null, undefined, /* handsArray= */ false)
1050
+ : operandText(ctx, callback);
1051
+ const args = [sourceText, ...(mapper === null ? [] : [mapper])].join(', ');
1038
1052
  // These helpers infer their own element type, so a discarded
1039
1053
  // `Array.from(source, mapper)` -- run for its mapper's effects -- renders
1040
1054
  // too; only the arms below, which build into the result's carrier, need one.
@@ -1080,7 +1094,7 @@ const arrayFromText = (ctx, operation) => {
1080
1094
  if (!callback) {
1081
1095
  throw createCppEmitBlockedError('host-member-call:ArrayConstructor.from', '"Array.from" of a length-only ArrayLike needs a mapper to produce each element');
1082
1096
  }
1083
- return `gea::runtime::array::fromLength(${arrayLikeLengthText(ctx, source)}, ${operandText(ctx, callback)})`;
1097
+ return `gea::runtime::array::fromLength(${arrayLikeLengthText(ctx, source)}, ${mapper})`;
1084
1098
  }
1085
1099
  // A Map's `@@iterator` is `%MapIteratorPrototype%` over its entries
1086
1100
  // (ECMA-262 24.1.3.12), so `Array.from(map)` is `[...map]`: one fresh