@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
@@ -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.
@@ -263,9 +263,11 @@ const referenceIdentityOperators = new Map([
263
263
  ['!=', { kind: 'infix', text: '!=' }]
264
264
  ]);
265
265
  /**
266
- * `-`, `*`, `/`, `%` and `**` over two genuinely dynamic operands (a JS
267
- * library's `this.pages.length * this.pageSize`, both read off an untyped
268
- * `opts`), where the checker typed the result `number`.
266
+ * `-`, `*`, `/`, `%`, `**` and the bitwise and shift operators over two
267
+ * genuinely dynamic operands (a JS library's `this.pages.length *
268
+ * this.pageSize`, both read off an untyped `opts`). Each yields a Number, so
269
+ * the result is that double, converted into whatever carrier the result
270
+ * holds (a field widened to `any` holds it boxed).
269
271
  *
270
272
  * 13.15.3 ApplyStringOrNumericBinaryOperator: ToNumeric the LEFT operand, then
271
273
  * the RIGHT -- in that order, since either may run user code (ToPrimitive) --
@@ -275,25 +277,100 @@ const referenceIdentityOperators = new Map([
275
277
  * BigInt: that aborts by name instead of producing a Number the language
276
278
  * never would.
277
279
  */
278
- const dynamicArithmeticOperators = new Set(['-', '*', '/', '%', '**']);
280
+ const dynamicArithmeticOperators = new Set(['-', '*', '/', '%', '**', '&', '|', '^', '<<', '>>', '>>>']);
279
281
  const dynamicArithmeticText = (ctx, operation, first, second) => {
280
282
  if (!dynamicArithmeticOperators.has(operation.operator))
281
283
  return null;
282
284
  if (first.representation.kind !== 'dynamic' || second.representation.kind !== 'dynamic')
283
285
  return null;
284
286
  const result = operation.result.representation;
285
- if (result.kind !== 'scalar' || result.domain !== 'number')
286
- return null;
287
287
  const numberCarrier = { kind: 'scalar', domain: 'number' };
288
288
  const spelling = binaryOperatorFor(operation.operator, numberCarrier);
289
289
  if (spelling === null)
290
290
  return null;
291
291
  const applied = spelling.kind === 'infix' ? `gea_left_number ${spelling.text} gea_right_number` : `${spelling.text}(gea_left_number, gea_right_number)`;
292
- return (`([&]() -> double { const gea::Value& gea_left = ${operandText(ctx, first)}; const gea::Value& gea_right = ${operandText(ctx, second)}; ` +
292
+ const number = `([&]() -> double { const gea::Value& gea_left = ${operandText(ctx, first)}; const gea::Value& gea_right = ${operandText(ctx, second)}; ` +
293
293
  'if (gea_left.tag() == gea::Value::Tag::BigInt && gea_right.tag() == gea::Value::Tag::BigInt) ' +
294
294
  `gea::detail::refusePayloadMismatch("BigInt ${operation.operator} BigInt is a BigInt, and this cell was typed number"); ` +
295
295
  'const double gea_left_number = gea::dynamicToNumber(gea_left); const double gea_right_number = gea::dynamicToNumber(gea_right); ' +
296
- `return ${applied}; }())`);
296
+ `return ${applied}; }())`;
297
+ if (result.kind === 'scalar' && result.domain === 'number')
298
+ return number;
299
+ // A dynamic result holds the Number boxed: the box is the value itself, not
300
+ // a conversion of a carrier the program wrote.
301
+ if (result.kind === 'dynamic')
302
+ return `gea::Value::box(gea::Value::Tag::Number, ${number})`;
303
+ return alignedValueText(ctx, 'emit.ts:dynamic-arithmetic', numberCarrier, result, number);
304
+ };
305
+ /**
306
+ * The relational and equality operators over a genuinely dynamic operand:
307
+ * ECMA-262's IsLessThan (7.2.13) and IsLooselyEqual (7.2.14) as the runtime
308
+ * implements them over boxes, and IsStrictlyEqual as `Value::strictEquals`.
309
+ * A typed other side is boxed for the comparison -- the box is that value,
310
+ * so no coercion is invented -- and the census names none that would bring
311
+ * a dynamic side to it. Each yields a Boolean, held boxed when the result is
312
+ * dynamic.
313
+ */
314
+ const dynamicComparisonOperators = new Set(['<', '>', '<=', '>=', '===', '!==', '==', '!=']);
315
+ const dynamicComparisonText = (ctx, operation, first, second) => {
316
+ const firstDynamic = first.representation.kind === 'dynamic';
317
+ const secondDynamic = second.representation.kind === 'dynamic';
318
+ if (!firstDynamic && !secondDynamic)
319
+ return null;
320
+ if (!dynamicComparisonOperators.has(operation.operator))
321
+ return null;
322
+ const left = firstDynamic ? operandText(ctx, first) : boxedValueText(ctx, first, 'dynamic comparison');
323
+ const right = secondDynamic ? operandText(ctx, second) : boxedValueText(ctx, second, 'dynamic comparison');
324
+ const condition = (() => {
325
+ switch (operation.operator) {
326
+ case '<':
327
+ return `gea::dynamicIsLessThan(${left}, ${right}, true) == 1`;
328
+ case '>':
329
+ return `gea::dynamicIsLessThan(${right}, ${left}, false) == 1`;
330
+ case '<=':
331
+ return `gea::dynamicIsLessThan(${right}, ${left}, false) == 0`;
332
+ case '>=':
333
+ return `gea::dynamicIsLessThan(${left}, ${right}, true) == 0`;
334
+ case '===':
335
+ return `gea::Value::strictEquals(${left}, ${right})`;
336
+ case '!==':
337
+ return `!gea::Value::strictEquals(${left}, ${right})`;
338
+ case '==':
339
+ return `gea::dynamicLooselyEquals(${left}, ${right})`;
340
+ case '!=':
341
+ return `!gea::dynamicLooselyEquals(${left}, ${right})`;
342
+ default:
343
+ return null;
344
+ }
345
+ })();
346
+ if (condition === null)
347
+ return null;
348
+ const result = operation.result.representation;
349
+ if (result.kind === 'scalar' && result.domain === 'boolean')
350
+ return `(${condition})`;
351
+ if (result.kind === 'dynamic')
352
+ return `gea::Value::box(gea::Value::Tag::Boolean, static_cast<bool>(${condition}))`;
353
+ return alignedValueText(ctx, 'emit.ts:dynamic-comparison', { kind: 'scalar', domain: 'boolean' }, result, `(${condition})`);
354
+ };
355
+ const dynamicUnaryText = (ctx, operation, operand) => {
356
+ if (operand.representation.kind !== 'dynamic')
357
+ return null;
358
+ const number = `gea::dynamicToNumber(${operandText(ctx, operand)})`;
359
+ const applied = operation.operator === '-'
360
+ ? `(-${number})`
361
+ : operation.operator === '+'
362
+ ? number
363
+ : operation.operator === '~'
364
+ ? `gea::bitwiseNot(${number})`
365
+ : null;
366
+ if (applied === null)
367
+ return null;
368
+ const result = operation.result.representation;
369
+ if (result.kind === 'scalar' && result.domain === 'number')
370
+ return applied;
371
+ if (result.kind === 'dynamic')
372
+ return `gea::Value::box(gea::Value::Tag::Number, ${applied})`;
373
+ return alignedValueText(ctx, 'emit.ts:dynamic-unary', { kind: 'scalar', domain: 'number' }, result, applied);
297
374
  };
298
375
  const binaryOperatorFor = (operator, carrier) => {
299
376
  if (carrier.kind === 'string')
@@ -525,6 +602,13 @@ const emitCompute = (ctx, lines, operation) => {
525
602
  }
526
603
  if (operation.operator === 'ToNumeric')
527
604
  return emitToNumericCoercion(ctx, lines, first, operation.result);
605
+ // `-x`, `+x` and `~x` over a dynamic operand: ToNumber (ToPrimitive
606
+ // first) and the Number operator, as the binary operators above do.
607
+ const dynamicUnary = dynamicUnaryText(ctx, operation, first);
608
+ if (dynamicUnary !== null) {
609
+ lines.push(`${defineValue(ctx, operation.result)} = ${dynamicUnary};`);
610
+ return;
611
+ }
528
612
  const spelling = unaryOperatorFor(operation.operator, first.representation);
529
613
  if (!spelling) {
530
614
  throw createCppEmitBlockedError(`runtime-helper:computation:unary:${operation.operator}:${first.representation.kind}`, `unary "${operation.operator}" on a "${first.representation.kind}" carrier has no C++ spelling in this emitter`);
@@ -768,7 +852,11 @@ const emitCompute = (ctx, lines, operation) => {
768
852
  // flag: it is the one case left that boxes an operand this backend could
769
853
  // otherwise have kept native (the `firstDynamic !== secondDynamic` branch
770
854
  // just above, when it applies).
771
- if (ctx.deriver.dynamicFallback &&
855
+ // Two dynamic operands have no native carrier to keep, so the full
856
+ // dispatch is the only spelling there is and needs no opt-in: a field
857
+ // widened to `any` added to another (`x + x` over a dynamic `x`).
858
+ const bothDynamic = first.representation.kind === 'dynamic' && second.representation.kind === 'dynamic';
859
+ if ((ctx.deriver.dynamicFallback || bothDynamic) &&
772
860
  operation.operator === '+' &&
773
861
  (first.representation.kind === 'dynamic' ||
774
862
  second.representation.kind === 'dynamic' ||
@@ -776,7 +864,10 @@ const emitCompute = (ctx, lines, operation) => {
776
864
  second.representation.kind === 'tagged-union')) {
777
865
  const left = boxedValueText(ctx, first, 'dynamic addition');
778
866
  const right = boxedValueText(ctx, second, 'dynamic addition');
779
- const dynamic = { kind: 'dynamic', reason: 'opt-in-fallback' };
867
+ // `gea::dynamicAdd` answers a box, which IS a dynamic result's carrier.
868
+ const dynamic = operation.result.representation.kind === 'dynamic' && !ctx.deriver.dynamicFallback
869
+ ? operation.result.representation
870
+ : { kind: 'dynamic', reason: 'opt-in-fallback' };
780
871
  const text = alignedValueText(ctx, 'emit.ts:738', dynamic, operation.result.representation, `gea::dynamicAdd(${left}, ${right})`);
781
872
  if (text === null)
782
873
  throw createCppEmitBlockedError(`conversion:dynamic->${representationKey(operation.result.representation)}`, 'dynamic addition result has no checked conversion');
@@ -862,6 +953,11 @@ const emitCompute = (ctx, lines, operation) => {
862
953
  return;
863
954
  }
864
955
  }
956
+ const dynamicComparison = dynamicComparisonText(ctx, operation, first, second);
957
+ if (dynamicComparison !== null) {
958
+ lines.push(`${defineValue(ctx, operation.result)} = ${dynamicComparison};`);
959
+ return;
960
+ }
865
961
  if (representationKey(first.representation) !== representationKey(second.representation)) {
866
962
  throw createCppEmitBlockedError(`conversion:${representationKey(first.representation)}->${representationKey(second.representation)}`, `binary "${operation.operator}" mixes a "${first.representation.kind}" and a "${second.representation.kind}" carrier, ` +
867
963
  'and the census names no coercion that brings them together');
@@ -246,6 +246,16 @@ const valuesOfView = (ctx, operation, view) => {
246
246
  throw createCppEmitBlockedError('host-member-call:Object.values', `"Object.values" of a known shape mints an array, and this call's result carries ` +
247
247
  `"${result === undefined ? 'nothing' : representationKey(result)}"`);
248
248
  }
249
+ if (!classOwnKeysAreStatic(ctx, view.representation)) {
250
+ const walked = creationOrderedOwnCopyText(ctx, view, 'values', (_key, value, walkCtx) => {
251
+ const converted = alignedValueText(walkCtx, 'host/emit-host-object.ts:values-of-class-instance', dynamicCarrier, result.element, value);
252
+ return converted === null ? null : `__gea_values.push_back(${converted});`;
253
+ }, null, true);
254
+ if (walked === null)
255
+ return refuseClassInstanceWalk('values', view.representation);
256
+ return (`([&]() { ${classWalkProtocolAssertion(view)} std::vector<${cppTypeOf(result.element)}> __gea_values; ${walked}; ` +
257
+ `return gea::detail::hostArrayResult(std::move(__gea_values)); })()`);
258
+ }
249
259
  const element = representationKey(result.element);
250
260
  const ordered = ownKeyFields(view);
251
261
  // A field whose carrier differs from the element (`{ on: true, none: 'none' }`
@@ -448,6 +458,16 @@ const entriesOfView = (ctx, operation, view) => {
448
458
  return (`gea::host::ObjectConstructor::entriesOf<${cppTypeOf(entry.element)}>(${view.receiver}, ` +
449
459
  `[](std::string __gea_key, ${cppTypeOf(view.value)} __gea_value) { ${entryText(entry, '__gea_key', value)} })`);
450
460
  }
461
+ if (!classOwnKeysAreStatic(ctx, view.representation)) {
462
+ const walked = creationOrderedOwnCopyText(ctx, view, 'entries', (key, value, walkCtx) => {
463
+ const converted = alignedValueText(walkCtx, 'host/emit-host-object.ts:entries-of-class-instance', dynamicCarrier, entry.value, value);
464
+ return converted === null ? null : `__gea_entries.push_back([&]() { ${entryText(entry, key, converted)} }());`;
465
+ }, null, true);
466
+ if (walked === null)
467
+ return refuseClassInstanceWalk('entries', view.representation);
468
+ return (`([&]() { ${classWalkProtocolAssertion(view)} std::vector<${cppTypeOf(entry.element)}> __gea_entries; ${walked}; ` +
469
+ `return gea::detail::hostArrayResult(std::move(__gea_entries)); })()`);
470
+ }
451
471
  const ordered = ownKeyFields(view);
452
472
  const entryOf = (field) => {
453
473
  const read = getOwnValue(ctx, view, field);
@@ -476,7 +496,54 @@ const entriesOfView = (ctx, operation, view) => {
476
496
  return (`([&]() { std::vector<${cppTypeOf(entry.element)}> __gea_entries; ${walked} ` +
477
497
  `return gea::detail::hostArrayResult(std::move(__gea_entries)); })()`);
478
498
  };
479
- const creationOrderedOwnCopyText = (ctx, view, destination, each, assigned = null) => {
499
+ /**
500
+ * Whether a class instance's own keys are exactly the field list its carrier's
501
+ * shape names, in that order, so the static arms of `values` and `entries`
502
+ * may list them.
503
+ *
504
+ * A `class-ref` names the class its handle is DECLARED at, and the object
505
+ * behind it can be any subclass: a `Material`-typed handle holding a
506
+ * `DashedMaterial` owns `dashSize`, which no struct the handle can name has.
507
+ * Its carrier's shape need not even be the class's own -- the struct is
508
+ * rendered from the class's instance shape, a use site's handle may carry a
509
+ * wider one (`model.ts`'s `class-ref`), and listing that shape's fields
510
+ * read members the struct does not have. And with a base class, the base's
511
+ * fields are created first while the shape lists the derived class's own
512
+ * first. Each of those is a run-time or chain-order fact the struct's own
513
+ * field dispatcher already answers (`nativeEnumerableStringKeys`), which is
514
+ * how `keys` enumerates every shared object, so only a class with no base,
515
+ * no subclass and its own instance shape keeps the static list.
516
+ */
517
+ const classOwnKeysAreStatic = (ctx, representation) => {
518
+ if (representation.kind !== 'class-ref')
519
+ return true;
520
+ if (representation.ancestors.length > 0 || representation.nativeBase !== undefined)
521
+ return false;
522
+ const layout = ctx.classes.get(representation.declaration);
523
+ const instance = layout?.instance;
524
+ if (layout === undefined || layout.base !== null || instance === null || instance === undefined)
525
+ return false;
526
+ if (!('shapeId' in instance) || instance.shapeId !== representation.shapeId)
527
+ return false;
528
+ for (const other of ctx.classes.values())
529
+ if (other.base === representation.declaration)
530
+ return false;
531
+ return true;
532
+ };
533
+ /**
534
+ * The runtime walk is the only arm a class instance gets, and without the
535
+ * struct's property protocol it answers false and copies nothing -- an empty
536
+ * array where the instance has keys. Stated to the C++ compiler, so that case
537
+ * cannot build at all.
538
+ */
539
+ const classWalkProtocolAssertion = (view) => `static_assert(gea::detail::NativeFieldTable<typename std::remove_cvref_t<decltype(${view.receiver})>::element_type>, ` +
540
+ '"the own properties of a class instance are walked through its property protocol");';
541
+ const refuseClassInstanceWalk = (member, representation) => {
542
+ throw createCppEmitBlockedError(`host-member-call:Object.${member}`, `"Object.${member}" of a "${representationKey(representation)}" handle enumerates whatever class the instance really is, ` +
543
+ "which only the runtime's creation-order walk can see, and no conversion from its dynamic values into this call's " +
544
+ 'result was admitted for that walk');
545
+ };
546
+ const creationOrderedOwnCopyText = (ctx, view, destination, each, assigned = null, always = false) => {
480
547
  const indexed = indexedRecordViewOf(ctx.deriver, view.representation);
481
548
  const ownership = indexed !== null ? indexed.ownership : ownershipOfGeneratedCarrier(view.representation);
482
549
  if (ownership !== 'shared-refcount')
@@ -506,7 +573,7 @@ const creationOrderedOwnCopyText = (ctx, view, destination, each, assigned = nul
506
573
  return (`gea::${assigned.orderless === true ? 'assignOwnPropertiesUnorderedWith' : 'assignOwnPropertiesInCreationOrderWith'}(${view.receiver}, ${assigned.target}, ` +
507
574
  `[&](const std::string& __gea_ordered_key, const gea::Value& __gea_ordered_value) { ${body} }, ${assigned.staticCopy})`);
508
575
  return (`gea::copyOwnPropertiesInCreationOrder(${view.receiver}, ` +
509
- `[&](const std::string& __gea_ordered_key, const gea::Value& __gea_ordered_value) { ${body} }${indexed !== null ? ', true' : ''})`);
576
+ `[&](const std::string& __gea_ordered_key, const gea::Value& __gea_ordered_value) { ${body} }${indexed !== null || always ? ', true' : ''})`);
510
577
  };
511
578
  /**
512
579
  * A property key argument, as `gea::PropertyKey`.
@@ -256,6 +256,7 @@ export declare const enumerationOrdered: <T>(entries: readonly T[], keyOf: (entr
256
256
  * this file did not name is left exactly as written.
257
257
  */
258
258
  export declare const withUnreadParametersUnnamed: (declaration: string, body: readonly string[]) => string;
259
+ export declare const switchedByKeyLength: (body: readonly string[]) => readonly string[];
259
260
  /**
260
261
  * The C++ storage one field of this struct occupies.
261
262
  *
@@ -1444,7 +1444,7 @@ const keyByteLengthOfBranch = (line) => {
1444
1444
  * it skips.
1445
1445
  */
1446
1446
  const switchedKeyBranches = 6;
1447
- const switchedByKeyLength = (body) => {
1447
+ export const switchedByKeyLength = (body) => {
1448
1448
  const out = [];
1449
1449
  let run = [];
1450
1450
  const flush = () => {
@@ -15,7 +15,7 @@ import { nativePromiseBaseInitializeStatements } from './native-promise-base.js'
15
15
  import { classFieldStorageOwnerOf, classMemberOf, classMethodOverrideOf } from '../../projection/fields.js';
16
16
  import { balanceCppUnits, chunkCppItems, cppChunkFileName, cppUnitByteBudget } from './balanced-units.js';
17
17
  import { readonlyBorrowFormalsOf } from '../../ir/borrowed-call-arguments.js';
18
- import { stableBorrowEntryOf } from './borrowed-call-entry.js';
18
+ import { borrowForwardedArgumentsOf, stableBorrowEntryOf, withoutDyingArguments } from './borrowed-call-entry.js';
19
19
  import { programFactsOf } from '../../ir/program-facts.js';
20
20
  import { integrityRestrictionsOf } from '../../ir/integrity-restrictions.js';
21
21
  import { keyOrderObservationOf, nothingProvenUnobserved } from '../../ir/key-order-observation.js';
@@ -752,7 +752,7 @@ const signatureOf = (body, captures, narrowed = new Set(), narrowedResult = fals
752
752
  const formals = bodyFormalsOf(cppEnvironmentStructOf(captures, body.sourceOwner), effectiveAbi, admission, narrowed, borrowsReceiver(body), borrowed, isCoroutineBody(body));
753
753
  return `${result} ${name}(${formals.join(', ')})`;
754
754
  };
755
- const thunkOf = (body, captures, narrowed, narrowedResult, linkage, taskResult = false) => {
755
+ const thunkOf = (body, captures, narrowed, narrowedResult, linkage, taskResult = false, stableEntry = undefined) => {
756
756
  if (!body.abi)
757
757
  return null;
758
758
  const abi = body.abi;
@@ -783,7 +783,12 @@ const thunkOf = (body, captures, narrowed, narrowedResult, linkage, taskResult =
783
783
  : admission.kind === 'ok' && admission.layout.receiver !== null
784
784
  ? [`${cppEnvironmentLocalName}->${cppCaptureReceiverFieldName}`]
785
785
  : [];
786
- const call = `${cppBodyName(body.sourceOwner)}(${[
786
+ // The thunk's by-value formals are slots of its own frame that nothing else
787
+ // can name, so they are stable actuals for the borrowed entry: entering it
788
+ // directly binds them in place, where the owning entry moved each one into a
789
+ // formal of its own and released the emptied shell on the way out.
790
+ const borrowedEntry = stableEntry !== undefined && !hasEnvironment && !isCoroutineBody(body) ? stableEntry : undefined;
791
+ const call = `${borrowedEntry?.name ?? cppBodyName(body.sourceOwner)}(${[
787
792
  ...(hasEnvironment ? [isCoroutineBody(body) ? `*${cppEnvironmentLocalName}` : cppEnvironmentLocalName] : []),
788
793
  ...receiverActual,
789
794
  // The thunk's own formals stay the ABI's, so the carrier's function-pointer
@@ -791,7 +796,9 @@ const thunkOf = (body, captures, narrowed, narrowedResult, linkage, taskResult =
791
796
  // boundary where the two spellings meet.
792
797
  ...abi.parameters.map((parameter, ordinal) => narrowed.has(ordinal)
793
798
  ? `static_cast<${cppNarrowedIntegerType}>(${cppFormalName(ordinal)})`
794
- : `std::forward<${cppAbiParameterType(parameter)}>(${cppFormalName(ordinal)})`)
799
+ : borrowedEntry?.formals.has(ordinal)
800
+ ? cppFormalName(ordinal)
801
+ : `std::forward<${cppAbiParameterType(parameter)}>(${cppFormalName(ordinal)})`)
795
802
  ].join(', ')})`;
796
803
  // The thunk's own result stays the ABI's, so the carrier's function-pointer
797
804
  // type is unchanged; a narrowed body result converts back here.
@@ -1938,22 +1945,45 @@ const renderTranslationUnitSession = (input) => {
1938
1945
  const physicalCounts = new Map();
1939
1946
  for (const body of input.bodies)
1940
1947
  physicalCounts.set(String(body.sourceOwner), (physicalCounts.get(String(body.sourceOwner)) ?? 0) + 1);
1948
+ const stableEntryOf = (body, dying) => isRegionId(body.sourceOwner) || constructorBodies.has(String(body.sourceOwner))
1949
+ ? null
1950
+ : stableBorrowEntryOf(body, body.sourceOwner, (declaration) => {
1951
+ const placement = input.placements.get(declaration);
1952
+ return placement?.storage.kind === 'local' && placement.storage.owner === body.sourceOwner && !captures.isBoxed(declaration)
1953
+ ? placement.representation
1954
+ : null;
1955
+ }, formalsBorrowedIn(body.sourceOwner), dying, {
1956
+ captureFree: captures.of(body.sourceOwner).kind === 'none',
1957
+ synchronous: !isCoroutineBody(body),
1958
+ singleBody: physicalCounts.get(String(body.sourceOwner)) === 1,
1959
+ narrowedNumericAbi: formalsNarrowedIn(body.sourceOwner).size > 0 || resultNarrowedIn(body.sourceOwner)
1960
+ });
1961
+ // A formal handed on as the last use of its cell is "dying", and a dying
1962
+ // read keeps its formal owning so the read can move. Into a position the
1963
+ // callee's own borrowed entry takes by reference, nothing moves: the entry
1964
+ // binds the slot in place. So such reads stop counting as dying, which can
1965
+ // admit the caller's formal to its own entry, which can in turn release the
1966
+ // read that forwards IT -- a fixed point, growing until no entry gains a
1967
+ // formal. A chain of setters forwarding one union or handle down to a
1968
+ // read-only leaf then passes it by reference at every level instead of
1969
+ // moving it once per level.
1970
+ let borrowDying = dyingArguments;
1971
+ for (;;) {
1972
+ const entries = new Map();
1973
+ for (const body of input.bodies) {
1974
+ const entry = stableEntryOf(body, borrowDying);
1975
+ if (entry)
1976
+ entries.set(cppBodyName(body.sourceOwner), entry);
1977
+ }
1978
+ const forwarded = borrowForwardedArgumentsOf(input.bodies, entries, dyingArguments);
1979
+ if ([...forwarded].every((value) => !borrowDying.has(value)))
1980
+ break;
1981
+ borrowDying = withoutDyingArguments(dyingArguments, forwarded);
1982
+ }
1941
1983
  for (const body of input.bodies) {
1942
1984
  if (isRegionId(body.sourceOwner))
1943
1985
  continue;
1944
- const entry = constructorBodies.has(String(body.sourceOwner))
1945
- ? null
1946
- : stableBorrowEntryOf(body, body.sourceOwner, (declaration) => {
1947
- const placement = input.placements.get(declaration);
1948
- return placement?.storage.kind === 'local' && placement.storage.owner === body.sourceOwner && !captures.isBoxed(declaration)
1949
- ? placement.representation
1950
- : null;
1951
- }, formalsBorrowedIn(body.sourceOwner), dyingArguments, {
1952
- captureFree: captures.of(body.sourceOwner).kind === 'none',
1953
- synchronous: !isCoroutineBody(body),
1954
- singleBody: physicalCounts.get(String(body.sourceOwner)) === 1,
1955
- unchangedNumericAbi: formalsNarrowedIn(body.sourceOwner).size === 0 && !resultNarrowedIn(body.sourceOwner)
1956
- });
1986
+ const entry = stableEntryOf(body, borrowDying);
1957
1987
  if (entry)
1958
1988
  stableBorrowEntries.set(cppBodyName(body.sourceOwner), entry);
1959
1989
  if (process.env.GEA_BORROW_DEBUG) {
@@ -1965,7 +1995,7 @@ const renderTranslationUnitSession = (input) => {
1965
1995
  return placement?.storage.kind === 'local' && placement.storage.owner === body.sourceOwner && !captures.isBoxed(declaration)
1966
1996
  ? placement.representation
1967
1997
  : null;
1968
- }, dyingArguments).size
1998
+ }, borrowDying).size
1969
1999
  : 0;
1970
2000
  const flags = [
1971
2001
  `entry=${entry ? 'yes' : 'no'}`,
@@ -1988,13 +2018,18 @@ const renderTranslationUnitSession = (input) => {
1988
2018
  const signatures = input.bodies.flatMap((body) => {
1989
2019
  const original = `${signatureOf(body, captures, formalsNarrowedIn(body.sourceOwner), resultNarrowedIn(body.sourceOwner), formalsBorrowedIn(body.sourceOwner), cppBodyName(body.sourceOwner), taskResultOf(body))};`;
1990
2020
  const entry = stableBorrowEntries.get(cppBodyName(body.sourceOwner));
1991
- return entry === undefined ? [original] : [original, `${signatureOf(body, captures, new Set(), false, entry.formals, entry.name)};`];
2021
+ return entry === undefined
2022
+ ? [original]
2023
+ : [
2024
+ original,
2025
+ `${signatureOf(body, captures, formalsNarrowedIn(body.sourceOwner), resultNarrowedIn(body.sourceOwner), entry.formals, entry.name)};`
2026
+ ];
1992
2027
  });
1993
2028
  const thunks = new Map();
1994
2029
  // The functions whose minted values publish a `[[Construct]]` entry.
1995
2030
  const constructEntries = new Set();
1996
2031
  for (const body of input.bodies) {
1997
- const thunk = thunkOf(body, captures, formalsNarrowedIn(body.sourceOwner), resultNarrowedIn(body.sourceOwner), linkage, taskResultOf(body));
2032
+ const thunk = thunkOf(body, captures, formalsNarrowedIn(body.sourceOwner), resultNarrowedIn(body.sourceOwner), linkage, taskResultOf(body), isRegionId(body.sourceOwner) ? undefined : stableBorrowEntries.get(cppBodyName(body.sourceOwner)));
1998
2033
  if (thunk)
1999
2034
  thunks.set(body, thunk);
2000
2035
  if (thunk?.publishesConstruct && !isRegionId(body.sourceOwner))
@@ -2074,7 +2109,7 @@ const renderTranslationUnitSession = (input) => {
2074
2109
  // The formals this body's signature takes by reference: their objects
2075
2110
  // outlive the call, which `emit.ts`'s stable field reads rely on.
2076
2111
  const borrowed = stableEntry?.formals ?? formalsBorrowedIn(body.sourceOwner);
2077
- const sections = emitBody(promiseView ?? body, input.placements, input.classes, hosts, deriver, input.wellKnownSymbols, captures, symbolKeys, templateObjects, directCallables, virtuals.dispatched, narrowedStorage.factsOf(body.sourceOwner), formalsNarrowedIn(body.sourceOwner), repeatedConstructors, dyingArguments, instantiation, (callable) => abiByBody.get(String(callable)) ?? null, functionFacts, constructEntries, hostMethodAliases, callableMemberCandidates, callableFlowCandidates.get(body.owner) ?? new Map(), borrowableMemberBodies, stableBorrowEntries, printerDrift, input.conversions, selectionHelpers, callableIdentityDemand, nativeIntegrityRestricted, fixedFieldStateConstant, definitionCells, constructionOnlyFields, keyOrderUnobserved, debugSource, borrowed, asyncResults.taskResults, programSite.conversionIsCertified, input.programConversionRecipes, structs.classIndexProtocols);
2112
+ const sections = emitBody(promiseView ?? body, input.placements, input.classes, hosts, deriver, input.wellKnownSymbols, captures, symbolKeys, templateObjects, directCallables, virtuals.dispatched, narrowedStorage.factsOf(body.sourceOwner), formalsNarrowedIn(body.sourceOwner), repeatedConstructors, borrowDying, instantiation, (callable) => abiByBody.get(String(callable)) ?? null, functionFacts, constructEntries, hostMethodAliases, callableMemberCandidates, callableFlowCandidates.get(body.owner) ?? new Map(), borrowableMemberBodies, stableBorrowEntries, printerDrift, input.conversions, selectionHelpers, callableIdentityDemand, nativeIntegrityRestricted, fixedFieldStateConstant, definitionCells, constructionOnlyFields, keyOrderUnobserved, debugSource, borrowed, asyncResults.taskResults, programSite.conversionIsCertified, input.programConversionRecipes, structs.classIndexProtocols);
2078
2113
  const commonJsScope = [
2079
2114
  ...coroutineEnvironmentPrologueOf(promiseView ?? body, captures),
2080
2115
  ...(commonJsOwner === null || commonJsOwner.nativeRecord
@@ -2098,7 +2133,9 @@ const renderTranslationUnitSession = (input) => {
2098
2133
  ...(stableEntry === undefined
2099
2134
  ? []
2100
2135
  : [
2101
- plain(`${signatureOf(body, captures, new Set(), false, formalsBorrowedIn(body.sourceOwner))} {`),
2136
+ // The wrapper keeps the declared signature's narrowed integer formals and
2137
+ // result, so it forwards them to the entry without a conversion.
2138
+ plain(`${signatureOf(body, captures, formalsNarrowedIn(body.sourceOwner), resultNarrowedIn(body.sourceOwner), formalsBorrowedIn(body.sourceOwner))} {`),
2102
2139
  plain(
2103
2140
  // The stable entry's own signature always states `gea_this`
2104
2141
  // first when the body has a receiver (`formalsOf` spells it