@geastack/compiler 1.0.42 → 1.0.43

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 (44) hide show
  1. package/dist/conversion/nodes.js +5 -2
  2. package/dist/ir/certify.js +1 -1
  3. package/dist/ir/host-template-conversions.d.ts +2 -2
  4. package/dist/ir/host-template-conversions.js +73 -2
  5. package/dist/ir/lower-destructuring.js +22 -3
  6. package/dist/ir/lower-operands.js +24 -0
  7. package/dist/ir/native-field-view-facts.d.ts +8 -1
  8. package/dist/ir/native-field-view-facts.js +13 -3
  9. package/dist/ir/operation-conversions.js +1 -1
  10. package/dist/ir/program-conversions.d.ts +1 -1
  11. package/dist/ir/program-conversions.js +68 -1
  12. package/dist/ir/property-read-conversions.js +7 -1
  13. package/dist/ir/publish-native-field-view-facts.js +4 -0
  14. package/dist/ir/reflection-demand.js +29 -3
  15. package/dist/projection/dispatch.d.ts +19 -1
  16. package/dist/projection/dispatch.js +34 -0
  17. package/dist/representation/value-records.js +182 -13
  18. package/dist/semantics/normalize/collection-bindings.d.ts +7 -0
  19. package/dist/semantics/normalize/collection-bindings.js +35 -1
  20. package/dist/semantics/normalize/derived-expression-type.js +49 -0
  21. package/dist/semantics/normalize/field-bindings.js +6 -1
  22. package/dist/semantics/normalize/flow/source-value-session.d.ts +9 -2
  23. package/dist/semantics/normalize/flow/source-value-session.js +538 -94
  24. package/dist/semantics/normalize/local-bindings.js +23 -1
  25. package/dist/semantics/normalize/producers/references.js +26 -18
  26. package/dist/semantics/normalize/structural-array-element.d.ts +7 -0
  27. package/dist/semantics/normalize/structural-array-element.js +24 -1
  28. package/dist/semantics/normalize/structural-layout-type.js +5 -1
  29. package/dist/semantics/normalize/structural-parts.js +13 -8
  30. package/dist/semantics/normalize/structural.js +25 -1
  31. package/dist/targets/cpp/class-properties/emit-class-properties.js +5 -1
  32. package/dist/targets/cpp/emit-callable.js +19 -10
  33. package/dist/targets/cpp/emit-native-field-view.d.ts +2 -0
  34. package/dist/targets/cpp/emit-native-field-view.js +1 -1
  35. package/dist/targets/cpp/emit-properties.js +114 -12
  36. package/dist/targets/cpp/host/emit-host-invoke.js +16 -2
  37. package/dist/targets/cpp/host/host-members.js +4 -0
  38. package/dist/targets/cpp/prototype/emit-prototype-array.d.ts +42 -0
  39. package/dist/targets/cpp/prototype/emit-prototype-array.js +31 -9
  40. package/dist/targets/cpp/records.js +39 -16
  41. package/dist/targets/cpp/translation-unit.js +23 -2
  42. package/package.json +1 -1
  43. package/src/targets/cpp/runtime/gea_dynamic_proxy.h +17 -1
  44. package/src/targets/cpp/runtime/gea_runtime.h +298 -51
@@ -718,6 +718,15 @@ moduleRecords = emptyCommonJsModuleRecordCensus) => {
718
718
  * element type, as do indexed reads whose absence is not observed.
719
719
  */
720
720
  const observedIndexedAbsence = new Map();
721
+ /**
722
+ * The same observation over a read the checker types `any` (`const lit = []`
723
+ * in a JavaScript file). `any` names no element, but this census may still
724
+ * type the cell from its write, and the read itself already admits absence
725
+ * (`structural-array-read.ts`'s `admitsUndefined`). The cell's type is known
726
+ * only once resolution settles, so its declaration and observing references
727
+ * wait for it.
728
+ */
729
+ const untypedObservedAbsence = [];
721
730
  const directUndefinedComparison = (expression) => {
722
731
  let inner = expression;
723
732
  let parent = inner.parent;
@@ -787,7 +796,8 @@ moduleRecords = emptyCommonJsModuleRecordCensus) => {
787
796
  if (!arrayRead && !dictionaryRead && !assertedRead)
788
797
  return;
789
798
  const value = checker.getTypeAtLocation(initializer);
790
- if (isUnusableEvidence(value) || (value.flags & ts.TypeFlags.Unknown) !== 0)
799
+ const untyped = isAnyType(value);
800
+ if (!untyped && (isUnusableEvidence(value) || (value.flags & ts.TypeFlags.Unknown) !== 0))
791
801
  return;
792
802
  const symbol = checker.getSymbolAtLocation(declaration.name);
793
803
  if (!symbol)
@@ -797,6 +807,10 @@ moduleRecords = emptyCommonJsModuleRecordCensus) => {
797
807
  .filter((reference) => directUndefinedComparison(reference) || directTruthinessTest(reference));
798
808
  if (observing.length === 0)
799
809
  return;
810
+ if (untyped) {
811
+ untypedObservedAbsence.push({ declaration, nodes: [declaration, declaration.name, ...observing] });
812
+ return;
813
+ }
800
814
  const optional = checker.getNullableType(value, ts.TypeFlags.Undefined);
801
815
  observedIndexedAbsence.set(declaration, optional);
802
816
  observedIndexedAbsence.set(declaration.name, optional);
@@ -1799,6 +1813,14 @@ moduleRecords = emptyCommonJsModuleRecordCensus) => {
1799
1813
  if (bound.size === before)
1800
1814
  break;
1801
1815
  }
1816
+ for (const { declaration, nodes } of untypedObservedAbsence) {
1817
+ const cell = bound.get(declaration);
1818
+ if (!cell)
1819
+ continue;
1820
+ const optional = checker.getNullableType(cell, ts.TypeFlags.Undefined);
1821
+ for (const node of nodes)
1822
+ observedIndexedAbsence.set(node, optional);
1823
+ }
1802
1824
  // `root` is the same stable, hand-written reason string this census always
1803
1825
  // keyed its old count map by (`no-symbol`, `write-unresolved`, one of
1804
1826
  // `noEvidenceReason`'s `no-writes:...` family, ...) -- never node text or a
@@ -43,8 +43,13 @@ const includesUndefined = (type) => {
43
43
  return true;
44
44
  return type.isUnion() && type.types.some(includesUndefined);
45
45
  };
46
- /** Whether an equality operation directly compares this expression with `undefined`. */
47
- const comparesWithUndefined = (context, node) => {
46
+ /**
47
+ * Whether this expression is an equality operand or `instanceof`'s left
48
+ * operand. Both answer for `undefined` without reading it: IsStrictlyEqual and
49
+ * IsLooselyEqual compare it, and OrdinaryHasInstance returns false for a
50
+ * non-object.
51
+ */
52
+ const comparesItsOperand = (node) => {
48
53
  let inner = node;
49
54
  let parent = inner.parent;
50
55
  while (parent && ts.isParenthesizedExpression(parent)) {
@@ -54,14 +59,12 @@ const comparesWithUndefined = (context, node) => {
54
59
  if (!parent || !ts.isBinaryExpression(parent))
55
60
  return false;
56
61
  const operator = parent.operatorToken.kind;
57
- if (operator !== ts.SyntaxKind.EqualsEqualsToken &&
58
- operator !== ts.SyntaxKind.ExclamationEqualsToken &&
59
- operator !== ts.SyntaxKind.EqualsEqualsEqualsToken &&
60
- operator !== ts.SyntaxKind.ExclamationEqualsEqualsToken) {
61
- return false;
62
- }
63
- const other = parent.left === inner ? parent.right : parent.right === inner ? parent.left : null;
64
- return other !== null && (context.types.rawTypeAt(other).flags & ts.TypeFlags.Undefined) !== 0;
62
+ if (operator === ts.SyntaxKind.InstanceOfKeyword)
63
+ return parent.left === inner;
64
+ return (operator === ts.SyntaxKind.EqualsEqualsToken ||
65
+ operator === ts.SyntaxKind.ExclamationEqualsToken ||
66
+ operator === ts.SyntaxKind.EqualsEqualsEqualsToken ||
67
+ operator === ts.SyntaxKind.ExclamationEqualsEqualsToken);
65
68
  };
66
69
  /**
67
70
  * Keep an explicitly optional local's physical absence when this use has a
@@ -71,21 +74,26 @@ const comparesWithUndefined = (context, node) => {
71
74
  * property producer restores that absence and the cell therefore physically
72
75
  * holds `Optional<T>`; dereferencing it at a later optional return or
73
76
  * `!== undefined` test would discard the very absence the producer recovered.
77
+ * An unannotated local has the same cell when the local-binding census
78
+ * restored the absence from a later test (`observedIndexedAbsence`), and the
79
+ * checker types its other reads `T` just the same.
74
80
  *
75
81
  * This does not suppress ordinary control-flow narrowing: only a use whose
76
- * contextual destination itself admits `undefined`, or which directly tests
77
- * for it, keeps the declaration's stated carrier. A use that requires `T`
78
- * continues to use the checker's narrowed answer and its existing presence
79
- * proof/conversion.
82
+ * contextual destination itself admits `undefined`, or which compares it
83
+ * (`comparesItsOperand`), keeps the declaration's stated carrier. A use that
84
+ * requires `T` continues to use the checker's narrowed answer and its existing
85
+ * presence proof/conversion.
80
86
  */
81
87
  const destinationPreservesDeclaredAbsence = (context, node, declaration) => {
82
- if (!declaration || !ts.isVariableDeclaration(declaration) || declaration.type === undefined)
88
+ if (!declaration || !ts.isVariableDeclaration(declaration))
83
89
  return null;
84
- const declared = context.checker.getTypeAtLocation(declaration.name);
85
- if (!includesUndefined(declared))
90
+ const declared = declaration.type !== undefined
91
+ ? context.checker.getTypeAtLocation(declaration.name)
92
+ : (context.parameters.preferredTypeAt?.(declaration) ?? null);
93
+ if (!declared || !includesUndefined(declared))
86
94
  return null;
87
95
  const contextual = context.checker.getContextualType(node);
88
- if ((contextual === undefined || !includesUndefined(contextual)) && !comparesWithUndefined(context, node))
96
+ if ((contextual === undefined || !includesUndefined(contextual)) && !comparesItsOperand(node))
89
97
  return null;
90
98
  return context.types.typeAt(declaration);
91
99
  };
@@ -3,6 +3,13 @@ import type { StructuralTypeId } from '../../identity/ids.js';
3
3
  import type { StructuralTypeTable } from '../model/structural-type-table.js';
4
4
  import type { CollectionBindingCensus } from './collection-bindings.js';
5
5
  import { type ObjectBagCensus } from './object-bag-bindings.js';
6
+ /**
7
+ * Whether a computed read (`this.koto[layer]`) can select an object literal's
8
+ * `[]` member that `arrayHoldsUnjoinedWrites`. That member is stored as the
9
+ * box (`inferredArrayElementAt`), while the checker still answers the read
10
+ * with the member's `never[]`.
11
+ */
12
+ export declare const readsUnjoinedArrayMember: (checker: ts.TypeChecker, collections: CollectionBindingCensus, layoutTypeAt: (node: ts.Node) => ts.Type, node: ts.ElementAccessExpression) => boolean;
6
13
  export declare const unstatedNeverArray: (checker: ts.TypeChecker, collections: CollectionBindingCensus, layoutTypeAt: (node: ts.Node) => ts.Type, node: ts.Node) => boolean;
7
14
  export declare const inferredArrayElementAt: (checker: ts.TypeChecker, collections: CollectionBindingCensus, layoutTypeAt: (node: ts.Node) => ts.Type, node: ts.Node) => ts.Type | null;
8
15
  /**
@@ -245,6 +245,22 @@ const isOpenStringIndexType = (checker, type) => {
245
245
  const index = checker.getIndexInfoOfType(type, ts.IndexKind.String);
246
246
  return index !== undefined && (index.type.flags & ts.TypeFlags.Any) !== 0 && type.getCallSignatures().length === 0;
247
247
  };
248
+ /**
249
+ * Whether a computed read (`this.koto[layer]`) can select an object literal's
250
+ * `[]` member that `arrayHoldsUnjoinedWrites`. That member is stored as the
251
+ * box (`inferredArrayElementAt`), while the checker still answers the read
252
+ * with the member's `never[]`.
253
+ */
254
+ export const readsUnjoinedArrayMember = (checker, collections, layoutTypeAt, node) => {
255
+ const receiver = checker.getNonNullableType(layoutTypeAt(node.expression));
256
+ return (receiver.isUnion() ? receiver.types : [receiver]).some((arm) => checker.getPropertiesOfType(arm).some((property) => {
257
+ const declaration = property.declarations?.[0];
258
+ return (declaration !== undefined &&
259
+ ts.isPropertyAssignment(declaration) &&
260
+ ts.isArrayLiteralExpression(declaration.initializer) &&
261
+ collections.arrayHoldsUnjoinedWrites(declaration.initializer));
262
+ }));
263
+ };
248
264
  export const unstatedNeverArray = (checker, collections, layoutTypeAt, node) => {
249
265
  const neverElement = (type) => {
250
266
  if (!checker.isArrayType(type))
@@ -356,8 +372,15 @@ const statesItsOwnType = (checker, node) => {
356
372
  declaration.type !== undefined);
357
373
  };
358
374
  export const inferredArrayElementAt = (checker, collections, layoutTypeAt, node) => {
375
+ // An array filled with values the census could not join holds the box.
376
+ // Answered here, not by `unstatedNeverArray`, which leaves an object
377
+ // literal's member to the record's `never[]`: the record's member storage is
378
+ // asked at this same literal (`structural-parts.ts`), so both get the box.
359
379
  if (ts.isArrayLiteralExpression(node))
360
- return (collections.arrayElementAt(node) ?? iterableMergeArmElement(checker, layoutTypeAt, node) ?? definedPropertyArrayElement(checker, node));
380
+ return (collections.arrayElementAt(node) ??
381
+ iterableMergeArmElement(checker, layoutTypeAt, node) ??
382
+ definedPropertyArrayElement(checker, node) ??
383
+ (collections.arrayHoldsUnjoinedWrites(node) ? checker.getAnyType() : null));
361
384
  // THE CELL'S OWN DECLARATION -- neither the literal that filled it nor a
362
385
  // read of it, and the node a cell's stored carrier is actually published
363
386
  // from. `const uvBuffer = []` types as `never[]` at the
@@ -502,7 +502,11 @@ export const createLayoutTypeResolver = (checker, parameters = emptyParameterBin
502
502
  : ts.isShorthandPropertyAssignment(declaration)
503
503
  ? declaration.name
504
504
  : declaration;
505
- const fromCensus = parameters.typeAt(censusNode);
505
+ // ...unless that write's answer is only its own right-hand side, which
506
+ // states nothing about the field's other writes: see `memberOf`'s
507
+ // `assignedField`.
508
+ const written = parameters.typeAt(censusNode);
509
+ const fromCensus = ts.isBinaryExpression(censusNode) && written === checker.getTypeAtLocation(censusNode) ? parameters.typeAt(censusNode.left) : written;
506
510
  if (fromCensus && !isUnreducedTypeForm(fromCensus) && (fromCensus.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) === 0)
507
511
  return fromCensus;
508
512
  const objectFlags = receiver.objectFlags ?? 0;
@@ -628,14 +628,19 @@ export const createStructuralParts = (input) => {
628
628
  // `IteratorResult`. An answer equal to the node's own declared type added
629
629
  // nothing, so the checker's instantiated answer stands.
630
630
  const censused = needsCensus && censusNode ? input.layoutTypeAt(censusNode) : null;
631
- // A JS assignment declaration (`this.x = k * 2`) is its own first write, so
632
- // the checker's type AT that node is the written value's, not the member's:
633
- // with a second, `any`-typed write (`this.x = opts.n`) the member is `any`
634
- // while this node reads `number`, and the census join agreeing with that one
635
- // write is real evidence, not an echo of the declared form. Treating it as an
636
- // echo left the field `any` -- boxed -- exactly when a typed write came first.
637
- const nodeStatesWrittenValue = censusNode !== null && ts.isBinaryExpression(censusNode);
638
- const fromCensus = censused !== null && censusNode && !nodeStatesWrittenValue && censused === checker.getTypeAtLocation(censusNode) ? null : censused;
631
+ // A JS assignment declaration (`this.x = k * 2`) is its own first write,
632
+ // and an answer there that only echoes its right-hand side says nothing
633
+ // about the field's other writes: a constructor's `this.shaku = null` typed
634
+ // the field `null` whatever a later `this.shaku = index.shakuhachi` stored.
635
+ // The field is the LEFT side, where `field-bindings.ts` joins every write
636
+ // (a typed `k * 2` beside an `any` write still binds `number` there) or
637
+ // answers nothing, leaving the checker's `any`.
638
+ const assignedField = censusNode !== null && ts.isBinaryExpression(censusNode) && censused !== null && censused === checker.getTypeAtLocation(censusNode)
639
+ ? censusNode.left
640
+ : null;
641
+ const censusCell = assignedField ?? censusNode;
642
+ const cellAnswer = assignedField ? input.layoutTypeAt(assignedField) : censused;
643
+ const fromCensus = cellAnswer !== null && censusCell && cellAnswer === checker.getTypeAtLocation(censusCell) ? null : cellAnswer;
639
644
  // Which of the three sources actually answered one named member. A record
640
645
  // that carries ONE dynamic field among 130 gives the reader no way to tell
641
646
  // "the checker was fine" from "the census had nothing to add".
@@ -42,7 +42,7 @@ import { indexedAccessMemberTypes } from './structural-indexed-access.js';
42
42
  import { joinedCallableOf } from './structural-joins.js';
43
43
  import { censusFreshDictionaryStorage, isNullPrototypeCreate, dictionaryArmIndexOf } from './fresh-dictionary-storage.js';
44
44
  import { creationOrderOf, creationOrderedProperties } from './structural-creation-order.js';
45
- import { collectionMemberResultTypeAt, contextualArrayConstructTypeAt, inferredArrayElementAt, statedCollectionTypeAt, inferredCollectionTypeArgumentsAt, unstatedNeverArray } from './structural-array-element.js';
45
+ import { collectionMemberResultTypeAt, contextualArrayConstructTypeAt, inferredArrayElementAt, statedCollectionTypeAt, inferredCollectionTypeArgumentsAt, readsUnjoinedArrayMember, unstatedNeverArray } from './structural-array-element.js';
46
46
  import { createDeclaredBodyResolver } from './structural-declared-body.js';
47
47
  import { emptyInstantiationCensus } from './instantiation.js';
48
48
  import { emptySpecializationCensus } from './specialization.js';
@@ -1250,6 +1250,30 @@ const structuralRules = [
1250
1250
  return null;
1251
1251
  }
1252
1252
  },
1253
+ {
1254
+ // The same box, read back through a computed key: each `never[]` arm the
1255
+ // checker answers is a member stored as the box.
1256
+ name: 'computed-read-of-unjoined-array-member',
1257
+ forms: [ts.SyntaxKind.ElementAccessExpression],
1258
+ resolve(node) {
1259
+ if (!ts.isElementAccessExpression(node))
1260
+ return null;
1261
+ const read = this.layoutTypeAt(node);
1262
+ const arms = read.isUnion() ? read.types : [read];
1263
+ const isNeverArray = (arm) => this.checker.isArrayType(arm) &&
1264
+ ((this.checker.getTypeArguments(arm)[0]?.flags ?? 0) & ts.TypeFlags.Never) !== 0;
1265
+ if (!arms.some(isNeverArray) || !readsUnjoinedArrayMember(this.checker, this.collections, this.layoutTypeAt, node))
1266
+ return null;
1267
+ const box = this.table.intern({
1268
+ kind: 'array',
1269
+ element: this.table.intern({ kind: 'primitive', primitive: 'any' }),
1270
+ readonly: false,
1271
+ extension: []
1272
+ });
1273
+ const members = [...new Set(arms.map((arm) => (isNeverArray(arm) ? box : this.typeOf(arm))))];
1274
+ return members.length === 1 ? members[0] : this.table.intern({ kind: 'union', members });
1275
+ }
1276
+ },
1253
1277
  {
1254
1278
  // The K/(V) a bare `new Map()`/`new Set()`/`new WeakMap()`/`new
1255
1279
  // WeakSet()` never states -- `collection-bindings.ts` has bound it since
@@ -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;
@@ -2098,20 +2098,29 @@ const emitTypedArrayConstruct = (ctx, lines, operation, result) => {
2098
2098
  return;
2099
2099
  }
2100
2100
  // 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.
2101
+ // off the BOX'S TAG instead, at run time, as ECMA-262 23.2.5.1 itself reads
2102
+ // it off the value: `Tag::Number` is the `length` overload, and anything
2103
+ // else is the numeric-Array copy `isNumericArrayCarrier` takes below.
2104
+ // The checker cannot pick for us: an `any` argument resolves to the first
2105
+ // declared overload, `length: number`, so `new Float32Array(out[k])` with
2106
+ // `k` from a `string[]` reached here as a length while the box held an
2107
+ // `ArrayObject<double>`, and the length read aborted.
2108
+ // `unboxedLoadText` renders both reads checked, so a box holding anything
2109
+ // else (a string, `undefined`, a boxed typed array or buffer, a non-number
2110
+ // element) aborts by name rather than being reinterpreted.
2108
2111
  //
2109
2112
  // `new Int32Array( n )` and `new Float32Array( flatSize )` in untyped
2110
2113
  // JavaScript are both a length through a parameter the source never typed.
2111
2114
  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})));`);
2115
+ const box = 'gea_typed_source';
2116
+ const number = { kind: 'scalar', domain: 'number' };
2117
+ const length = unboxedLoadText(number, box);
2118
+ const values = unboxedLoadText({ kind: 'array-object', element: number, ownership: 'shared-refcount', extension: null }, box);
2119
+ if (length !== null && values !== null) {
2120
+ lines.push(`${name} = ([&]() -> ${cppTypeOf(result)} { const gea::Value& ${box} = ${operandText(ctx, argument)}; ` +
2121
+ `if (${box}.tag() == gea::Value::Tag::Number) ` +
2122
+ `return gea::makeRef<${target}>(gea::detail::typedArrayLengthIndex(gea::detail::toIntegerOrInfinity(${length}))); ` +
2123
+ `return gea::makeRef<${target}>(${target}::fromValues(${values})); }());`);
2115
2124
  return;
2116
2125
  }
2117
2126
  }
@@ -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
@@ -110,6 +110,10 @@ export const coreHostMembers = new Map([
110
110
  // than a second severity: a server adapter writes one on the recoverable
111
111
  // client-abort path and refused by name until it existed.
112
112
  ['Console.info', { kind: 'method', emit: 'gea::host::console::info({args})', arity: 'variadic' }],
113
+ // `console.warn` writes what `console.error` writes, to stderr (see the
114
+ // runtime's `warn` overloads). An app's recoverable load-failure paths call
115
+ // it, and each call refused by name until this row existed.
116
+ ['Console.warn', { kind: 'method', emit: 'gea::host::console::warn({args})', arity: 'variadic' }],
113
117
  // `localStorage`. `gea::host::storage` is a singleton table rather than a
114
118
  // per-handle one, so no template here names a `{receiver}`.
115
119
  ['Storage.getItem', { kind: 'method', emit: 'gea::host::storage::getItem({arg0})', arity: 1 }],
@@ -44,6 +44,48 @@ import { type EmitContext } from '../emit-context.js';
44
44
  */
45
45
  /** The one signature every member's renderer has. `element` is the receiver's own element carrier; `result` is read by the members whose ECMA-262 result can be `undefined`. */
46
46
  export type ArrayCallRenderer = (ctx: EmitContext, receiverText: string, element: Representation, args: readonly IrOperand[], result: IrResult | null, operation?: CallOperation) => string;
47
+ /**
48
+ * The callback, as the runtime's per-element call can invoke it.
49
+ *
50
+ * `gea::runtime::array`'s `mapCall` (and its siblings) hand the callable the
51
+ * element AS the element's own C++ type, at whichever arity the callable takes.
52
+ * That is exact while the callback's first parameter IS the element carrier. A
53
+ * callback declared WIDER than the element -- `nums.map(label)` with `label:
54
+ * (x: number | string) => string`, or `pairs.map(([[, value]]) => value)` over
55
+ * a union of two tuple-array arms, whose parameter is the union of the two arms' tuple elements
56
+ * while each arm's array holds exactly one of them -- is a call whose argument
57
+ * needs the conversion any direct call renders at its call site, except that
58
+ * this call site is inside the runtime template. C++ does not perform it:
59
+ * `gea::TaggedUnion` has no converting constructor (arm injection is
60
+ * `ofArm<i>`, spelled by the emitter), so `is_invocable` fails at every arity
61
+ * and the template falls through to its last resort and does not compile --
62
+ * an error at the C++ step, after certification, about a program this backend
63
+ * had already accepted.
64
+ *
65
+ * So the conversion is rendered here, at the one boundary the emitter owns: a
66
+ * lambda of EXACTLY the callback's own arity that converts the element into
67
+ * the first parameter's carrier through `alignedValueText` -- the one authority
68
+ * on which pairs convert -- and forwards the index and the array untouched.
69
+ * Exactly the arity, never a variadic forwarder: `mapCall` picks its call by
70
+ * `is_invocable`, and a lambda that accepted anything would be picked at the
71
+ * three-argument arity and then fail to call a one-parameter callback inside
72
+ * its own body. The callable is init-captured by value so an rvalue callback
73
+ * expression is evaluated once, not once per element.
74
+ *
75
+ * Untouched when the first parameter already carries the element -- the text
76
+ * is exactly what it was, so nothing that emitted before moves -- and untouched
77
+ * for a callable that is not a `function-value-dispatch` or that declares a
78
+ * receiver, which the runtime passes `Undefined{}` for ahead of the element.
79
+ * Refused BY NAME when the pair has no conversion, when the index or array
80
+ * parameter is not the one the runtime hands over, or when the callback is
81
+ * variadic: a refusal at emission is the fail-closed answer the C++ error was
82
+ * standing in for.
83
+ *
84
+ * `Array.from`'s mapper crosses the same boundary inside `fromCall`, which
85
+ * hands it `(kValue, k)` and no array (23.1.2.1), so `handsArray` is false
86
+ * there and a third parameter is refused rather than declared.
87
+ */
88
+ export declare const elementAdaptedCallbackText: (ctx: EmitContext, member: string, clause: string, element: Representation, callback: IrOperand, result?: IrResult | null, operation?: CallOperation, handsArray?: boolean) => string;
47
89
  /** `emit-carrier-members.ts`'s `arrayAccessText` defers exactly these keys off an `array-object` receiver -- one authority for "is this method implemented". */
48
90
  export declare const arrayMethods: ReadonlyMap<string, ArrayCallRenderer>;
49
91
  /**