@geastack/compiler 1.0.48 → 1.0.62

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 (127) hide show
  1. package/README.md +57 -19
  2. package/dist/cli.js +2 -1
  3. package/dist/compiler.d.ts +1 -1
  4. package/dist/compiler.js +13 -6
  5. package/dist/conversion/derive.js +5 -0
  6. package/dist/conversion/native-field-view.d.ts +7 -0
  7. package/dist/conversion/native-field-view.js +50 -0
  8. package/dist/conversion/native-record-products.js +1 -0
  9. package/dist/conversion/native-view-origins.d.ts +1 -1
  10. package/dist/conversion/native-view-origins.js +5 -4
  11. package/dist/conversion/nodes.d.ts +9 -0
  12. package/dist/conversion/nodes.js +18 -0
  13. package/dist/conversion/record-view.d.ts +25 -1
  14. package/dist/conversion/record-view.js +61 -2
  15. package/dist/conversion/structural-plan.js +7 -6
  16. package/dist/ir/borrowed-field-reads.d.ts +30 -0
  17. package/dist/ir/borrowed-field-reads.js +218 -0
  18. package/dist/ir/borrowed-window-cells.d.ts +35 -0
  19. package/dist/ir/borrowed-window-cells.js +117 -0
  20. package/dist/ir/call-dispatch.js +21 -4
  21. package/dist/ir/callable-class-flow.js +269 -43
  22. package/dist/ir/captures.js +18 -1
  23. package/dist/ir/certify.js +14 -1
  24. package/dist/ir/construction-only-fields.d.ts +15 -1
  25. package/dist/ir/construction-only-fields.js +71 -3
  26. package/dist/ir/dead-logical-merge.d.ts +4 -0
  27. package/dist/ir/dead-logical-merge.js +89 -18
  28. package/dist/ir/dense-loops.d.ts +38 -4
  29. package/dist/ir/dense-loops.js +112 -17
  30. package/dist/ir/dense-read-windows.d.ts +42 -0
  31. package/dist/ir/dense-read-windows.js +137 -0
  32. package/dist/ir/facts.d.ts +12 -0
  33. package/dist/ir/facts.js +18 -2
  34. package/dist/ir/field-read-reuse.d.ts +71 -0
  35. package/dist/ir/field-read-reuse.js +430 -0
  36. package/dist/ir/hoist.d.ts +19 -2
  37. package/dist/ir/hoist.js +143 -24
  38. package/dist/ir/lower-narrow.js +19 -1
  39. package/dist/ir/model.d.ts +19 -0
  40. package/dist/ir/native-field-view-domains.d.ts +12 -2
  41. package/dist/ir/native-field-view-domains.js +51 -15
  42. package/dist/ir/native-field-view-facts.js +5 -2
  43. package/dist/ir/native-method-frames.js +15 -2
  44. package/dist/ir/plain-field-read.d.ts +31 -0
  45. package/dist/ir/plain-field-read.js +51 -0
  46. package/dist/ir/program-facts.d.ts +14 -0
  47. package/dist/ir/program-facts.js +85 -2
  48. package/dist/ir/proven-branches.js +8 -1
  49. package/dist/ir/publish-conversion-recipes.js +5 -1
  50. package/dist/ir/short-circuit-threading.d.ts +12 -4
  51. package/dist/ir/short-circuit-threading.js +124 -12
  52. package/dist/ir/stable-cell-reads.d.ts +24 -1
  53. package/dist/ir/stable-cell-reads.js +65 -42
  54. package/dist/ir/write-effects.d.ts +42 -0
  55. package/dist/ir/write-effects.js +208 -0
  56. package/dist/plugins/gea/contract.d.ts +3 -2
  57. package/dist/plugins/gea/contract.js +3 -1
  58. package/dist/plugins/gea/host.d.ts +7 -2
  59. package/dist/plugins/gea/host.js +25 -5
  60. package/dist/project-preparation.d.ts +11 -0
  61. package/dist/project-preparation.js +44 -0
  62. package/dist/projection/classes.d.ts +8 -0
  63. package/dist/projection/classes.js +112 -12
  64. package/dist/projection/dispatch.d.ts +24 -4
  65. package/dist/projection/dispatch.js +71 -2
  66. package/dist/projection/fields.js +2 -2
  67. package/dist/representation/model.d.ts +3 -0
  68. package/dist/representation/model.js +3 -0
  69. package/dist/representation/value-records.js +22 -0
  70. package/dist/semantics/frontend-timing.d.ts +9 -0
  71. package/dist/semantics/frontend-timing.js +43 -2
  72. package/dist/semantics/frontend.js +103 -7
  73. package/dist/semantics/model/operations.d.ts +7 -0
  74. package/dist/semantics/normalize/binding-fixpoint.js +7 -2
  75. package/dist/semantics/normalize/callable-data-write.js +6 -2
  76. package/dist/semantics/normalize/field-bindings.js +151 -111
  77. package/dist/semantics/normalize/flow/callable-reach.js +27 -0
  78. package/dist/semantics/normalize/flow/component-solver.js +23 -5
  79. package/dist/semantics/normalize/flow/source-record-data.js +6 -2
  80. package/dist/semantics/normalize/flow/source-value-session.d.ts +13 -0
  81. package/dist/semantics/normalize/flow/source-value-session.js +207 -65
  82. package/dist/semantics/normalize/global-host-mutations.js +162 -1
  83. package/dist/semantics/normalize/parameter-bindings.js +16 -1
  84. package/dist/semantics/normalize/producers/class-lifecycle.js +2 -1
  85. package/dist/semantics/normalize/producers/erasure.js +13 -8
  86. package/dist/semantics/subclass-member-overlay-transform.d.ts +3 -2
  87. package/dist/semantics/subclass-member-overlay-transform.js +416 -316
  88. package/dist/semantics/typescript-tsgo.d.ts +20 -0
  89. package/dist/semantics/typescript-tsgo.js +832 -0
  90. package/dist/semantics/typescript.d.ts +0 -9
  91. package/dist/semantics/typescript.js +4 -1
  92. package/dist/targets/cpp/borrowed-call-entry.d.ts +9 -0
  93. package/dist/targets/cpp/borrowed-call-entry.js +12 -2
  94. package/dist/targets/cpp/captures.js +4 -0
  95. package/dist/targets/cpp/class-properties/computed-method-value.d.ts +1 -1
  96. package/dist/targets/cpp/class-properties/computed-method-value.js +17 -7
  97. package/dist/targets/cpp/class-properties/emit-class-properties.d.ts +8 -0
  98. package/dist/targets/cpp/class-properties/emit-class-properties.js +62 -2
  99. package/dist/targets/cpp/class-properties/native-method-read.js +12 -1
  100. package/dist/targets/cpp/conversions.js +1 -0
  101. package/dist/targets/cpp/emit-arrays.d.ts +5 -0
  102. package/dist/targets/cpp/emit-arrays.js +60 -10
  103. package/dist/targets/cpp/emit-binding-reference.d.ts +19 -6
  104. package/dist/targets/cpp/emit-binding-reference.js +26 -8
  105. package/dist/targets/cpp/emit-bindings.js +22 -0
  106. package/dist/targets/cpp/emit-callable.js +133 -16
  107. package/dist/targets/cpp/emit-carrier-members.d.ts +6 -0
  108. package/dist/targets/cpp/emit-carrier-members.js +24 -2
  109. package/dist/targets/cpp/emit-context.d.ts +97 -1
  110. package/dist/targets/cpp/emit-context.js +52 -0
  111. package/dist/targets/cpp/emit-equality.js +3 -0
  112. package/dist/targets/cpp/emit-narrowing.js +9 -0
  113. package/dist/targets/cpp/emit-native-field-view.d.ts +24 -0
  114. package/dist/targets/cpp/emit-native-field-view.js +87 -8
  115. package/dist/targets/cpp/emit-properties.js +139 -16
  116. package/dist/targets/cpp/emit-record-view.js +49 -22
  117. package/dist/targets/cpp/emit-return.js +5 -1
  118. package/dist/targets/cpp/emit-tonumber.js +4 -1
  119. package/dist/targets/cpp/emit-union-properties.js +1 -1
  120. package/dist/targets/cpp/emit.d.ts +4 -1
  121. package/dist/targets/cpp/emit.js +148 -6
  122. package/dist/targets/cpp/reactive-dependencies.js +100 -28
  123. package/dist/targets/cpp/translation-unit.js +71 -17
  124. package/dist/targets/cpp/virtual-methods.d.ts +2 -2
  125. package/dist/targets/cpp/virtual-methods.js +11 -3
  126. package/package.json +1 -1
  127. package/src/targets/cpp/runtime/gea_runtime.h +400 -21
@@ -1,12 +1,3 @@
1
1
  import type TypeScript from 'typescript';
2
- /**
3
- * The one runtime load of TypeScript, behind the package's `#typescript`
4
- * import (whose `types` condition is TypeScript's own declarations, so every
5
- * importer sees `ts.Node`, `ts.SyntaxKind` and the rest unchanged). Loaded with
6
- * `require` rather than `import`: Node's ESM loader reads a CommonJS module's
7
- * source to find its export names and keeps that copy beside the one the
8
- * module was compiled from -- for TypeScript's 8.7 MB `typescript.js`, about
9
- * 17 MB of RSS for the whole compile.
10
- */
11
2
  declare const ts: typeof TypeScript;
12
3
  export default ts;
@@ -1,4 +1,5 @@
1
1
  import { createRequire } from 'node:module';
2
+ import { tsgoTypeScript } from './typescript-tsgo.js';
2
3
  /**
3
4
  * The one runtime load of TypeScript, behind the package's `#typescript`
4
5
  * import (whose `types` condition is TypeScript's own declarations, so every
@@ -8,5 +9,7 @@ import { createRequire } from 'node:module';
8
9
  * module was compiled from -- for TypeScript's 8.7 MB `typescript.js`, about
9
10
  * 17 MB of RSS for the whole compile.
10
11
  */
11
- const ts = createRequire(import.meta.url)('typescript');
12
+ const loaded = createRequire(import.meta.url)('typescript');
13
+ // EXPERIMENT: `GEA_TS_BACKEND=tsgo` puts typescript-go's checker behind the same program.
14
+ const ts = process.env['GEA_TS_BACKEND'] === 'tsgo' ? tsgoTypeScript(loaded) : loaded;
12
15
  export default ts;
@@ -18,9 +18,18 @@ export interface StableBorrowEntry {
18
18
  * must keep the thunk, which converts at that boundary.
19
19
  */
20
20
  readonly narrowedNumericAbi: boolean;
21
+ /**
22
+ * Whether the body is a closure, whose entry takes its environment pointer
23
+ * first (as its owning entry does). Only a call that has the environment to
24
+ * pass may enter it: the closure's own thunk, its owning wrapper, and a call
25
+ * through the callable that holds it (`callKnownBorrowedEnvironment`).
26
+ */
27
+ readonly environment: boolean;
21
28
  }
22
29
  export declare const stableBorrowEntryOf: (body: IrBody, owner: FunctionId, privateCell: PrivateBorrowCell, originalBorrowed: ReadonlySet<number>, dyingArguments: ReadonlySet<IrValueId>, admission: {
30
+ /** Capture-free, or a closure whose plain environment the borrowed body takes first (`environment`). */
23
31
  readonly captureFree: boolean;
32
+ readonly environment: boolean;
24
33
  readonly synchronous: boolean;
25
34
  readonly singleBody: boolean;
26
35
  readonly narrowedNumericAbi: boolean;
@@ -41,7 +41,14 @@ export const stableBorrowEntryOf = (body, owner, privateCell, originalBorrowed,
41
41
  // Never revoke an established, stronger effect-based borrow proof.
42
42
  for (const ordinal of originalBorrowed)
43
43
  formals.add(ordinal);
44
- return { owner, name: `${cppBodyName(owner)}_stable_borrow`, abi, formals, narrowedNumericAbi: admission.narrowedNumericAbi };
44
+ return {
45
+ owner,
46
+ name: `${cppBodyName(owner)}_stable_borrow`,
47
+ abi,
48
+ formals,
49
+ narrowedNumericAbi: admission.narrowedNumericAbi,
50
+ environment: admission.environment
51
+ };
45
52
  };
46
53
  /** A private caller slot survives arbitrary program re-entry. All extra
47
54
  * reference formals must bind such slots; otherwise use the existing owning
@@ -122,7 +129,10 @@ export const borrowForwardedArgumentsOf = (bodies, entries, dyingArguments) => {
122
129
  continue;
123
130
  const target = operation.target;
124
131
  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)));
132
+ const callees = targets.map((functionId) => {
133
+ const entry = entries.get(cppBodyName(functionId));
134
+ return entry?.environment ? undefined : entry;
135
+ });
126
136
  if (callees.length === 0)
127
137
  continue;
128
138
  // A union dispatch enters one arm's body, so every arm must take the position by reference.
@@ -376,6 +376,7 @@ const frameIdentitiesOf = (bodies, frames, admissions, accessorEnvironmentOwners
376
376
  export const buildCaptureIndex = (bodies, placements, capturingAccessors = new Set()) => {
377
377
  const boxedDeclarations = new Set();
378
378
  const requiresEarlyBoxDeclarations = new Set();
379
+ const settledBoxes = new Set();
379
380
  const capturedDeclarations = new Set();
380
381
  const bodyBySourceOwner = new Map();
381
382
  for (const body of bodies) {
@@ -384,6 +385,8 @@ export const buildCaptureIndex = (bodies, placements, capturingAccessors = new S
384
385
  boxedDeclarations.add(declaration);
385
386
  for (const declaration of body.facts?.requiresEarlyBox ?? [])
386
387
  requiresEarlyBoxDeclarations.add(declaration);
388
+ for (const declaration of body.facts?.settledBoxes ?? [])
389
+ settledBoxes.add(declaration);
387
390
  for (const declaration of body.facts?.capturedDeclarations ?? [])
388
391
  capturedDeclarations.add(declaration);
389
392
  }
@@ -475,6 +478,7 @@ export const buildCaptureIndex = (bodies, placements, capturingAccessors = new S
475
478
  // A dissolved group's members are read by their own closures through the frame.
476
479
  isCaptured: (declaration) => capturedDeclarations.has(declaration) || frameMemberOf(declaration) !== null,
477
480
  requiresEarlyBox: (declaration) => requiresEarlyBoxDeclarations.has(declaration),
481
+ isSettledBox: (declaration) => settledBoxes.has(declaration),
478
482
  readsReceiver: (owner) => bodyBySourceOwner.get(owner)?.facts?.readsReceiver ?? false,
479
483
  groupOf: (owner) => (dissolvedGroupMembers.has(owner) ? null : (bodyBySourceOwner.get(owner)?.facts?.captureGroup ?? null)),
480
484
  isAccessorEnvironment: (owner) => accessorEnvironmentOwners.has(owner),
@@ -19,7 +19,7 @@ export declare const computedOverriddenMethodValueText: (ctx: EmitContext, opera
19
19
  export declare const overriddenMethodValueText: (ctx: EmitContext, receiver: Representation, receiverText: string, key: string, materialize: (method: ClassMethod) => {
20
20
  readonly text: string;
21
21
  readonly type: string;
22
- }, held?: CallableAbi | null) => {
22
+ }, held?: CallableAbi | null, carrier?: Representation | null) => {
23
23
  readonly text: string;
24
24
  readonly type: string;
25
25
  };
@@ -1,4 +1,4 @@
1
- import { classMethodValueArmsOf } from '../../../projection/dispatch.js';
1
+ import { classAbstractMemberMissesAt, classPrototypeMethodValueArmsOf } from '../../../projection/dispatch.js';
2
2
  import { heldMethodCopyOf as projectedHeldMethodCopyOf, publishedMethodCopyOf as projectedPublishedMethodCopyOf } from '../../../projection/method-values.js';
3
3
  import { abiOfCallee } from '../../../projection/callee.js';
4
4
  import { createCppEmitBlockedError, operandText } from '../emit-context.js';
@@ -8,21 +8,31 @@ import { cppClassName } from '../types.js';
8
8
  * environment even when Function.call later supplies a different receiver.
9
9
  */
10
10
  export const computedOverriddenMethodValueText = (ctx, operation, key, materialize) => {
11
- return overriddenMethodValueText(ctx, operation.receiver.representation, operandText(ctx, operation.receiver), key, materialize, abiOfCallee(operation.result.representation));
11
+ return overriddenMethodValueText(ctx, operation.receiver.representation, operandText(ctx, operation.receiver), key, materialize, abiOfCallee(operation.result.representation), operation.result.representation);
12
12
  };
13
13
  /** A tagged-union leaf uses the same allocation-selected method as a computed
14
14
  * read on a lone class; the static arm is not the allocation's exact class.
15
15
  */
16
- export const overriddenMethodValueText = (ctx, receiver, receiverText, key, materialize, held = null) => {
17
- const arms = receiver.kind === 'class-ref' ? classMethodValueArmsOf(ctx.classes, receiver.declaration, key) : null;
18
- if (arms === null)
16
+ export const overriddenMethodValueText = (ctx, receiver, receiverText, key, materialize, held = null, carrier = null) => {
17
+ const arms = receiver.kind === 'class-ref' ? classPrototypeMethodValueArmsOf(ctx.classes, receiver.declaration, key) : null;
18
+ const complete = arms !== null &&
19
+ arms.some((arm) => arm.method !== null) &&
20
+ arms.every((arm) => (arm.method !== null && arm.owner !== null) || classAbstractMemberMissesAt(ctx.classes, arm.allocation, key));
21
+ if (!complete)
19
22
  throw createCppEmitBlockedError('property-access:computed-class-method-virtual', `computed method "${key}" has no complete native prototype selection for this family`);
20
23
  const values = arms.map((arm) => {
24
+ if (arm.method === null)
25
+ return { ...arm, text: null, type: null };
21
26
  const method = held === null ? arm.method : heldMethodCopyOf(ctx, arm.method, key, held);
22
27
  return { ...arm, ...materialize(method) };
23
28
  });
24
- const type = values[0].type;
25
- const branches = values.map((arm) => `if (gea::host::hasNativeClassLayoutRef<${cppClassName(arm.allocation)}>(${receiverText})) return ${arm.text};`);
29
+ const type = values.find((arm) => arm.type !== null).type;
30
+ // An instance of the abstract class itself reads `undefined`; the empty
31
+ // callable is that value, and calling it raises the TypeError JS raises for
32
+ // calling `undefined` -- after the arguments are evaluated, as JS orders it.
33
+ if (values.some((arm) => arm.text === null) && carrier?.kind !== 'function-value-dispatch')
34
+ throw createCppEmitBlockedError('property-access:computed-class-method-virtual', `computed method "${key}" misses on an abstract allocation, and its carrier has no empty callable to stand for undefined`);
35
+ const branches = values.map((arm) => `if (gea::host::hasNativeClassLayoutRef<${cppClassName(arm.allocation)}>(${receiverText})) return ${arm.text ?? `${type}()`};`);
26
36
  return { type, text: `([&]() -> ${type} { ${branches.join(' ')} std::abort(); })()` };
27
37
  };
28
38
  /**
@@ -119,6 +119,14 @@ export interface ReactiveClassFieldRead {
119
119
  readonly origin: ReactiveRevisionOrigin;
120
120
  }
121
121
  export declare const reactiveClassFieldClaim: (ctx: EmitContext, operation: GetOperation) => ReactiveClassFieldRead | null;
122
+ /**
123
+ * The key of a method read that always misses: the receiver's family has no
124
+ * override and only an abstract declaration under the key, so an instance
125
+ * (constructed by reflection) has no own or inherited member there and the
126
+ * read is `undefined`. `emit-callable.ts` asks this of a callee so the call
127
+ * raises its TypeError itself, after the arguments are evaluated.
128
+ */
129
+ export declare const abstractMissReadKeyOf: (ctx: EmitContext, operation: GetOperation) => string | null;
122
130
  export declare const classMemberText: (ctx: EmitContext, operation: GetOperation) => ClassMemberValue | null;
123
131
  /**
124
132
  * The member and convention an overridden method read has to be DISPATCHED
@@ -13,7 +13,7 @@ import { operationConversionText } from '../emit-certified-conversion.js';
13
13
  import { nativeMethodValueRecipeText } from '../emit-native-method.js';
14
14
  import { computedOverriddenMethodValueText, heldMethodCopyOf } from './computed-method-value.js';
15
15
  import { nativePrototypeMethodFallbackText } from './native-prototype.js';
16
- import { classFamilyMayAllocate, classMethodValueArmsOf, classPrototypeMethodKeysOf, classPrototypeMethodValueArmsOf, virtualDispatchFor } from '../../../projection/dispatch.js';
16
+ import { classDynamicMethodShadowOf, classFamilyMayAllocate, classMethodFamilyHasNativeBody, classMethodReadMayMissAbstractly, classMethodValueArmsOf, classPrototypeMethodKeysOf, classPrototypeMethodValueArmsOf, virtualDispatchFor } from '../../../projection/dispatch.js';
17
17
  /**
18
18
  * Reading a class's own members as VALUES: an instance's methods and
19
19
  * accessors (`classMemberText`), and a class value's own static methods and
@@ -118,7 +118,16 @@ valueRepresentation = operation.result.representation, receiverText = operandTex
118
118
  const override = receiverRepresentation.kind === 'class-ref' && !dispatchesStatically(ctx, operation.receiver)
119
119
  ? classMethodOverrideOf(ctx.classes, receiverRepresentation.declaration, key)
120
120
  : null;
121
- const heldReceiver = override === null ? receiverText : 'gea_method_receiver';
121
+ // A shadow only a dynamic write installs has no slot: it is read from the
122
+ // instance's expando table (`ClassLayout.dynamicMethodShadows`).
123
+ // A read only a resolved call consumes is the callee of that call, which
124
+ // checks the expando table itself (`CallOperation.expandoShadowGuard`).
125
+ const shadowed = override === null &&
126
+ !ctx.deferredMethodValues.has(operation.result.id) &&
127
+ receiverRepresentation.kind === 'class-ref' &&
128
+ !dispatchesStatically(ctx, operation.receiver) &&
129
+ classDynamicMethodShadowOf(ctx.classes, receiverRepresentation.declaration, key);
130
+ const heldReceiver = override === null && !shadowed ? receiverText : 'gea_method_receiver';
122
131
  const state = `${heldReceiver}->gea_method_state`;
123
132
  const bodyValue = `gea::nativeClassMethodValue<${cppClassName(owner.declaration)}, &${cppCallableDeclarationTagName(method.callable)}>(${state}, ${payload})`;
124
133
  const materialized = nativeMethodValueRecipeText(ctx, operation, key, bodyRepresentation, valueRepresentation, bodyValue, 'prototype', method.callable) ??
@@ -133,6 +142,19 @@ valueRepresentation = operation.result.representation, receiverText = operandTex
133
142
  ? `gea::nativeClassAdaptedMethodValue<${cppClassName(owner.declaration)}, &${cppCallableDeclarationTagName(method.callable)}, ${valueType}>(${state}, [&]() { return ${materialized}; })`
134
143
  : materialized;
135
144
  const fallback = nativePrototypeMethodFallbackText(ctx, receiverRepresentation, key, owner, valueRepresentation, heldReceiver, originalValue, dispatchesStatically(ctx, operation.receiver));
145
+ if (shadowed) {
146
+ const slot = { kind: 'function-value-dispatch', abi: { ...bodyAbi, receiver: null } };
147
+ const stored = `gea::detail::DynamicCarrier<${cppTypeOf(slot)}>::in(*gea_method_shadow, 0)`;
148
+ const owned = nativeMethodValueRecipeText(ctx, operation, key, slot, valueRepresentation, stored, 'own', null) ??
149
+ operationConversionText(ctx, operation, 'method-frame', slot, valueRepresentation, stored);
150
+ if (owned === null) {
151
+ throw createCppEmitBlockedError(`conversion:${representationKey(slot)}->${representationKey(valueRepresentation)}`, `a dynamically shadowed method "${key}" cannot fill its published method-read convention`);
152
+ }
153
+ const text = `([&]() -> ${valueType} { const auto& ${heldReceiver} = ${receiverText}; ` +
154
+ `if (gea::detail::nativeExpandoPresent(${heldReceiver})) { if (const auto gea_method_shadow = gea::detail::nativeExpandoOwnValue(${heldReceiver}, ${JSON.stringify(key)})) return ${owned}; } ` +
155
+ `return ${fallback}; })()`;
156
+ return { text, type: valueType, environment };
157
+ }
136
158
  if (override === null)
137
159
  return { text: fallback, type: valueType, environment };
138
160
  const ownedStorage = `${heldReceiver}->${cppRecordFieldName(key)}`;
@@ -337,6 +359,32 @@ export const reactiveClassFieldClaim = (ctx, operation) => {
337
359
  origin: { struct, key, receiver: operation.receiver }
338
360
  };
339
361
  };
362
+ /**
363
+ * The key of a method read that always misses: the receiver's family has no
364
+ * override and only an abstract declaration under the key, so an instance
365
+ * (constructed by reflection) has no own or inherited member there and the
366
+ * read is `undefined`. `emit-callable.ts` asks this of a callee so the call
367
+ * raises its TypeError itself, after the arguments are evaluated.
368
+ */
369
+ export const abstractMissReadKeyOf = (ctx, operation) => {
370
+ const receiver = operation.receiver.representation;
371
+ if (receiver.kind !== 'class-ref' || operation.result.representation.kind !== 'function-value-dispatch')
372
+ return null;
373
+ const key = ctx.staticKeyTexts.get(operation.key.value);
374
+ if (key === undefined)
375
+ return null;
376
+ const site = classMemberOf(ctx.classes, receiver.declaration, key);
377
+ if (site?.kind !== 'method' || site.method.callable !== null || dispatchesStatically(ctx, operation.receiver))
378
+ return null;
379
+ if (classFamilyOverridesOf(ctx.classes, receiver.declaration, key).length > 0)
380
+ return null;
381
+ if (!classFamilyMayAllocate(ctx.classes, receiver.declaration))
382
+ return null;
383
+ return classMethodFamilyHasNativeBody(ctx.classes, receiver.declaration, key) &&
384
+ classMethodReadMayMissAbstractly(ctx.classes, receiver.declaration, key)
385
+ ? key
386
+ : null;
387
+ };
340
388
  export const classMemberText = (ctx, operation) => {
341
389
  const receiver = operation.receiver.representation;
342
390
  if (receiver.kind !== 'class-ref')
@@ -476,6 +524,16 @@ export const classMemberText = (ctx, operation) => {
476
524
  'std::abort();';
477
525
  return { text: `[]() -> ${carrier} { ${failure} }()`, spelling: carrier };
478
526
  }
527
+ // An instance of the abstract class itself (constructed by reflection, with
528
+ // nothing below it redeclaring the key) misses the lookup: the read is
529
+ // `undefined`, which the dispatch carrier's empty callable stands for. A
530
+ // call of it raises the TypeError JS raises for calling `undefined`, after
531
+ // the arguments are evaluated (`emitCall`). Certification refuses any other
532
+ // carrier.
533
+ if (abstractMissReadKeyOf(ctx, operation) !== null) {
534
+ const carrier = cppTypeOf(operation.result.representation);
535
+ return { text: `${carrier}()`, spelling: carrier };
536
+ }
479
537
  // Certification requires a native implementation family for an evaluated
480
538
  // method read. A declaration without a body cannot provide a callable:
481
539
  // JavaScript can still construct its class through an erased assertion.
@@ -531,6 +589,8 @@ export const virtualCalleeClaim = (ctx, operation) => {
531
589
  return null;
532
590
  if (classPrototypeMethodMutableOf(ctx.classes, receiver.declaration, key))
533
591
  return null;
592
+ // A dynamic shadow (`ClassLayout.dynamicMethodShadows`) keeps the virtual call:
593
+ // the call checks the expando table before dispatching (`CallOperation.expandoShadowGuard`).
534
594
  if (classMethodOverrideOf(ctx.classes, receiver.declaration, key) !== null)
535
595
  return null;
536
596
  // One copy of a generic method dispatches through that copy's own member
@@ -1,5 +1,5 @@
1
1
  import { abiOfCallee } from '../../../projection/callee.js';
2
- import { classMethodValueArmsOf, methodCopyHeldBy } from '../../../projection/dispatch.js';
2
+ import { classDynamicMethodShadowOf, classMethodValueArmsOf, methodCopyHeldBy } from '../../../projection/dispatch.js';
3
3
  import { classMethodOverrideOf } from '../../../projection/fields.js';
4
4
  import { cppThunkEntryText, createCppEmitBlockedError } from '../emit-context.js';
5
5
  import { cppCallableDeclarationTagName, cppClassName, cppRecordFieldName, cppRecordFieldPresenceName, cppTypeOf } from '../types.js';
@@ -52,6 +52,17 @@ export const nativeClassMethodReadText = (ctx, source, carrier, key, text, conve
52
52
  return null;
53
53
  selection = `if (${object}->${cppRecordFieldPresenceName(key)}) return ${stored}; ${selection}`;
54
54
  }
55
+ else if (classDynamicMethodShadowOf(ctx.classes, arm.allocation, key)) {
56
+ // A shadow a dynamic write installed lives in the expando table
57
+ // (`ClassLayout.dynamicMethodShadows`), held as the slot would have held it.
58
+ const slot = { kind: 'function-value-dispatch', abi: { ...ownAbi, receiver: null } };
59
+ const stored = convert('native-method-read:own', slot, carrier, `gea::detail::DynamicCarrier<${cppTypeOf(slot)}>::in(*gea_method_shadow, 0)`);
60
+ if (stored === null)
61
+ return null;
62
+ selection =
63
+ `if (gea::detail::nativeExpandoPresent(${object})) { if (const auto gea_method_shadow = gea::detail::nativeExpandoOwnValue(${object}, ${JSON.stringify(key)})) return ${stored}; } ` +
64
+ selection;
65
+ }
55
66
  branches.push(`if (gea::host::hasNativeClassLayoutRef<${cppClassName(arm.allocation)}>(gea_method_receiver)) { ` +
56
67
  `const auto ${object} = gea::Ref<void>(gea_method_receiver).staticCast<${cppClassName(arm.allocation)}>(); ${selection} }`);
57
68
  }
@@ -898,6 +898,7 @@ const cppConversionTables = (layouts, nativeNarrowing, nativeWrappedPayload) =>
898
898
  const eligible = (target.kind === 'dictionary' ||
899
899
  target.kind === 'record-with-index' ||
900
900
  target.kind === 'typed-array' ||
901
+ (target.kind === 'keyed-collection' && target.recursive === undefined) ||
901
902
  (target.kind === 'record' && target.accessors.length > 0)) &&
902
903
  target.ownership === 'shared-refcount';
903
904
  if (!eligible && target.kind !== 'array-buffer' && target.kind !== 'shared-array-buffer' && target.kind !== 'data-view')
@@ -4,6 +4,11 @@ import type { HoistPlan } from '../../ir/hoist.js';
4
4
  import type { RecordToArrayPlan } from '../../conversion/structural-plan.js';
5
5
  import { type EmitContext, type FillLoop, type EmitBodyPrepassFacts } from './emit-context.js';
6
6
  import { type ConversionSite } from './emit-narrowing.js';
7
+ /**
8
+ * Marks every array literal of a body whose literals together hold
9
+ * `outOfLineLiteralPushThreshold` or more ordinary elements.
10
+ */
11
+ export declare const collectOutOfLineLiteralPushes: (prepass: EmitBodyPrepassFacts, body: IrBody) => void;
7
12
  /**
8
13
  * Whether a value's rendered text is a constant expression a `static const` initializer may hold.
9
14
  *
@@ -6,7 +6,7 @@ import { atBlockExit, collectDefinitionSites, controlFlowGraphOf, dominatorTreeO
6
6
  import { operandsOfIrOperation, resultOfIrOperation } from '../../ir/queries.js';
7
7
  import { representationKey } from '../../representation/model.js';
8
8
  import { admittedDenseLoopPlanOf } from '../../ir/dense-loops.js';
9
- import { bindingReference, copiedCaptureName, declareCell, defineValueAlias, cppDenseDivisorName, cppDenseFlagName, cppDenseLengthName, cppDensePointerName, cppDenseRowName, cppDenseRowsName, createCppEmitBlockedError, defineValue, operandText, storageTypeOf } from './emit-context.js';
9
+ import { bindingReference, copiedCaptureName, declareCell, defineValueAlias, cppDenseDivisorName, cppDenseFlagName, cppDenseLengthName, cppDenseExtentName, cppDensePointerName, cppDenseRowName, cppDenseRowsName, createCppEmitBlockedError, defineValue, operandText, storageTypeOf } from './emit-context.js';
10
10
  import { readsCell } from './deferral-safety.js';
11
11
  import { cellValueText } from './emit-bindings.js';
12
12
  import { alignedText } from './emit-callable.js';
@@ -32,6 +32,45 @@ import { arrayBulkAppendMethodName } from './prototype/emit-prototype-array.js';
32
32
  * being a handful, not at the size where the statement form stops compiling.
33
33
  */
34
34
  const constantTableThreshold = 8;
35
+ /**
36
+ * How many inlined literal `push`es one body may hold before they are spelled
37
+ * as calls instead.
38
+ *
39
+ * `ArrayObject::push` is always-inline, and every inlined copy brings its
40
+ * capacity branch and an unwind edge that releases every handle live in the
41
+ * body. A level table written as nested short literals -- thousands of
42
+ * `[x, y, z]` rows, each under the constant-table threshold -- puts all of
43
+ * those in one module body: 15,861 pushes made a 217,743 instruction function
44
+ * that clang's GVN (`addDeadBlock`, quadratic in the folded capacity branches)
45
+ * had not finished after 214 CPU minutes. The same body through
46
+ * `gea::runtime::array::pushOutOfLine` compiles in under nine minutes.
47
+ *
48
+ * A body below the bound keeps the inlined form, where a handful of stores
49
+ * fold; one at or past it is a data table, built once, and gains nothing from
50
+ * inlining.
51
+ */
52
+ const outOfLineLiteralPushThreshold = 512;
53
+ /**
54
+ * Marks every array literal of a body whose literals together hold
55
+ * `outOfLineLiteralPushThreshold` or more ordinary elements.
56
+ */
57
+ export const collectOutOfLineLiteralPushes = (prepass, body) => {
58
+ let count = 0;
59
+ const literals = [];
60
+ for (const block of body.blocks.values())
61
+ for (const operation of block.operations) {
62
+ if (operation.kind !== 'allocate-array-object')
63
+ continue;
64
+ literals.push(operation.result.id);
65
+ for (const slot of operation.elements)
66
+ if (slot.kind === 'element')
67
+ count += 1;
68
+ }
69
+ if (count < outOfLineLiteralPushThreshold)
70
+ return;
71
+ for (const literal of literals)
72
+ prepass.outOfLineLiteralPushes.add(literal);
73
+ };
35
74
  /** How many values one line of a static table's initializer carries. A table of 87,210 doubles is otherwise a single 700 KB line. */
36
75
  const constantTableRowWidth = 16;
37
76
  /**
@@ -248,6 +287,7 @@ export const emitAllocateArrayObject = (ctx, lines, operation) => {
248
287
  lines.push(`gea::runtime::array::appendTable(${name}, ${table.name}, ${table.count});`);
249
288
  return;
250
289
  }
290
+ const outOfLine = ctx.outOfLineLiteralPushes.has(operation.result.id);
251
291
  for (const slot of operation.elements) {
252
292
  if (slot.kind === 'hole') {
253
293
  lines.push(`${name}->pushHole();`);
@@ -378,7 +418,8 @@ export const emitAllocateArrayObject = (ctx, lines, operation) => {
378
418
  // and a concrete value has to be boxed on the way in. Without it the push
379
419
  // assigned an `NSObject` straight into a `gea::Value` slot, which is the
380
420
  // one thing the box's storage-only design cannot do implicitly.
381
- lines.push(`${name}->push(${alignedText(ctx, representation.element, slot.value, 'allocate-array-object')});`);
421
+ const stored = alignedText(ctx, representation.element, slot.value, 'allocate-array-object');
422
+ lines.push(outOfLine ? `gea::runtime::array::pushOutOfLine(${name}, ${stored});` : `${name}->push(${stored});`);
382
423
  }
383
424
  };
384
425
  /** The number a capacity hint names, spelled where the array is allocated. */
@@ -899,7 +940,7 @@ const advancesByOne = (loop, facts) => {
899
940
  return facts.constants.get(other.value) === '1';
900
941
  };
901
942
  /** The plain C++ name a dense window may read its array or its counter through, or `null` when this body has no such name for the cell. */
902
- const denseCellName = (ctx, declaration) => {
943
+ const denseCellName = (ctx, declaration, boundsTheLoop = false) => {
903
944
  const placement = ctx.placements.get(declaration);
904
945
  if (!placement)
905
946
  return null;
@@ -910,14 +951,14 @@ const denseCellName = (ctx, declaration) => {
910
951
  return realmBindingName(ctx.placements, declaration);
911
952
  if (placement.storage.kind !== 'local')
912
953
  return null;
913
- if (ctx.captures.isBoxed(declaration))
914
- return null;
915
954
  if (placement.storage.owner === ctx.owner)
916
- return bindingReference(ctx, declaration, 'a dense Array window').name;
955
+ return ctx.captures.isBoxed(declaration) ? null : bindingReference(ctx, declaration, 'a dense Array window').name;
917
956
  // A parallel region's row callback reads every array it indexes as a
918
957
  // capture, and without this each element read paid the bounds and view
919
- // checks the window hoists.
920
- return copiedCaptureName(ctx, declaration);
958
+ // checks the window hoists. A settled box qualifies only as the array whose
959
+ // length bounds the loop: the hoist that moved that read out proved the loop
960
+ // changes no storage, so nothing it runs can write the box either.
961
+ return copiedCaptureName(ctx, declaration, boundsTheLoop);
921
962
  };
922
963
  /** One dense-window operand as a `long long`; the census already narrowed most of them, and the rest are ordinary `number` cells. */
923
964
  const denseIntegerText = (ctx, operand) => ctx.integerValues.has(operand.value) ? operandText(ctx, operand) : `static_cast<${cppNarrowedIntegerType}>(${operandText(ctx, operand)})`;
@@ -950,7 +991,7 @@ export const admitDenseWindows = (ctx, prepass, body) => {
950
991
  throw new Error(`body ${body.owner} has no certified dense-loop plan`);
951
992
  if (plan.arrays.length === 0)
952
993
  return;
953
- const admitted = admittedDenseLoopPlanOf(plan, ctx.integerValues, (declaration) => denseCellName(ctx, declaration) !== null, ctx.hoistedResults);
994
+ const admitted = admittedDenseLoopPlanOf(plan, ctx.integerValues, (declaration, boundsTheLoop) => denseCellName(ctx, declaration, boundsTheLoop) !== null, ctx.hoistedResults);
954
995
  for (const [operation, access] of admitted.accesses)
955
996
  prepass.denseAccesses.set(operation, access);
956
997
  for (const array of admitted.arrays) {
@@ -981,7 +1022,7 @@ const materializeDenseReference = (prepass, reference) => {
981
1022
  */
982
1023
  const denseHolderOf = (ctx, lines, reference, array) => {
983
1024
  if (reference.kind === 'cell') {
984
- const name = denseCellName(ctx, reference.declaration);
1025
+ const name = denseCellName(ctx, reference.declaration, reference.declaration === array.lengthCell);
985
1026
  if (name === null)
986
1027
  return null;
987
1028
  if (reference.conversion === undefined)
@@ -1056,6 +1097,15 @@ export const emitDenseSetup = (ctx, lines, blockId) => {
1056
1097
  if (holder === null)
1057
1098
  continue;
1058
1099
  const pointer = cppDensePointerName(array.ordinal);
1100
+ // A checked window bounds each access itself (`DenseArray.checked`):
1101
+ // the preheader only names the view's elements and how many there are.
1102
+ // A detached buffer has none, and `data()` would abort on it.
1103
+ if (array.checked === true && array.typed !== null) {
1104
+ const extent = cppDenseExtentName(array.ordinal);
1105
+ ctx.declarations.push({ name: pointer, type: `${cppScalarType(array.typed)}*` }, { name: extent, type: 'std::size_t' });
1106
+ lines.push(`${extent} = ${holder.text}->size();`, `${pointer} = ${extent} > 0 ? ${holder.text}->data() : nullptr;`);
1107
+ continue;
1108
+ }
1059
1109
  const cells = `${holder.text}->cells`;
1060
1110
  const data = array.typed === null ? `${cells}.data()` : `${holder.text}->data()`;
1061
1111
  const size = array.typed === null ? `${cells}.size()` : `${holder.text}->size()`;
@@ -40,12 +40,25 @@ export declare const bindingReference: (ctx: EmitContext, declaration: Declarati
40
40
  frame?: true;
41
41
  };
42
42
  /**
43
- * The name this body reads another frame's local through when its environment
44
- * holds a by-value copy of it, or `null` for anything else.
43
+ * The name this body reads another frame's local through when that local
44
+ * holds one value for as long as this body runs, or `null` for anything else.
45
45
  *
46
46
  * Unboxed means nothing rebinds the declaration once a closure has captured
47
- * it, so the copy holds the same value for as long as this body runs, whatever
48
- * code it calls. A frame member or a boxed slot is shared storage and can
49
- * change under a call.
47
+ * it, whatever code this body calls. That holds wherever the value lives: in
48
+ * this body's environment as a copy, or in the owner's frame, which an
49
+ * unboxed declaration joins only when its one write runs once per call of the
50
+ * owner -- a read here that did not throw came after that write. A collision
51
+ * world's `raycast` reads its `boxes` through the frame it shares with
52
+ * `addBox`, and every box paid the bounds and view checks again because the
53
+ * frame slot was taken for mutable storage.
54
+ *
55
+ * A boxed declaration the program writes exactly once holds one value too
56
+ * (`IrBodyFacts.settledBoxes`): it is boxed only because a hoisted function
57
+ * declaration may run before its write, as `raycast`'s owner declares
58
+ * `rebuildGrid` above `const boxes`. Its frame slot is the box itself, so
59
+ * the name is the value -- but its one write can still run after this body
60
+ * starts, in code it calls, so a caller asks for one (`settled`) only where
61
+ * the loop it reads in changes no storage. Any other boxed slot is one a call
62
+ * can change.
50
63
  */
51
- export declare const copiedCaptureName: (ctx: EmitContext, declaration: DeclarationId) => string | null;
64
+ export declare const copiedCaptureName: (ctx: EmitContext, declaration: DeclarationId, settled?: boolean) => string | null;
@@ -211,20 +211,38 @@ export const bindingReference = (ctx, declaration, what) => {
211
211
  return { name, owned: true, boxed: ctx.captures.isBoxed(declaration) };
212
212
  };
213
213
  /**
214
- * The name this body reads another frame's local through when its environment
215
- * holds a by-value copy of it, or `null` for anything else.
214
+ * The name this body reads another frame's local through when that local
215
+ * holds one value for as long as this body runs, or `null` for anything else.
216
216
  *
217
217
  * Unboxed means nothing rebinds the declaration once a closure has captured
218
- * it, so the copy holds the same value for as long as this body runs, whatever
219
- * code it calls. A frame member or a boxed slot is shared storage and can
220
- * change under a call.
218
+ * it, whatever code this body calls. That holds wherever the value lives: in
219
+ * this body's environment as a copy, or in the owner's frame, which an
220
+ * unboxed declaration joins only when its one write runs once per call of the
221
+ * owner -- a read here that did not throw came after that write. A collision
222
+ * world's `raycast` reads its `boxes` through the frame it shares with
223
+ * `addBox`, and every box paid the bounds and view checks again because the
224
+ * frame slot was taken for mutable storage.
225
+ *
226
+ * A boxed declaration the program writes exactly once holds one value too
227
+ * (`IrBodyFacts.settledBoxes`): it is boxed only because a hoisted function
228
+ * declaration may run before its write, as `raycast`'s owner declares
229
+ * `rebuildGrid` above `const boxes`. Its frame slot is the box itself, so
230
+ * the name is the value -- but its one write can still run after this body
231
+ * starts, in code it calls, so a caller asks for one (`settled`) only where
232
+ * the loop it reads in changes no storage. Any other boxed slot is one a call
233
+ * can change.
221
234
  */
222
- export const copiedCaptureName = (ctx, declaration) => {
235
+ export const copiedCaptureName = (ctx, declaration, settled = false) => {
223
236
  const placement = ctx.placements.get(declaration);
224
237
  if (placement?.storage.kind !== 'local' || placement.storage.owner === ctx.owner)
225
238
  return null;
226
- if (ctx.captures.isBoxed(declaration))
239
+ const boxed = ctx.captures.isBoxed(declaration);
240
+ if (boxed && !(settled && ctx.captures.isSettledBox(declaration)))
227
241
  return null;
228
242
  const captured = bindingReference(ctx, declaration, 'a captured cell');
229
- return captured.capture === true && captured.frame !== true && !captured.boxed ? captured.name : null;
243
+ if (captured.capture !== true)
244
+ return null;
245
+ if (captured.frame === true)
246
+ return captured.name;
247
+ return !boxed && !captured.boxed ? captured.name : null;
230
248
  };
@@ -120,6 +120,13 @@ export const emitBindingRead = (ctx, lines, operation) => {
120
120
  defineValueAlias(ctx, operation.result, `std::as_const(${fieldCell})`);
121
121
  return;
122
122
  }
123
+ // A cell that points at its window cell (`EmitContext.borrowedWindowCells`).
124
+ // Const for the same reason: a consumer that moves must not empty the array.
125
+ const windowCell = ctx.borrowedWindowCellNames.get(operation.declaration);
126
+ if (windowCell !== undefined) {
127
+ defineValueAlias(ctx, operation.result, `std::as_const(*${windowCell})`);
128
+ return;
129
+ }
123
130
  // A char-code buffer is read by naming the string, never by copying it: a push appends to the cell itself.
124
131
  if (ctx.charCodeBuffers.reads.has(operation.result.id)) {
125
132
  defineValueAlias(ctx, operation.result, cellValueText(bindingReference(ctx, operation.declaration, 'a char-code buffer read')));
@@ -457,6 +464,21 @@ export const emitBindingWrite = (ctx, lines, operation) => {
457
464
  // (`EmitContext.forwardedBindings`), so there is no cell to declare or fill.
458
465
  if (ctx.forwardedBindings.get(operation.declaration)?.value.value === operation.value.value)
459
466
  return;
467
+ // The one write of a cell that borrows its window cell stores the cell's
468
+ // address: the read rendered as the cell itself, an lvalue in both arms, and
469
+ // the loop changes no array, so the address holds the element for every read.
470
+ if (ctx.borrowedWindowCells.has(operation.declaration) && ctx.denseCellReads.has(operation.value.value)) {
471
+ const held = ctx.placements.get(operation.declaration)?.representation;
472
+ const deferred = ctx.deferredTexts.get(operation.value.value);
473
+ if (held !== undefined && held !== null && deferred !== undefined && !ctx.declaredBindings.has(operation.declaration)) {
474
+ const cell = bindingReference(ctx, operation.declaration, 'a borrowed window cell');
475
+ declareCell(ctx, cell.name, `const ${cppTypeOf(held)}*`);
476
+ ctx.declaredBindings.add(operation.declaration);
477
+ ctx.borrowedWindowCellNames.set(operation.declaration, cell.name);
478
+ lines.push(`${cell.name} = &${deferred};`);
479
+ return;
480
+ }
481
+ }
460
482
  // The value is the class object of a generic the program never instantiates
461
483
  // at the written name (`classObjectReadsOf`): the read names the bare
462
484
  // declaration, which has no cell of its own, but the family the carrier names