@geastack/compiler 1.0.41 → 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 (52) hide show
  1. package/dist/conversion/nodes.js +5 -2
  2. package/dist/ir/certify.js +1 -1
  3. package/dist/ir/facts.d.ts +3 -1
  4. package/dist/ir/facts.js +1 -0
  5. package/dist/ir/host-template-conversions.d.ts +2 -2
  6. package/dist/ir/host-template-conversions.js +73 -2
  7. package/dist/ir/integers.d.ts +6 -0
  8. package/dist/ir/integers.js +133 -0
  9. package/dist/ir/lower-destructuring.js +22 -3
  10. package/dist/ir/lower-operands.js +24 -0
  11. package/dist/ir/native-field-view-facts.d.ts +8 -1
  12. package/dist/ir/native-field-view-facts.js +13 -3
  13. package/dist/ir/operation-conversions.js +1 -1
  14. package/dist/ir/program-conversions.d.ts +1 -1
  15. package/dist/ir/program-conversions.js +68 -1
  16. package/dist/ir/property-read-conversions.js +7 -1
  17. package/dist/ir/publish-native-field-view-facts.js +4 -0
  18. package/dist/ir/reflection-demand.js +29 -3
  19. package/dist/projection/dispatch.d.ts +19 -1
  20. package/dist/projection/dispatch.js +34 -0
  21. package/dist/representation/value-records.js +182 -13
  22. package/dist/semantics/normalize/collection-bindings.d.ts +7 -0
  23. package/dist/semantics/normalize/collection-bindings.js +35 -1
  24. package/dist/semantics/normalize/derived-expression-type.js +49 -0
  25. package/dist/semantics/normalize/field-bindings.js +6 -1
  26. package/dist/semantics/normalize/flow/source-value-session.d.ts +9 -2
  27. package/dist/semantics/normalize/flow/source-value-session.js +538 -94
  28. package/dist/semantics/normalize/local-bindings.js +23 -1
  29. package/dist/semantics/normalize/producers/allocations.js +5 -1
  30. package/dist/semantics/normalize/producers/references.js +26 -18
  31. package/dist/semantics/normalize/structural-array-element.d.ts +7 -0
  32. package/dist/semantics/normalize/structural-array-element.js +24 -1
  33. package/dist/semantics/normalize/structural-layout-type.js +5 -1
  34. package/dist/semantics/normalize/structural-parts.js +13 -8
  35. package/dist/semantics/normalize/structural.js +25 -1
  36. package/dist/targets/cpp/class-properties/emit-class-properties.js +5 -1
  37. package/dist/targets/cpp/emit-callable.js +19 -10
  38. package/dist/targets/cpp/emit-context.d.ts +3 -0
  39. package/dist/targets/cpp/emit-context.js +3 -0
  40. package/dist/targets/cpp/emit-native-field-view.d.ts +2 -0
  41. package/dist/targets/cpp/emit-native-field-view.js +1 -1
  42. package/dist/targets/cpp/emit-properties.js +114 -12
  43. package/dist/targets/cpp/emit.js +7 -1
  44. package/dist/targets/cpp/host/emit-host-invoke.js +16 -2
  45. package/dist/targets/cpp/host/host-members.js +4 -0
  46. package/dist/targets/cpp/prototype/emit-prototype-array.d.ts +42 -0
  47. package/dist/targets/cpp/prototype/emit-prototype-array.js +31 -9
  48. package/dist/targets/cpp/records.js +39 -16
  49. package/dist/targets/cpp/translation-unit.js +23 -2
  50. package/package.json +1 -1
  51. package/src/targets/cpp/runtime/gea_dynamic_proxy.h +17 -1
  52. package/src/targets/cpp/runtime/gea_runtime.h +312 -51
@@ -331,9 +331,12 @@ export const createConversionNodes = (input) => {
331
331
  // A conditional can have one exact record arm and another record
332
332
  // that satisfies the same interface. Dispatch the complete source
333
333
  // when its native view is admitted; selecting the exact arm would
334
- // discard the other live value.
334
+ // discard the other live value. An optional record target is the
335
+ // same question: `this._c = c` into a `{...} | null` field selected
336
+ // the record arm of a `record | Vector3` parameter unchecked and
337
+ // stored the Vector3's bytes as the record.
335
338
  if (source.kind === 'tagged-union' &&
336
- (target.kind === 'record' || (target.kind === 'native-record-ref' && target.native === null)) &&
339
+ (nativeRecord.kind === 'record' || (nativeRecord.kind === 'native-record-ref' && nativeRecord.native === null)) &&
337
340
  (capability.materializer.armSelection !== undefined || capability.materializer.nativeSelection !== undefined)) {
338
341
  const complete = input.registry.structuralRecipe?.(source, target, nodeFor, undefined, nativeMethodFor, nodeById, dictionaryReadFor, checkedFrameNarrowingFor);
339
342
  if (complete?.recordView?.view.kind === 'dispatch')
@@ -1235,7 +1235,7 @@ const nativeFieldViewDemandsOf = (operation, ctx) => {
1235
1235
  const semantic = ctx.semanticOperationOf(operation.lineage);
1236
1236
  if (required &&
1237
1237
  receipt === undefined &&
1238
- nativeFieldViewOpenDocumentRead(operation, key, ctx.nativeFieldViewTargets ?? new Set(), ctx.nativeFieldViewDocumentTargets ?? new Set()))
1238
+ nativeFieldViewOpenDocumentRead(operation, key, ctx.nativeFieldViewTargets ?? new Set(), ctx.nativeFieldViewDocumentTargets ?? new Set(), ctx.nativeFieldViews))
1239
1239
  return [];
1240
1240
  const keyDomain = key === null && semantic?.family === 'property' ? computedPropertyKeyTextsOf(ctx.graph, semantic) : undefined;
1241
1241
  const copiedDomain = operation.provenKeyTexts;
@@ -35,6 +35,8 @@ export interface IrBodyCensus {
35
35
  readonly roundingArithmetic: ReadonlySet<IrValueId>;
36
36
  /** See `IntegerNarrowing.integerDivisions`. */
37
37
  readonly integerDivisions: ReadonlySet<IrValueId>;
38
+ /** See `IntegerNarrowing.nonZeroDivisors`. */
39
+ readonly nonZeroDivisors: ReadonlySet<IrValueId>;
38
40
  /** See `IntegerNarrowing.declaredWidths`. */
39
41
  readonly declaredWidths: ReadonlyMap<IrValueId, DeclaredIntegerWidth>;
40
42
  readonly exactNumericConversions: ReadonlySet<IrValueId>;
@@ -97,7 +99,7 @@ export interface IrBodyCensusPolicy {
97
99
  readonly copiedCapture: (declaration: DeclarationId) => boolean;
98
100
  }
99
101
  /** What is known when `formalStorage` runs: everything except the hoists and the two censuses that read them. */
100
- export type IrBodyCensusBeforeHoists = Pick<IrBodyCensus, 'localIterators' | 'deferrable' | 'callArgumentOnly' | 'forwardedBindings' | 'dead' | 'unread' | 'booleanConstants' | 'typeQueryValues' | 'typeQueryBindings' | 'typeQueryComparisons' | 'integerValues' | 'integerBindings' | 'float32' | 'remainderForms' | 'roundingArithmetic' | 'integerDivisions' | 'declaredWidths' | 'exactNumericConversions' | 'declaredIntegerCells' | 'numericCalls' | 'numericCallOnly'>;
102
+ export type IrBodyCensusBeforeHoists = Pick<IrBodyCensus, 'localIterators' | 'deferrable' | 'callArgumentOnly' | 'forwardedBindings' | 'dead' | 'unread' | 'booleanConstants' | 'typeQueryValues' | 'typeQueryBindings' | 'typeQueryComparisons' | 'integerValues' | 'integerBindings' | 'float32' | 'remainderForms' | 'roundingArithmetic' | 'integerDivisions' | 'nonZeroDivisors' | 'declaredWidths' | 'exactNumericConversions' | 'declaredIntegerCells' | 'numericCalls' | 'numericCallOnly'>;
101
103
  export declare const irBodyCensusOf: (body: IrBody, policy: IrBodyCensusPolicy) => IrBodyCensus;
102
104
  /**
103
105
  * Where every value in this body came from -- purely syntactic indices over
package/dist/ir/facts.js CHANGED
@@ -107,6 +107,7 @@ export const irBodyCensusOf = (body, policy) => {
107
107
  remainderForms,
108
108
  roundingArithmetic: narrowed.roundingArithmetic,
109
109
  integerDivisions: narrowed.integerDivisions,
110
+ nonZeroDivisors: narrowed.nonZeroDivisors,
110
111
  declaredWidths: narrowed.declaredWidths,
111
112
  exactNumericConversions: narrowed.exactNumericConversions,
112
113
  declaredIntegerCells: narrowed.declaredBindings,
@@ -5,7 +5,7 @@ import type { ClassLayout } from '../projection/classes.js';
5
5
  import type { RepresentationDeriver } from '../representation/derive.js';
6
6
  import { type Representation } from '../representation/model.js';
7
7
  import { type HostSpellings } from '../targets/cpp/host/host-members.js';
8
- import type { CallOperation, IrOperand, IrOperation } from './model.js';
8
+ import { type CallOperation, type IrBody, type IrOperand, type IrOperation } from './model.js';
9
9
  import type { HostMethodAlias } from './host-method-aliases.js';
10
10
  import type { OperationConversionInput } from './operation-conversions.js';
11
11
  /** A host row is authenticated by the producer of the callee, never its C++ spelling. */
@@ -19,7 +19,7 @@ export declare const hostTemplateMemberOf: (operation: CallOperation, definition
19
19
  */
20
20
  export declare const nativeArrayDescriptorSnapshotRequired: (operation: CallOperation, definitionOf: (value: IrValueId) => IrOperation | null, liveValues: ReadonlySet<IrValueId> | undefined, aliases?: ReadonlyMap<DeclarationId, HostMethodAlias>) => boolean;
21
21
  /** Internal template stores and callback arguments, independent of the ambient callable ABI. */
22
- export declare const hostTemplateConversionInputsOf: (operation: CallOperation, definitionOf: (value: IrValueId) => IrOperation | null, deriver: RepresentationDeriver, classes: ReadonlyMap<DeclarationId, ClassLayout>, hosts?: Pick<HostSpellings, "members">, aliases?: ReadonlyMap<DeclarationId, HostMethodAlias>) => readonly OperationConversionInput[];
22
+ export declare const hostTemplateConversionInputsOf: (operation: CallOperation, definitionOf: (value: IrValueId) => IrOperation | null, deriver: RepresentationDeriver, classes: ReadonlyMap<DeclarationId, ClassLayout>, hosts?: Pick<HostSpellings, "members">, aliases?: ReadonlyMap<DeclarationId, HostMethodAlias>, body?: IrBody) => readonly OperationConversionInput[];
23
23
  export interface HostObjectWalkPlan {
24
24
  readonly member: string;
25
25
  /** Only complete admitted callbacks are present. Omitted routes retain their static copy. */
@@ -4,9 +4,12 @@ import { abiOfCallee } from '../projection/callee.js';
4
4
  import { declaredRecordFieldOf, nativeBaseFieldOf, recordFieldsOfShape } from '../projection/fields.js';
5
5
  import { canonicalIndexLiteral } from '../representation/array-index.js';
6
6
  import { isNativeCallableCarrier } from '../representation/callable-object.js';
7
+ import { storedCarrier } from '../representation/primitives.js';
7
8
  import { hostReceiverProtocolOf } from '../representation/host-templates.js';
8
- import { representationKey } from '../representation/model.js';
9
+ import { isCanonicalNumberPropertyKeyText, representationKey } from '../representation/model.js';
9
10
  import { hostMemberOf } from '../targets/cpp/host/host-members.js';
11
+ import { allOperationsOf } from './model.js';
12
+ import { operandsOfIrOperation } from './queries.js';
10
13
  import { indexedRecordViewOf } from './certify/carrier-keys.js';
11
14
  import { nativePrototypeCallClaimsOf } from './native-prototype-calls.js';
12
15
  const dynamic = { kind: 'dynamic', reason: 'declared-any-never-narrowed' };
@@ -62,8 +65,62 @@ const descriptorValueOf = (deriver, result) => {
62
65
  const payload = result?.kind === 'optional' ? result.payload : result;
63
66
  return payload === undefined ? null : (knownFieldsOf(deriver, payload)?.find((field) => field.key === 'value')?.value ?? null);
64
67
  };
68
+ /**
69
+ * The `kValue` each `gea::runtime::array::from*` helper hands `Array.from`'s
70
+ * mapper (ECMA-262 23.1.2.1), or `null` where the mapper is passed unadapted.
71
+ *
72
+ * `fromLength` reads no element: it hands `Undefined{}` for every k, which is
73
+ * step 7.e.i's `Get(arrayLike, Pk)` only while the array-like holds none. The
74
+ * carrier cannot say so -- `ArrayLike<T>`'s index signature gives even
75
+ * `{ length: 8 }` an index table -- so the literal proves it. Each member
76
+ * definition answers the object it installed into, so the chain from the call
77
+ * back to the allocation is that one object; when every key on it is a
78
+ * non-numeric string and nothing but the next link and this call uses any of
79
+ * it, nothing can have stored an element before the call reads it.
80
+ */
81
+ const arrayFromElementOf = (call, definitionOf, body) => {
82
+ const source = call.arguments[0];
83
+ if (source === undefined)
84
+ return null;
85
+ const carrier = source.representation;
86
+ if (carrier.kind === 'array-object' || carrier.kind === 'iterator')
87
+ return carrier.element;
88
+ if (carrier.kind === 'typed-array')
89
+ return number;
90
+ if (carrier.kind === 'string')
91
+ return string;
92
+ if (carrier.kind === 'keyed-collection' && carrier.family === 'set')
93
+ return carrier.key;
94
+ if (body === undefined || (carrier.kind !== 'record' && carrier.kind !== 'record-with-index' && carrier.kind !== 'native-record-ref'))
95
+ return null;
96
+ const chain = new Set();
97
+ let value = source.value;
98
+ let definition = definitionOf(value);
99
+ while (definition?.kind === 'define-own-property') {
100
+ const key = definitionOf(definition.key.value);
101
+ if (key?.kind !== 'constant' || key.literal !== 'string' || isCanonicalNumberPropertyKeyText(key.text))
102
+ return null;
103
+ chain.add(value);
104
+ value = definition.receiver.value;
105
+ definition = definitionOf(value);
106
+ }
107
+ if (definition?.kind !== 'allocate-record' || definition.fields.some((field) => isCanonicalNumberPropertyKeyText(field.key)))
108
+ return null;
109
+ chain.add(value);
110
+ for (const block of body.blocks.values())
111
+ for (const operation of allOperationsOf(block)) {
112
+ const uses = operandsOfIrOperation(operation).filter((operand) => chain.has(operand.value));
113
+ if (uses.length === 0)
114
+ continue;
115
+ const isThisCall = operation.kind === 'call' && operation.lineage === call.lineage && operation.callee.value === call.callee.value;
116
+ const isLink = operation.kind === 'define-own-property' && operation.result !== null && chain.has(operation.result.id);
117
+ if (uses.length > 1 || !(isThisCall || isLink))
118
+ return null;
119
+ }
120
+ return undefinedValue;
121
+ };
65
122
  /** Internal template stores and callback arguments, independent of the ambient callable ABI. */
66
- export const hostTemplateConversionInputsOf = (operation, definitionOf, deriver, classes, hosts, aliases) => {
123
+ export const hostTemplateConversionInputsOf = (operation, definitionOf, deriver, classes, hosts, aliases, body) => {
67
124
  if (operation.nativeArrayDescriptorSnapshot || operation.nativeArrayDescriptorReinstallation)
68
125
  return [];
69
126
  const inputs = new Map();
@@ -87,6 +144,14 @@ export const hostTemplateConversionInputsOf = (operation, definitionOf, deriver,
87
144
  const callback = operation.arguments[0]?.representation;
88
145
  if (callback?.kind === 'function-value-dispatch' && callback.abi.receiver === null && callback.abi.parameters[0])
89
146
  add('prototype-callback', element, callback.abi.parameters[0].value);
147
+ // `map` mints its result, so each callback result enters the call's
148
+ // element as it is stored. A closure narrowed past the checker's `U`
149
+ // returns a carrier the published element does not hold.
150
+ if (member === 'map' &&
151
+ result?.kind === 'array-object' &&
152
+ callback?.kind === 'function-value-dispatch' &&
153
+ callback.abi.receiver === null)
154
+ add('prototype-result', storedCarrier(callback.abi.result), result.element);
90
155
  }
91
156
  // SortCompare hands the comparator two elements; the emitter converts
92
157
  // each into its parameter's carrier (`sortText`), so both pairs are
@@ -153,6 +218,12 @@ export const hostTemplateConversionInputsOf = (operation, definitionOf, deriver,
153
218
  }
154
219
  }
155
220
  const host = hostTemplateMemberOf(operation, definitionOf, aliases);
221
+ if (host?.protocol === 'ArrayConstructor' && host.member === 'from') {
222
+ const callback = operation.arguments[1]?.representation;
223
+ const element = callback ? arrayFromElementOf(operation, definitionOf, body) : null;
224
+ if (element && callback?.kind === 'function-value-dispatch' && callback.abi.receiver === null && callback.abi.parameters[0])
225
+ add('prototype-callback', element, callback.abi.parameters[0].value);
226
+ }
156
227
  if (host && hosts) {
157
228
  const row = hostMemberOf(hosts.members, host.protocol, host.member);
158
229
  if (row?.kind === 'method' && row.arity === 'pass-through') {
@@ -102,6 +102,12 @@ export interface IntegerNarrowing {
102
102
  * it anyway, and a `%` whose divisor is not a known non-zero constant.
103
103
  */
104
104
  readonly integerDivisions: ReadonlySet<IrValueId>;
105
+ /**
106
+ * The `%` among `integerDivisions` whose divisor the body proves odd
107
+ * (`oddValuesOf`), and so never zero: their helper keeps only the
108
+ * `MIN % -1` test, which -1, being odd, still needs.
109
+ */
110
+ readonly nonZeroDivisors: ReadonlySet<IrValueId>;
105
111
  /**
106
112
  * The narrowed values an `int`/`i32` annotation put there, each with its
107
113
  * machine width. Their `+ - *`, negation and updates WRAP at that width --
@@ -10,6 +10,7 @@ export const emptyIntegerNarrowing = {
10
10
  dynamicRemainders: new Set(),
11
11
  roundingArithmetic: new Set(),
12
12
  integerDivisions: new Set(),
13
+ nonZeroDivisors: new Set(),
13
14
  declaredWidths: new Map(),
14
15
  exactNumericConversions: new Set(),
15
16
  declaredBindings: new Map()
@@ -777,6 +778,14 @@ export const narrowableIntegersOf = (body, storage = noStorageFacts) => {
777
778
  }
778
779
  };
779
780
  const declared = declaredIntegerValuesOf(body, declaredCells, readsCell, computes, phis, numericConversions, valueRepresentations, integral, constants, isNumberScalarValue);
781
+ const odd = oddValuesOf(body, graph, readsCell, computes, phis, numericConversions, constants);
782
+ const nonZeroDivisors = new Set();
783
+ for (const value of declared.divisions) {
784
+ const compute = computes.get(value);
785
+ const divisor = compute?.form === 'binary' && compute.operator === '%' ? compute.operands[1] : undefined;
786
+ if (divisor !== undefined && odd.has(divisor.value))
787
+ nonZeroDivisors.add(value);
788
+ }
780
789
  const values = new Set(declared.values);
781
790
  const bindings = new Set();
782
791
  const declaredBindings = new Map();
@@ -866,6 +875,7 @@ export const narrowableIntegersOf = (body, storage = noStorageFacts) => {
866
875
  dynamicRemainders,
867
876
  roundingArithmetic,
868
877
  integerDivisions: declared.divisions,
878
+ nonZeroDivisors,
869
879
  declaredWidths: declared.widths,
870
880
  exactNumericConversions,
871
881
  declaredBindings
@@ -1268,3 +1278,126 @@ const cellReadRefinementsOf = (body, graph, readsCell, computes, constants, type
1268
1278
  }
1269
1279
  return refinements;
1270
1280
  };
1281
+ /**
1282
+ * The values a body proves odd, and so never zero.
1283
+ *
1284
+ * A trial-division loop's divisor (`for (let d: int = 3; d * d <= n; d += 2)
1285
+ * if (n % d === 0) ...`) starts odd and steps by an even constant, so it is
1286
+ * odd at every read. Without that proof its `%` keeps the guarded helper's
1287
+ * zero test, and clang lays the loop out around that branch: primes ran 8%
1288
+ * behind the same loop written in C++ and Rust on the Haswell benchmark
1289
+ * machine. Parity survives wrapping, so `int` and `i32` arithmetic keeps it.
1290
+ *
1291
+ * A value is odd when it is an odd constant, a numeric conversion of an odd
1292
+ * value, odd plus or minus an even constant, a product of two odd values, a
1293
+ * phi of odd values, or a read of a cell that holds an odd value on every path
1294
+ * to it. The cells take the forward dataflow `cellReadRefinementsOf` uses, met
1295
+ * by intersection: only a cell this body alone writes takes part, and the
1296
+ * entry, which a parameter's or an unwritten cell's value reaches, holds none.
1297
+ */
1298
+ const oddValuesOf = (body, graph, readsCell, computes, phis, numericConversions, constants) => {
1299
+ const facts = body.facts;
1300
+ const oddReads = new Set();
1301
+ if (facts === undefined)
1302
+ return oddReads;
1303
+ const captured = new Set(facts.capturedDeclarations);
1304
+ const eligible = (cell) => !facts.boxed.has(cell) && !captured.has(cell);
1305
+ const evenConstant = (value) => {
1306
+ const constant = constants.get(value);
1307
+ return constant !== undefined && constant % 2 === 0;
1308
+ };
1309
+ const odd = (value, seen = new Set()) => {
1310
+ if (seen.has(value))
1311
+ return false;
1312
+ seen.add(value);
1313
+ const constant = constants.get(value);
1314
+ if (constant !== undefined)
1315
+ return Math.abs(constant % 2) === 1;
1316
+ if (readsCell.has(value))
1317
+ return oddReads.has(value);
1318
+ const converted = numericConversions.get(value);
1319
+ if (converted !== undefined)
1320
+ return odd(converted.value, seen);
1321
+ const incoming = phis.get(value);
1322
+ if (incoming !== undefined)
1323
+ return incoming.length > 0 && incoming.every((operand) => odd(operand.value, new Set(seen)));
1324
+ const compute = computes.get(value);
1325
+ if (compute?.form !== 'binary')
1326
+ return false;
1327
+ const [left, right] = compute.operands;
1328
+ if (!left || !right)
1329
+ return false;
1330
+ if (compute.operator === '+' || compute.operator === '-')
1331
+ return (odd(left.value, new Set(seen)) && evenConstant(right.value)) || (evenConstant(left.value) && odd(right.value, new Set(seen)));
1332
+ if (compute.operator === '*')
1333
+ return odd(left.value, new Set(seen)) && odd(right.value, new Set(seen));
1334
+ return false;
1335
+ };
1336
+ const transfer = (blockId, entry) => {
1337
+ const state = new Set(entry);
1338
+ for (const operation of body.blocks.get(blockId)?.operations ?? []) {
1339
+ if (operation.kind === 'binding-read') {
1340
+ if (state.has(operation.declaration))
1341
+ oddReads.add(operation.result.id);
1342
+ else
1343
+ oddReads.delete(operation.result.id);
1344
+ continue;
1345
+ }
1346
+ if (operation.kind === 'binding-write') {
1347
+ if (eligible(operation.declaration) && odd(operation.value.value))
1348
+ state.add(operation.declaration);
1349
+ else
1350
+ state.delete(operation.declaration);
1351
+ continue;
1352
+ }
1353
+ if ('declaration' in operation && typeof operation.declaration === 'string')
1354
+ state.delete(operation.declaration);
1355
+ }
1356
+ return state;
1357
+ };
1358
+ const meet = (states) => {
1359
+ const [first, ...rest] = states;
1360
+ if (first === undefined)
1361
+ return new Set();
1362
+ return new Set([...first].filter((cell) => rest.every((other) => other.has(cell))));
1363
+ };
1364
+ // Optimistic, as in `cellReadRefinementsOf`: an unvisited predecessor adds
1365
+ // nothing to the meet, facts only shrink, and the entry starts empty.
1366
+ const exits = new Map();
1367
+ const entryOf = (blockId) => {
1368
+ const predecessors = graph.predecessors.get(blockId) ?? [];
1369
+ if (blockId === body.entry || predecessors.length === 0)
1370
+ return new Set();
1371
+ const visited = predecessors.map((predecessor) => exits.get(predecessor)).filter((state) => state !== undefined);
1372
+ return visited.length === 0 ? null : meet(visited);
1373
+ };
1374
+ const sameState = (left, right) => left !== undefined && left.size === right.size && [...right].every((cell) => left.has(cell));
1375
+ for (let changed = true, rounds = 0; changed; rounds++) {
1376
+ // An unsettled optimistic state is not a sound one.
1377
+ if (rounds === 64)
1378
+ return new Set();
1379
+ changed = false;
1380
+ for (const blockId of body.blockOrder) {
1381
+ const entry = entryOf(blockId);
1382
+ if (entry === null)
1383
+ continue;
1384
+ const exit = transfer(blockId, entry);
1385
+ if (sameState(exits.get(blockId), exit))
1386
+ continue;
1387
+ exits.set(blockId, exit);
1388
+ changed = true;
1389
+ }
1390
+ }
1391
+ // The settled states, applied once more, leave exactly the reads they prove.
1392
+ oddReads.clear();
1393
+ for (const blockId of body.blockOrder) {
1394
+ const entry = entryOf(blockId);
1395
+ if (entry !== null)
1396
+ transfer(blockId, entry);
1397
+ }
1398
+ const proved = new Set(oddReads);
1399
+ for (const value of [...computes.keys(), ...phis.keys(), ...numericConversions.keys()])
1400
+ if (odd(value))
1401
+ proved.add(value);
1402
+ return proved;
1403
+ };
@@ -1,5 +1,5 @@
1
1
  import { operationOfResult } from '../identity/ids.js';
2
- import { carriesUndefined, representationKey } from '../representation/model.js';
2
+ import { carriesUndefined, isArrayPatternCapable, representationKey } from '../representation/model.js';
3
3
  import { edgesOfKind } from '../semantics/model/edges.js';
4
4
  import { operandOf } from '../semantics/model/operands.js';
5
5
  import { IrLoweringBlockedError } from './lower-graph.js';
@@ -216,8 +216,27 @@ const lowerArrayPatternSource = (ctx, block, operation) => {
216
216
  throw new IrLoweringBlockedError(`an array binding pattern's source resolved to a tagged union none of whose arms carry the declared ` +
217
217
  `"${representationKey(declared)}" iterator-record shape`);
218
218
  }
219
- const value = ctx.builder.compute(block, lineage, 'require-tagged-union-arm', String(armIndex), [source], declared);
220
- source = { value, representation: declared };
219
+ // The guard below is ECMA-262 7.4.2's TypeError for an arm GetIterator
220
+ // rejects (`number` beside `number[]`). An arm the pattern can read
221
+ // positionally is no such value: `cond ? split(...) : [ids, []]` holds a
222
+ // tuple record beside the declared array, and refusing it at run time
223
+ // aborted on a valid program. Every arm then enters the declared carrier
224
+ // through its own conversion, dispatched on the live tag.
225
+ const arms = source.representation.arms;
226
+ if (arms.some((arm, index) => index !== armIndex && isArrayPatternCapable(arm.value))) {
227
+ const unconverted = arms.find((arm) => ctx.program.conversions.nodeFor(arm.value, declared).capability.kind === 'never');
228
+ if (unconverted !== undefined) {
229
+ throw new IrLoweringBlockedError(`an array binding pattern reads "${representationKey(declared)}" from a tagged union whose arm ` +
230
+ `"${representationKey(unconverted.value)}" has no conversion into it`);
231
+ }
232
+ const live = arms.map((_, index) => index);
233
+ const value = ctx.builder.mergeLiveArmRebuild(block, lineage, source, declared, live, false, ctx.program.conversions);
234
+ source = { value, representation: declared };
235
+ }
236
+ else {
237
+ const value = ctx.builder.compute(block, lineage, 'require-tagged-union-arm', String(armIndex), [source], declared);
238
+ source = { value, representation: declared };
239
+ }
221
240
  }
222
241
  if (isSnapshotSource(source.representation.kind) && declared.kind === 'array-object') {
223
242
  registerResult(ctx, operation, ctx.builder.allocateArrayObject(block, lineage, [{ kind: 'spread', value: source, from: 0 }], declared));
@@ -304,6 +304,7 @@ export const enter = (ctx, block, lineage, operation, operand, resolved) => {
304
304
  unproven ??
305
305
  assertedUnionEntry(ctx, block, lineage, operation, operand, resolved, answer.representation) ??
306
306
  unsharedFreshTableEntry(ctx, block, lineage, operand, resolved, answer.representation) ??
307
+ unprovenClassEntry(ctx, block, lineage, operand, resolved, answer.representation) ??
307
308
  convertTo(ctx, block, lineage, resolved, answer.representation) ??
308
309
  familyMemberEntry(ctx, block, lineage, operation, operand, resolved, answer.representation) ??
309
310
  assertedArmEntry(ctx, block, lineage, operand, resolved, answer.representation) ??
@@ -657,6 +658,29 @@ export const assertedClassReceiver = (ctx, block, lineage, operand, resolved, vi
657
658
  return null;
658
659
  return { value: ctx.builder.convert(block, lineage, node.id, held, target), representation: target };
659
660
  };
661
+ /**
662
+ * A base class handle entering a slot typed at one of its descendants while
663
+ * the operand's own type is still a class the slot does not accept: no
664
+ * `instanceof` narrowed it. The checker never matches a call made through an
665
+ * `any` callee against the body value flow finds for it -- three's
666
+ * `background.render( scene )` hands an `Object3D` to a `@param {Scene}` --
667
+ * and the ordinary downcast (`downcastClassRef`) trusts a guard that never
668
+ * ran, so the body then read a Mesh's bytes as a Scene. An assertion renders
669
+ * no guard either, and its operand carries the type of what it wraps. The
670
+ * checked downcast the census already has for `as Derived` receivers is the
671
+ * value when it is that class and a TypeError otherwise.
672
+ */
673
+ const unprovenClassEntry = (ctx, block, lineage, operand, resolved, slot) => {
674
+ if (resolved.representation.kind !== 'class-ref' || slot.kind !== 'class-ref')
675
+ return null;
676
+ const stated = ctx.constantDeriver.derive(operand.type);
677
+ if (stated.kind === 'class-ref' && (stated.declaration === slot.declaration || stated.ancestors.includes(slot.declaration)))
678
+ return null;
679
+ const node = ctx.program.conversions.assertedClassDowncastFor(resolved.representation, slot);
680
+ if (node === null)
681
+ return null;
682
+ return { value: ctx.builder.convert(block, lineage, node.id, resolved, slot), representation: slot };
683
+ };
660
684
  /** Whether a carrier has a `null` state of its own (a class reference's empty `Ref` is read separately). */
661
685
  const holdsNull = (representation) => {
662
686
  if (representation.kind === 'null' || representation.kind === 'dynamic')
@@ -90,8 +90,15 @@ export declare const nativeFieldViewDocumentTargetSetOf: (plans: readonly Native
90
90
  * receipt can exist for it, and none is needed: the ordinary native [[Get]]
91
91
  * reads the view's original Document entry, and a plain allocation its own
92
92
  * slots and sidecar.
93
+ *
94
+ * A fixed key that no layout, accessor or installed view of the receiver
95
+ * names (`parameters.morphAttributeCount` off a record that never declares
96
+ * it) is the same read once no receipt exists for it. Its only receipt route
97
+ * claims `undefined` and needs an unescaped allocation
98
+ * (`originalDescriptorAbsent`); a published record can gain the key in its
99
+ * sidecar, and the ordinary [[Get]] answers that too.
93
100
  */
94
- export declare const nativeFieldViewOpenDocumentRead: (operation: GetOperation | SetOperation, constantKey: string | null | undefined, targets: ReadonlySet<string>, documents: ReadonlySet<string>) => boolean;
101
+ export declare const nativeFieldViewOpenDocumentRead: (operation: GetOperation | SetOperation, constantKey: string | null | undefined, targets: ReadonlySet<string>, documents: ReadonlySet<string>, flow?: Pick<FieldFlow, "nativeFieldViewAbsentRoutesOf">) => boolean;
95
102
  /**
96
103
  * A receiver the host census resolved to a namespace PATH is no allocation:
97
104
  * `navigator.bluetooth.keyboard` has no object behind it, only spellings for
@@ -85,12 +85,22 @@ const carrierTargetsAreDocuments = (value, targets, documents) => {
85
85
  * receipt can exist for it, and none is needed: the ordinary native [[Get]]
86
86
  * reads the view's original Document entry, and a plain allocation its own
87
87
  * slots and sidecar.
88
+ *
89
+ * A fixed key that no layout, accessor or installed view of the receiver
90
+ * names (`parameters.morphAttributeCount` off a record that never declares
91
+ * it) is the same read once no receipt exists for it. Its only receipt route
92
+ * claims `undefined` and needs an unescaped allocation
93
+ * (`originalDescriptorAbsent`); a published record can gain the key in its
94
+ * sidecar, and the ordinary [[Get]] answers that too.
88
95
  */
89
- export const nativeFieldViewOpenDocumentRead = (operation, constantKey, targets, documents) => operation.kind === 'get' &&
90
- (constantKey === null || constantKey === undefined) &&
96
+ export const nativeFieldViewOpenDocumentRead = (operation, constantKey, targets, documents, flow) => operation.kind === 'get' &&
91
97
  operation.provenKeyTexts === undefined &&
92
98
  documents.size > 0 &&
93
- carrierTargetsAreDocuments(operation.receiver.representation, targets, documents);
99
+ carrierTargetsAreDocuments(operation.receiver.representation, targets, documents) &&
100
+ (constantKey === null || constantKey === undefined || keyNamedByNoDescriptor(operation.receiver.value, constantKey, flow));
101
+ const keyNamedByNoDescriptor = (receiver, key, flow) => flow
102
+ ?.nativeFieldViewAbsentRoutesOf?.(receiver, key)
103
+ ?.every((route) => route.originalAbsent === true || route.declaredAnyEntry === true) ?? false;
94
104
  /**
95
105
  * A receiver the host census resolved to a namespace PATH is no allocation:
96
106
  * `navigator.bluetooth.keyboard` has no object behind it, only spellings for
@@ -262,7 +262,7 @@ export const operationConversionInputsOf = (operation, keyText, deriver, classes
262
262
  for (const conversion of nativePrototypeConversionInputsOf(operation, prototypeClaims))
263
263
  add(conversion.role, conversion.source, conversion.target);
264
264
  if (definitionOf)
265
- for (const conversion of hostTemplateConversionInputsOf(operation, definitionOf, deriver, classes, hosts, hostMethodAliases))
265
+ for (const conversion of hostTemplateConversionInputsOf(operation, definitionOf, deriver, classes, hosts, hostMethodAliases, body))
266
266
  add(conversion.role, conversion.source, conversion.target);
267
267
  if (definitionOf)
268
268
  for (const conversion of promiseReactionConversionInputsOf(operation, definitionOf, classes))
@@ -7,7 +7,7 @@ import type { RepresentationDeriver } from '../representation/derive.js';
7
7
  import { type Representation } from '../representation/model.js';
8
8
  import type { IrBody } from './model.js';
9
9
  import type { ReflectionExposure } from './reflection-demand.js';
10
- export type ProgramConversionRole = 'async-entry' | 'construct-argument' | 'field-initializer' | 'dynamic-field-write' | 'prototype-method' | 'prototype-setter-argument' | 'prototype-setter-receiver' | 'prototype-getter-receiver' | 'prototype-getter-result' | 'virtual-receiver' | 'virtual-parameter' | 'virtual-result' | 'virtual-field';
10
+ export type ProgramConversionRole = 'async-entry' | 'construct-argument' | 'field-initializer' | 'dynamic-field-write' | 'dynamic-call-argument' | 'prototype-method' | 'prototype-setter-argument' | 'prototype-setter-receiver' | 'prototype-getter-receiver' | 'prototype-getter-result' | 'virtual-receiver' | 'virtual-parameter' | 'virtual-result' | 'virtual-field';
11
11
  /** One selected native artifact boundary, independent of operation-local conversions. */
12
12
  export interface ProgramConversionInput {
13
13
  readonly role: ProgramConversionRole;
@@ -1,9 +1,11 @@
1
+ import { abiOfCallee } from '../projection/callee.js';
1
2
  import { runtimeClassLayoutsOf } from '../projection/classes.js';
2
3
  import { virtualDispatchVerdictOf } from '../projection/dispatch.js';
3
4
  import { declaredRecordFieldOf, recordShapeLayoutsOf } from '../projection/fields.js';
4
5
  import { classMethodOverrideOf } from '../projection/fields.js';
5
6
  import { representationKey, walkRepresentation } from '../representation/model.js';
6
7
  import { dynamicRecordLoadNeedsPlan } from '../conversion/document-record-view.js';
8
+ import { recipeClosureOf } from '../conversion/recipe-closure.js';
7
9
  import { capturesNothing } from './captures.js';
8
10
  import { asyncPromiseViewOf } from './coroutine-bodies.js';
9
11
  import { allOperationsOf } from './model.js';
@@ -48,6 +50,41 @@ export const prototypePropertyDeclarationsOf = (classes, reflection) => {
48
50
  return held;
49
51
  };
50
52
  export const prototypeSetterValue = { kind: 'dynamic', reason: 'declared-any-never-narrowed' };
53
+ /**
54
+ * Whether the census carries out `any -> value`, every cited recipe included.
55
+ * A plan without one would refuse the whole program at certification; with no
56
+ * plan the one operation that reaches the slot keeps its named refusal.
57
+ */
58
+ const dynamicLoadInstalled = (value, conversions) => {
59
+ try {
60
+ const closure = recipeClosureOf([conversions.nodeFor(prototypeSetterValue, value)], conversions.nodeById);
61
+ return [...closure.values()].every((node) => node.capability.kind !== 'never');
62
+ }
63
+ catch {
64
+ // Conflicting citations are certification's `missing` verdict: no plan.
65
+ return false;
66
+ }
67
+ };
68
+ /**
69
+ * A Function field written through a dynamic receiver (`mat.onBeforeCompile =
70
+ * fn` on an `any` material) stores the box adapted to the field's own frame.
71
+ * Only the census knows which frames the runtime can adapt and whether the
72
+ * slot admits an unknown Function at all, so the write cites its installed
73
+ * reader; a field with none keeps the dispatcher's named refusal.
74
+ */
75
+ const dynamicCallableLoadInstalled = (value, conversions) => abiOfCallee(value) !== null && dynamicLoadInstalled(value, conversions);
76
+ /**
77
+ * The shared records a boxed callable's frame reads its arguments into: a
78
+ * record parameter, the present arm of an optional one, and an Array's
79
+ * element (each element crosses the same per-carrier rule).
80
+ */
81
+ const argumentRecordsOf = (value) => value.kind === 'optional'
82
+ ? argumentRecordsOf(value.payload)
83
+ : value.kind === 'array-object'
84
+ ? argumentRecordsOf(value.element)
85
+ : value.kind === 'record' || value.kind === 'record-with-index' || value.kind === 'native-record-ref'
86
+ ? [value]
87
+ : [];
51
88
  export const programConversionKey = (input) => JSON.stringify([input.role, input.owner, input.slot]);
52
89
  export const virtualConversionOwnerOf = (family, declaration) => JSON.stringify([family.root, family.key, family.role, family.copy ?? null, declaration]);
53
90
  /** Every conversion the final native construction, coroutine and virtual artifacts actually spell. */
@@ -58,10 +95,19 @@ export const programConversionInputsOf = (input) => {
58
95
  const inputs = new Map();
59
96
  const propertyDeclarations = prototypePropertyDeclarationsOf(input.classes, input.reflection);
60
97
  const prototypeDeclarations = new Set();
98
+ // Every frame a dynamic caller can invoke with its own arguments: a
99
+ // Function boxed into `any`, a prototype method a boxed instance answers
100
+ // with, and a callable own field a full-reflection receiver answers with.
101
+ const boxedFrames = [];
61
102
  for (const body of bodies) {
62
103
  const operations = [...body.blocks.values()].flatMap((block) => allOperationsOf(block));
63
104
  const definitions = new Map(operations.flatMap((operation) => (operation.kind === 'constant' ? [[operation.result.id, operation]] : [])));
64
105
  for (const operation of operations) {
106
+ if (operation.kind === 'convert' && operation.result.representation.kind === 'dynamic') {
107
+ const abi = abiOfCallee(operation.source.representation);
108
+ if (abi !== null)
109
+ boxedFrames.push(abi);
110
+ }
65
111
  if (operation.kind !== 'get' || constantPropertyKeyTextOf(definitions.get(operation.key.value)) !== 'prototype')
66
112
  continue;
67
113
  const receivers = operation.receiver.representation.kind === 'tagged-union'
@@ -110,12 +156,33 @@ export const programConversionInputsOf = (input) => {
110
156
  if (isPrivateNameKey(field.key))
111
157
  continue;
112
158
  const operations = demand.fieldOperations?.get(field.key);
159
+ const callable = abiOfCallee(field.value);
160
+ if (callable !== null && (demand.fieldOperations === undefined || operations?.has('read')))
161
+ boxedFrames.push(callable);
113
162
  if (demand.fieldOperations !== undefined && !operations?.has('write') && !operations?.has('define'))
114
163
  continue;
115
- if (dynamicRecordLoadNeedsPlan(field.value, layouts) || dynamicTableLoadNeedsPlan(field.value, layouts))
164
+ if (dynamicRecordLoadNeedsPlan(field.value, layouts) ||
165
+ dynamicTableLoadNeedsPlan(field.value, layouts) ||
166
+ dynamicCallableLoadInstalled(field.value, input.conversions))
116
167
  add('dynamic-field-write', owner, field.key, prototypeSetterValue, field.value);
117
168
  }
118
169
  }
170
+ for (const layout of runtimeClassLayoutsOf(input.classes))
171
+ if (propertyDeclarations === null || propertyDeclarations.has(layout.declaration))
172
+ for (const method of layout.methods) {
173
+ const abi = method.callable === null ? null : abiOf(method.callable);
174
+ if (abi !== null)
175
+ boxedFrames.push(abi);
176
+ }
177
+ for (const abi of boxedFrames)
178
+ for (const parameter of abi.parameters)
179
+ for (const record of argumentRecordsOf(parameter.value)) {
180
+ const owner = dynamicFieldConversionOwnerOf(record);
181
+ if (owner === null || inputs.has(programConversionKey({ role: 'dynamic-call-argument', owner, slot: '' })))
182
+ continue;
183
+ if (dynamicRecordLoadNeedsPlan(record, layouts) && dynamicLoadInstalled(record, input.conversions))
184
+ add('dynamic-call-argument', owner, '', prototypeSetterValue, record);
185
+ }
119
186
  for (const body of bodies) {
120
187
  const view = asyncPromiseViewOf(body);
121
188
  if (view?.abi && body.abi)
@@ -1,5 +1,5 @@
1
1
  import { classMemberOf, declaredRecordFieldOf, propertyReadResultRepresentationOf, recordAccessorsOfShape, recordFieldsOfShape } from '../projection/fields.js';
2
- import { virtualDispatchKey } from '../projection/dispatch.js';
2
+ import { classFieldAccessorArmsOf, virtualDispatchKey } from '../projection/dispatch.js';
3
3
  import { nativeExpandoSidecarOf } from '../projection/native-expando.js';
4
4
  import { regexpFieldStorageOf } from '../projection/regexp-fields.js';
5
5
  import { representationKey } from '../representation/model.js';
@@ -72,6 +72,12 @@ export const propertyReadConversionInputsOf = (operation, keyText, deriver, clas
72
72
  const physical = virtual?.result ?? propertyReadResultRepresentationOf(deriver, classes, abis, leaf, keyText);
73
73
  if (physical !== null)
74
74
  add(physical);
75
+ if (leaf.kind === 'class-ref' && !unionReceiver && operation.spreadSnapshot !== true)
76
+ for (const { accessor } of classFieldAccessorArmsOf(classes, leaf.declaration, keyText)) {
77
+ const result = accessor.getter === null ? undefined : abis.get(accessor.getter)?.result;
78
+ if (result !== undefined)
79
+ add(result);
80
+ }
75
81
  const member = leaf.kind === 'class-ref' ? classMemberOf(classes, leaf.declaration, keyText) : null;
76
82
  if (unionReceiver && (member === null || member.kind === 'field')) {
77
83
  const field = declaredRecordFieldOf(deriver, leaf, keyText, classes);
@@ -74,6 +74,10 @@ export const publishNativeFieldViewFacts = (input) => {
74
74
  ? nativeFieldViewReadOf(operation, key, flow, input.conversions)
75
75
  : (nativeFieldViewReadSelectionOf(operation, operation.provenKeyTexts ?? [], flow, input.conversions) ??
76
76
  nativeFieldViewOpenReadOf(operation, flow, input.conversions));
77
+ if (read === null && key !== undefined && nativeFieldViewOpenDocumentRead(operation, key, targets, documents, flow)) {
78
+ const { nativeFieldViewRead: previousRead, ...open } = ordinary;
79
+ return open;
80
+ }
77
81
  return read === null
78
82
  ? ordinary
79
83
  : {