@geastack/compiler 1.0.63 → 1.0.65

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 (82) hide show
  1. package/dist/cli-emit.js +14 -5
  2. package/dist/conversion/dictionary-view.js +13 -2
  3. package/dist/conversion/document-record-view.d.ts +0 -1
  4. package/dist/conversion/document-record-view.js +30 -3
  5. package/dist/conversion/impossible-field-read.d.ts +9 -0
  6. package/dist/conversion/impossible-field-read.js +26 -0
  7. package/dist/conversion/nodes.d.ts +12 -0
  8. package/dist/conversion/nodes.js +106 -2
  9. package/dist/conversion/record-view.js +21 -0
  10. package/dist/ir/build.d.ts +5 -2
  11. package/dist/ir/build.js +9 -2
  12. package/dist/ir/callable-class-flow.js +233 -13
  13. package/dist/ir/certify/parallel-region.js +1 -0
  14. package/dist/ir/certify.js +32 -2
  15. package/dist/ir/hoist.js +15 -1
  16. package/dist/ir/host-template-conversions.js +12 -0
  17. package/dist/ir/lower-invocation.js +42 -2
  18. package/dist/ir/lower-property.js +2 -2
  19. package/dist/ir/model.d.ts +18 -6
  20. package/dist/ir/native-callable-data-reads.js +15 -2
  21. package/dist/ir/native-field-view-domains.d.ts +8 -0
  22. package/dist/ir/native-field-view-domains.js +44 -3
  23. package/dist/ir/native-field-view-facts.d.ts +2 -2
  24. package/dist/ir/native-field-view-facts.js +57 -13
  25. package/dist/ir/native-own-assignment.js +20 -2
  26. package/dist/ir/program-conversions.js +38 -7
  27. package/dist/ir/property-read-conversions.js +14 -5
  28. package/dist/ir/publish-native-field-view-facts.js +1 -1
  29. package/dist/ir/queries.js +2 -0
  30. package/dist/ir/read-only-dictionary.js +138 -15
  31. package/dist/ir/reflection-demand.js +7 -1
  32. package/dist/ir/shake.js +26 -6
  33. package/dist/ir/typed-property-access.d.ts +20 -0
  34. package/dist/ir/typed-property-access.js +56 -0
  35. package/dist/projection/bindings.js +14 -19
  36. package/dist/projection/fields.js +7 -1
  37. package/dist/projection/native-object-data.d.ts +8 -1
  38. package/dist/projection/native-object-data.js +16 -4
  39. package/dist/representation/derive.js +67 -1
  40. package/dist/representation/proxy-carriers.js +17 -2
  41. package/dist/representation/publish.js +34 -0
  42. package/dist/semantics/callable-own-data-slots.js +71 -6
  43. package/dist/semantics/model/operations.d.ts +15 -4
  44. package/dist/semantics/native-own-assignment.d.ts +3 -0
  45. package/dist/semantics/normalize/collection-bindings.js +2 -2
  46. package/dist/semantics/normalize/flow/array-element-continuation.d.ts +1 -1
  47. package/dist/semantics/normalize/flow/array-element-continuation.js +32 -9
  48. package/dist/semantics/normalize/flow/callable-reach.d.ts +3 -5
  49. package/dist/semantics/normalize/flow/callable-reach.js +3 -5
  50. package/dist/semantics/normalize/flow/component-solver.d.ts +2 -0
  51. package/dist/semantics/normalize/flow/component-solver.js +32 -6
  52. package/dist/semantics/normalize/flow/computed-key-set.js +53 -1
  53. package/dist/semantics/normalize/flow/source-value-session.js +16 -14
  54. package/dist/semantics/normalize/producers/invocations.js +40 -1
  55. package/dist/semantics/normalize/producers/native-own-assignment.js +12 -4
  56. package/dist/semantics/normalize/reachability.js +18 -8
  57. package/dist/semantics/normalize/structural-mutable-field.d.ts +1 -0
  58. package/dist/semantics/normalize/structural-mutable-field.js +170 -4
  59. package/dist/semantics/normalize/structural-parts.js +6 -1
  60. package/dist/semantics/normalize/structural-self-reference.d.ts +1 -1
  61. package/dist/semantics/normalize/structural-self-reference.js +9 -1
  62. package/dist/semantics/normalize/structural.js +10 -1
  63. package/dist/semantics/program.js +102 -1
  64. package/dist/targets/cpp/class-properties/emit-class-properties.js +9 -0
  65. package/dist/targets/cpp/emit-allocation.js +22 -1
  66. package/dist/targets/cpp/emit-bindings.js +5 -5
  67. package/dist/targets/cpp/emit-exceptions.js +6 -0
  68. package/dist/targets/cpp/emit-narrowing.js +24 -2
  69. package/dist/targets/cpp/emit-native-field-view.d.ts +1 -1
  70. package/dist/targets/cpp/emit-native-field-view.js +37 -5
  71. package/dist/targets/cpp/emit-native-own-assignment.js +5 -1
  72. package/dist/targets/cpp/emit-record-view.js +6 -1
  73. package/dist/targets/cpp/emit-tonumber.d.ts +22 -11
  74. package/dist/targets/cpp/emit-tonumber.js +86 -25
  75. package/dist/targets/cpp/emit.js +3 -0
  76. package/dist/targets/cpp/host/emit-host-invoke.js +6 -6
  77. package/dist/targets/cpp/prototype/emit-prototype-array.js +13 -1
  78. package/dist/targets/cpp/records.js +15 -7
  79. package/dist/targets/cpp/recursive-containers.js +5 -1
  80. package/dist/targets/cpp/translation-unit.js +17 -2
  81. package/package.json +4 -2
  82. package/src/targets/cpp/runtime/gea_runtime.h +212 -7
@@ -190,6 +190,60 @@ unwrittenMembers = new Map()) => {
190
190
  };
191
191
  /** The carrier a *stored* position holds -- see `storedCarrier`. */
192
192
  const deriveStored = (id) => storedCarrier(derive(id));
193
+ /**
194
+ * The earlier instantiation of the same generic record declaration whose
195
+ * type arguments carry identically, or `null` when this one is the first.
196
+ *
197
+ * A generic class is one struct per LAYOUT (`classGroupsOf`): its copies are
198
+ * grouped by the representation of their fillings, so `List<any>` and
199
+ * `List<unknown>` -- both fillings the `dynamic` carrier -- are one struct.
200
+ * A record type built over the filling has to group the same way, or that
201
+ * one struct's field is typed `ListNode<any>` while the copy's own body
202
+ * reads and writes it as `ListNode<unknown>`: two nominal shapes with the
203
+ * same fields and no conversion between them, because none should exist --
204
+ * they are one object seen through two spellings of "anything". Keyed the
205
+ * way `classArgumentKeyOf` keys a class filling, and answered by the first
206
+ * instantiation in table order so every walk names the same shape.
207
+ */
208
+ let declaredInstantiations = null;
209
+ const declaredLayoutTwinOf = (id, shape) => {
210
+ if (shape.typeArguments.length === 0)
211
+ return null;
212
+ if (declaredInstantiations === null) {
213
+ declaredInstantiations = new Map();
214
+ for (const [candidate, entry] of types) {
215
+ if (entry.shape.kind !== 'declared' || entry.shape.typeArguments.length === 0 || entry.shape.body === null)
216
+ continue;
217
+ const known = declaredInstantiations.get(entry.shape.declaration);
218
+ if (known)
219
+ known.push(candidate);
220
+ else
221
+ declaredInstantiations.set(entry.shape.declaration, [candidate]);
222
+ }
223
+ }
224
+ const candidates = declaredInstantiations.get(shape.declaration) ?? [];
225
+ if (candidates.length < 2 || candidates[0] === id)
226
+ return null;
227
+ const argumentKeyOf = (argument) => {
228
+ const filling = shapeOf(argument);
229
+ if (filling?.kind === 'declared' && filling.declaration === shape.declaration)
230
+ return `self:${argument}`;
231
+ return representationKey(deriveStored(argument));
232
+ };
233
+ const own = shape.typeArguments.map(argumentKeyOf).join(',');
234
+ for (const candidate of candidates) {
235
+ if (candidate === id)
236
+ return null;
237
+ const other = shapeOf(candidate);
238
+ if (other?.kind !== 'declared' || other.typeArguments.length !== shape.typeArguments.length || other.body === null)
239
+ continue;
240
+ if (shapeOf(other.body)?.kind !== 'object')
241
+ continue;
242
+ if (other.typeArguments.map(argumentKeyOf).join(',') === own)
243
+ return candidate;
244
+ }
245
+ return null;
246
+ };
193
247
  const isDataOnlyBody = (id) => isDataOnlyObjectShape(shapeOf(id), shapeOf);
194
248
  /**
195
249
  * The container which a recursive type identity denotes, without expanding
@@ -2733,11 +2787,23 @@ unwrittenMembers = new Map()) => {
2733
2787
  // the name and the body one answer, which is what `publish.ts` seals.
2734
2788
  if (valueRecords.forType(shape.body))
2735
2789
  return derive(shape.body);
2790
+ const nominal = {
2791
+ kind: 'native-record-ref',
2792
+ shapeId: shape.body,
2793
+ ownership: ownership.forShape(shape, id),
2794
+ native: null
2795
+ };
2796
+ const twin = declaredLayoutTwinOf(id, shape);
2797
+ if (twin !== null) {
2798
+ const shared = derive(twin);
2799
+ if (shared.kind === 'native-record-ref' && shared.native === null && shared.ownership === nominal.ownership)
2800
+ return shared;
2801
+ }
2736
2802
  // Otherwise a declared name is carried nominally: its layout is
2737
2803
  // resolved from the sealed table by shape id at emission. Expanding it
2738
2804
  // here is what would make `interface Node { next: Node }` an infinite
2739
2805
  // carrier.
2740
- return { kind: 'native-record-ref', shapeId: shape.body, ownership: ownership.forShape(shape, id), native: null };
2806
+ return nominal;
2741
2807
  }
2742
2808
  case 'object-anchor': {
2743
2809
  // A callable-bearing object literal's nominal anchor (`structural.ts`).
@@ -72,6 +72,14 @@ export const proxyCarriersOf = (graph, deriver, statics = staticMembersOf(graph,
72
72
  continue;
73
73
  if (operation.family === 'binding')
74
74
  followed.add(value.id);
75
+ // A `require` of a package absent from this build only throws
76
+ // MODULE_NOT_FOUND (`staticRequireOutcomeOf`): its result never holds a
77
+ // value, so it is followed and stays empty. Read as "other", the optional
78
+ // dependency loader `try { return require('x') } catch { return
79
+ // makeErrorModule(e) }` kept the module's declared record arm beside the
80
+ // proxy it is the only thing that ever returns.
81
+ else if (operation.family === 'invocation' && operation.commonJsRequire !== undefined && 'absentPackage' in operation.commonJsRequire)
82
+ followed.add(value.id);
75
83
  else if (operation.family === 'computation' && operation.form === 'assignment' && operation.operator === '=')
76
84
  followed.add(value.id);
77
85
  else if (calleeOf(operation) !== undefined)
@@ -133,8 +141,15 @@ export const proxyCarriersOf = (graph, deriver, statics = staticMembersOf(graph,
133
141
  const field = staticFieldByDeclaration.get(operation.declaration);
134
142
  if (!field)
135
143
  continue;
136
- // A field declared without an initializer starts `undefined`.
137
- const initializer = field.initializer === null ? undefined : callables.get(field.initializer);
144
+ // A field declared without an initializer starts `undefined`, and that
145
+ // absence is the static-field-absence census's to add to the cell and
146
+ // every read of it (`staticFieldAbsenceOf`). Read as "other" here, it
147
+ // also restored the declared type's every arm: `_awsSDK ??=
148
+ // loadOptional()` over a loader that only returns its error proxy kept
149
+ // the module record arm, whose method calls have no receiver protocol.
150
+ if (field.initializer === null)
151
+ continue;
152
+ const initializer = callables.get(field.initializer);
138
153
  join(heldOf(staticCells, operation.declaration), initializer === undefined ? undefined : heldOf(returns, initializer));
139
154
  continue;
140
155
  }
@@ -528,6 +528,33 @@ const dynamicCallableValueOf = (result, callableOrigins, dynamicCallables) => {
528
528
  ? { kind: 'dynamic', reason: 'opt-in-fallback' }
529
529
  : null;
530
530
  };
531
+ const absentRequireCells = new WeakMap();
532
+ /** Cells written only by `require`s of absent packages, and never declared without a value. */
533
+ const absentRequireCellsOf = (graph) => {
534
+ const known = absentRequireCells.get(graph);
535
+ if (known)
536
+ return known;
537
+ const verdicts = new Map();
538
+ const absentRequireResult = (operand) => {
539
+ if (operand?.source.kind !== 'result')
540
+ return false;
541
+ const producer = graph.operations.get(graph.results.get(operand.source.result) ?? '');
542
+ return producer?.family === 'invocation' && producer.commonJsRequire?.target === null;
543
+ };
544
+ for (const operation of graph.operations.values()) {
545
+ if (operation.family !== 'binding' || operation.action === 'read')
546
+ continue;
547
+ if (verdicts.get(operation.declaration) === false)
548
+ continue;
549
+ const stores = (operation.action === 'initialize' || operation.action === 'write') &&
550
+ operation.parameterInitialization !== true &&
551
+ absentRequireResult(operation.operands.find((operand) => operand.evaluation.kind !== 'provenance'));
552
+ verdicts.set(operation.declaration, stores);
553
+ }
554
+ const cells = new Set([...verdicts].flatMap(([declaration, only]) => (only ? [declaration] : [])));
555
+ absentRequireCells.set(graph, cells);
556
+ return cells;
557
+ };
531
558
  /**
532
559
  * CommonJS module records are the one explicitly dynamic host boundary here.
533
560
  * The checker authenticated the wrapper declaration and normalization carried
@@ -541,6 +568,13 @@ const commonJsBoundaryOf = (graph, operation) => {
541
568
  // module that does not exist.
542
569
  if (operation?.family === 'invocation' && operation.commonJsRequire?.target === null)
543
570
  return { kind: 'undefined' };
571
+ // So is a cell every write of which is such a require: `const peer =
572
+ // require('absent'); return peer` never stores, so `peer` holds nothing
573
+ // either. Laid out at its consumer's type instead, the dead `return peer`
574
+ // asked for a conversion from that type into whatever the function really
575
+ // returns -- the loader's error Proxy alone -- which no recipe has.
576
+ if (operation?.family === 'binding' && absentRequireCellsOf(graph).has(operation.declaration))
577
+ return { kind: 'undefined' };
544
578
  if (operation?.family === 'invocation' &&
545
579
  operation.commonJsRequire !== undefined &&
546
580
  !('nativeRecord' in operation.commonJsRequire && operation.commonJsRequire.nativeRecord === true))
@@ -339,11 +339,74 @@ const inventoryOf = (graph, native) => {
339
339
  observeAll(functions, { operation, target, key: null, kind: 'publication' });
340
340
  }
341
341
  }
342
+ // A Function no operation publishes, which is stored only into its own data
343
+ // slots (`saslprep.saslprep = saslprep`) and whose stored self is never read
344
+ // back into a value the origins lose, is held only by values whose origins
345
+ // name it. A write through an unknown target therefore cannot reach it. The
346
+ // obligation is coinductive over the same origins every `exposure` blocker
347
+ // already trusts: a read of a self-storing key either keeps the Function's
348
+ // origin or is consumed only as a callee.
349
+ let consumers = null;
350
+ const consumersOf = (result) => {
351
+ if (consumers === null) {
352
+ consumers = new Map();
353
+ for (const operation of graph.operations.values())
354
+ for (const operand of operation.operands) {
355
+ if (operand.source.kind !== 'result')
356
+ continue;
357
+ const bucket = consumers.get(operand.source.result) ?? [];
358
+ if (bucket[bucket.length - 1] !== operation)
359
+ bucket.push(operation);
360
+ consumers.set(operand.source.result, bucket);
361
+ }
362
+ }
363
+ return consumers.get(result) ?? [];
364
+ };
365
+ const calledOnly = (result) => consumersOf(result).every((consumer) => consumer.family === 'invocation' &&
366
+ consumer.operands.every((operand) => operand.source.kind !== 'result' || operand.source.result !== result || operand.role === 'callee'));
367
+ const selfKeys = new Map();
368
+ for (const write of writes) {
369
+ if (write.value === null || write.value === undefined || write.value.source.kind !== 'result')
370
+ continue;
371
+ if (write.kind !== 'set' && write.kind !== 'define-own-property' && write.kind !== 'reflect-set')
372
+ continue;
373
+ const targets = sourcesOf(write.result);
374
+ for (const functionId of sourcesOf(write.value.source.result)) {
375
+ const keys = selfKeys.get(functionId);
376
+ if (keys === null)
377
+ continue;
378
+ if (write.key === null || targets.length !== 1 || targets[0] !== functionId)
379
+ selfKeys.set(functionId, null);
380
+ else
381
+ selfKeys.set(functionId, (keys ?? new Set()).add(write.key));
382
+ }
383
+ }
384
+ const confined = (functionId) => {
385
+ const keys = selfKeys.get(functionId);
386
+ if (keys === null || (exposures.get(functionId)?.length ?? 0) > 0)
387
+ return false;
388
+ return (observations.get(functionId) ?? []).every((observed) => {
389
+ if (observed.kind === 'publication' || observed.kind === 'prototype' || observed.kind === 'invocation-receiver')
390
+ return false;
391
+ if (observed.kind !== 'get' && observed.kind !== 'descriptor')
392
+ return true;
393
+ if (keys === undefined || (observed.key !== null && !keys.has(observed.key)))
394
+ return true;
395
+ return (observed.kind === 'get' &&
396
+ observed.key !== null &&
397
+ observed.operation.results.every((value) => sourcesOf(value.id).includes(functionId) || calledOnly(value.id)));
398
+ });
399
+ };
400
+ const confinedOwners = new Set();
401
+ for (const functionId of new Set([...allocations.keys(), ...[...origins.values()].flat()]))
402
+ if (confined(functionId))
403
+ confinedOwners.add(functionId);
342
404
  const blockerList = blockerInterner();
343
405
  const schemas = new Map();
344
406
  for (const [functionId, keys] of owned) {
345
407
  const perKey = new Map();
346
408
  const blockingWrites = blockingWritesOf(functionId);
409
+ const reachable = (write) => unknownTargetWriteSet.has(write) && !confinedOwners.has(functionId);
347
410
  for (const [key, writers] of keys) {
348
411
  const blockers = blockerList();
349
412
  const add = blockers.add;
@@ -366,13 +429,11 @@ const inventoryOf = (graph, native) => {
366
429
  // Without a prior own-descriptor receipt, all schemas for this owner
367
430
  // must retain the possible inherited-chain change, including writes
368
431
  // through an identity the inventory cannot isolate from this owner.
369
- if (write.key === '__proto__' &&
370
- (write.kind === 'set' || write.kind === 'reflect-set') &&
371
- (own || unknownTargetWriteSet.has(write)))
432
+ if (write.key === '__proto__' && (write.kind === 'set' || write.kind === 'reflect-set') && (own || reachable(write)))
372
433
  add(write.operation, 'inherited-chain');
373
434
  if (write.key !== null && write.key !== key)
374
435
  continue;
375
- if (unknownTargetWriteSet.has(write))
436
+ if (reachable(write))
376
437
  add(write.operation, 'unknown-target');
377
438
  if (prototypeWriteSet.has(write))
378
439
  add(write.operation, 'prototype-mutation');
@@ -407,16 +468,20 @@ const inventoryOf = (graph, native) => {
407
468
  // order; `inherited-chain` joins it only where the target is unknown, and
408
469
  // `unknown-key` needs ownership, so both stay per owner otherwise.
409
470
  const shared = blockerList();
471
+ const confinedShared = blockerList();
410
472
  for (const index of sharedWriteIndexes) {
411
473
  const write = writes[index];
412
474
  if (unknownTargetWriteSet.has(write))
413
475
  shared.add(write.operation, 'unknown-target');
414
- if (prototypeWriteSet.has(write))
476
+ if (prototypeWriteSet.has(write)) {
415
477
  shared.add(write.operation, 'prototype-mutation');
478
+ confinedShared.add(write.operation, 'prototype-mutation');
479
+ }
416
480
  if (write.key === '__proto__' && (write.kind === 'set' || write.kind === 'reflect-set') && unknownTargetWriteSet.has(write))
417
481
  shared.add(write.operation, 'inherited-chain');
418
482
  }
419
483
  const sharedBlockers = shared.list();
484
+ const confinedSharedBlockers = confinedShared.list();
420
485
  for (const functionId of new Set([...allocations.keys(), ...[...origins.values()].flat()])) {
421
486
  const blockers = blockerList();
422
487
  const add = blockers.add;
@@ -438,7 +503,7 @@ const inventoryOf = (graph, native) => {
438
503
  writes: (ownWriteIndexes.get(functionId) ?? []).map((index) => writes[index]),
439
504
  observations: observations.get(functionId) ?? [],
440
505
  blockers: blockers.list(),
441
- sharedBlockers
506
+ sharedBlockers: confinedOwners.has(functionId) ? confinedSharedBlockers : sharedBlockers
442
507
  });
443
508
  }
444
509
  return { owners, schemas, unknownTargetWrites, prototypeWrites };
@@ -264,6 +264,20 @@ export interface BindingOperation extends SemanticOperationBase {
264
264
  readonly nativeRecord?: true;
265
265
  };
266
266
  }
267
+ /** A literal host builtin lookup whose ModuleRecord must be retained. */
268
+ export interface CallBuiltinModuleLookup {
269
+ readonly target: RegionId;
270
+ readonly builtinModule: string;
271
+ /**
272
+ * The ES module namespace a literal lookup of an ES-module builtin denotes:
273
+ * each export's key and the cell that holds it. Absent for a CommonJS
274
+ * target, or when some export is a mutable binding a snapshot cannot track.
275
+ */
276
+ readonly namespace?: readonly {
277
+ readonly key: string;
278
+ readonly declaration: DeclarationId;
279
+ }[];
280
+ }
267
281
  /** Evaluated `[[Call]]` and `[[Construct]]`, plus tagged-template application. */
268
282
  export interface InvocationOperation extends SemanticOperationBase {
269
283
  /** Actual unmodified standard Object()/new Object(), with no arguments. */
@@ -292,10 +306,7 @@ export interface InvocationOperation extends SemanticOperationBase {
292
306
  readonly builtinModule: null;
293
307
  };
294
308
  /** A literal host builtin lookup whose ModuleRecord must be retained. */
295
- readonly builtinModuleLookup?: {
296
- readonly target: RegionId;
297
- readonly builtinModule: string;
298
- };
309
+ readonly builtinModuleLookup?: CallBuiltinModuleLookup;
299
310
  /** A checker-authenticated intrinsic that mutates its first argument. */
300
311
  readonly intrinsicMutation?: 'object-assign' | 'reflect-set' | 'object-define-property' | 'object-define-properties';
301
312
  /** Exact allocation/slot families consumed by the native bulk assignment authority. */
@@ -10,6 +10,9 @@ export interface NativeOwnAssignmentValue {
10
10
  readonly kind: 'function';
11
11
  readonly callable: FunctionId;
12
12
  };
13
+ /** The slot may be absent here: a read observes `undefined`, but nothing
14
+ * stores it -- the key's presence, not its storage, carries this value. */
15
+ readonly absence?: true;
13
16
  }
14
17
  /** A direct slot projects the same complete source closure as bulk copies.
15
18
  * Every root names the original allocation; the consumer's view is not storage.
@@ -2,7 +2,7 @@ import ts from '#typescript';
2
2
  import { censusRefusal } from './census-refusal.js';
3
3
  import { disjointUnionTypeOf, isStandardInterfaceType, joinOfWrites, literalMemberNameOf, widestOf } from './derived-expression-type.js';
4
4
  import { emptyParameterBindingCensus } from './parameter-bindings.js';
5
- import { closedArrayStoredValuesOf } from './flow/callable-reach.js';
5
+ import { closedArrayIsProvenEmpty } from './flow/callable-reach.js';
6
6
  import { deferredIntrinsicProtocolLedgerOf } from './deferred-intrinsic-protocols.js';
7
7
  import { forEachReachableStatement } from './reachability.js';
8
8
  /** A census that binds nothing, for callers that state no program. */
@@ -734,7 +734,7 @@ flow) => {
734
734
  const literals = [...aliases].flatMap((alias) => arraysByOwner.get(alias) ?? []);
735
735
  if (literals.length === 0)
736
736
  return false;
737
- const proof = ledger.capture(() => literals.every((literal) => closedArrayStoredValuesOf(checker, flow, literal)?.length === 0));
737
+ const proof = ledger.capture(() => literals.every((literal) => closedArrayIsProvenEmpty(checker, flow, literal)));
738
738
  if (!proof.value)
739
739
  return false;
740
740
  neverStoredRequirements.push(...proof.requirements);
@@ -24,4 +24,4 @@ import type { OriginAuthority } from './origin-authority.js';
24
24
  * parameter frame. No standalone frame inference or authority-free cache is
25
25
  * accepted.
26
26
  */
27
- export declare const arrayStoredValuesOf: (checker: ts.TypeChecker, flow: ValueFlowIndex, array: ts.Expression, authority: OriginAuthority) => readonly ts.Expression[] | null;
27
+ export declare const arrayStoredValuesOf: (checker: ts.TypeChecker, flow: ValueFlowIndex, array: ts.Expression, authority: OriginAuthority, goal?: "all" | "empty") => readonly ts.Expression[] | null;
@@ -974,7 +974,7 @@ const REFUSED = { seed: false, admitted: false, dependencies: [] };
974
974
  const VACUOUS = { seed: false, admitted: true, dependencies: [] };
975
975
  const SEED = { seed: true, admitted: true, dependencies: [] };
976
976
  const through = (dependencies) => ({ seed: false, admitted: true, dependencies });
977
- const computeInventory = (checker, flow, entry, authority) => {
977
+ const computeInventory = (checker, flow, entry, authority, emptyOnly) => {
978
978
  const original = unwrapErasedExpression;
979
979
  const values = new Set();
980
980
  const plans = new Set();
@@ -1132,7 +1132,28 @@ const computeInventory = (checker, flow, entry, authority) => {
1132
1132
  return REFUSED;
1133
1133
  };
1134
1134
  const solve = seededOriginSolver(expand);
1135
- const adopt = (cell) => cells.has(cell) || solve(cell) !== 'refused';
1135
+ const adopt = (cell) => {
1136
+ if (cells.has(cell))
1137
+ return true;
1138
+ // An admitted call forwards the array into this parameter. A successful
1139
+ // inventory would have to visit every reference to it. An argument to a
1140
+ // direct push would either enter the inventory or make that use opaque.
1141
+ // Both answers rule out a proof of emptiness, even before expanding the
1142
+ // parameter's other callers and rebindings.
1143
+ if (emptyOnly &&
1144
+ !isFieldCell(cell) &&
1145
+ ts.isParameter(cell) &&
1146
+ flow.referencesToDeclaration(cell).some((reference) => {
1147
+ const access = reference.parent;
1148
+ if (!ts.isPropertyAccessExpression(access) || access.expression !== reference || access.name.text !== 'push')
1149
+ return false;
1150
+ const callee = outermostErasureOf(access);
1151
+ const call = callee.parent;
1152
+ return ts.isCallExpression(call) && call.expression === callee && call.arguments.length > 0;
1153
+ }))
1154
+ return false;
1155
+ return solve(cell) !== 'refused';
1156
+ };
1136
1157
  const seen = new Set();
1137
1158
  /** Ordinary calls use the admitted frame. Construction still asks its
1138
1159
  * source constructor frame; checker selection alone never admits a method. */
@@ -1353,7 +1374,7 @@ const computeInventory = (checker, flow, entry, authority) => {
1353
1374
  return facts !== null && open === undefined;
1354
1375
  };
1355
1376
  const root = cellNamedBy(checker, flow, entry, authority) ?? original(entry);
1356
- if (solve(root) !== 'allocated')
1377
+ if (solve(root) !== 'allocated' || (emptyOnly && values.size > 0))
1357
1378
  return null;
1358
1379
  for (let index = 0; index < pending.length; index += 1) {
1359
1380
  const item = pending[index];
@@ -1362,7 +1383,7 @@ const computeInventory = (checker, flow, entry, authority) => {
1362
1383
  : ts.isVariableDeclaration(item) || ts.isPropertyDeclaration(item) || ts.isParameter(item)
1363
1384
  ? flow.referencesToDeclaration(item).every(use)
1364
1385
  : use(item);
1365
- if (!closed)
1386
+ if (!closed || (emptyOnly && values.size > 0))
1366
1387
  return null;
1367
1388
  }
1368
1389
  const held = anchor ?? flow.arrayLiterals.find((literal) => arrayTyped(checker, literal)) ?? null;
@@ -1377,11 +1398,13 @@ const keyNameOf = (key) => {
1377
1398
  const node = isFieldCell(key) ? key.declaration : key;
1378
1399
  return `${isFieldCell(key) ? `${key.key}@` : ''}${node.getSourceFile().fileName}#${node.pos}`;
1379
1400
  };
1380
- const inventoryOf = (checker, flow, expression, authority) => {
1401
+ const inventoryOf = (checker, flow, expression, authority, emptyOnly = false) => {
1381
1402
  const key = cellNamedBy(checker, flow, expression, authority) ?? unwrapErasedExpression(expression);
1382
1403
  const cache = scopedCache(authorityInventories, authority, flow, () => new Map());
1383
1404
  if (cache.has(key)) {
1384
1405
  const cached = cache.get(key);
1406
+ if (emptyOnly && cached && cached.values.length > 0)
1407
+ return null;
1385
1408
  if (cached && cached.requirements.length > 0 && deferredIntrinsicProtocolLedgerOf(flow)?.include(cached.requirements) !== true)
1386
1409
  return null;
1387
1410
  return cached;
@@ -1406,11 +1429,11 @@ const inventoryOf = (checker, flow, expression, authority) => {
1406
1429
  enterHypothesisGuard(key, true);
1407
1430
  try {
1408
1431
  const ledger = deferredIntrinsicProtocolLedgerOf(flow);
1409
- const compute = () => computeInventory(checker, flow, expression, authority);
1432
+ const compute = () => computeInventory(checker, flow, expression, authority, emptyOnly);
1410
1433
  // Shared across proofs where the authority can (see `sharedAnswerOf`); a
1411
1434
  // tainted inventory answered from an incomplete view stays this proof's.
1412
1435
  const captured = authority.sharedAnswerOf
1413
- ? authority.sharedAnswerOf(`array-inventory:${keyNameOf(key)}`, compute, () => !frame.tainted)
1436
+ ? authority.sharedAnswerOf(`${emptyOnly ? 'empty-array-inventory' : 'array-inventory'}:${keyNameOf(key)}`, compute, () => !frame.tainted)
1414
1437
  : ledger
1415
1438
  ? ledger.capture(compute)
1416
1439
  : { value: compute(), requirements: [] };
@@ -1452,8 +1475,8 @@ const inventoryOf = (checker, flow, expression, authority) => {
1452
1475
  * parameter frame. No standalone frame inference or authority-free cache is
1453
1476
  * accepted.
1454
1477
  */
1455
- export const arrayStoredValuesOf = (checker, flow, array, authority) => {
1456
- const inventory = inventoryOf(checker, flow, array, authority);
1478
+ export const arrayStoredValuesOf = (checker, flow, array, authority, goal = 'all') => {
1479
+ const inventory = inventoryOf(checker, flow, array, authority, goal === 'empty');
1457
1480
  if (!inventory)
1458
1481
  return null;
1459
1482
  for (const plan of inventory.plans)
@@ -183,12 +183,10 @@ export interface ClosedInvocationAuthority extends ComputedKeySetAuthority {
183
183
  }
184
184
  export declare const closedCallableAuthorityOf: (checker: ts.TypeChecker, flow: ValueFlowIndex, receiverTypeAt: (expression: ts.Expression) => ts.Type | null, argumentsUsesAt: (declaration: ts.SignatureDeclaration) => readonly ts.Identifier[] | undefined, explicitInvocationIsIntact?: (call: ts.CallExpression) => boolean) => ClosedInvocationAuthority;
185
185
  /**
186
- * Every value the array `array` names can ever hold, under the shared
187
- * closed-frame authority, or `null` when that set is not closed. For a census
188
- * outside this module's own proofs; intrinsic obligations go to the caller's
189
- * active ledger capture.
186
+ * Prove the array can never hold a value under the shared closed-frame
187
+ * authority. Intrinsic obligations go to the caller's active ledger capture.
190
188
  */
191
- export declare const closedArrayStoredValuesOf: (checker: ts.TypeChecker, flow: ValueFlowIndex, array: ts.Expression) => readonly ts.Expression[] | null;
189
+ export declare const closedArrayIsProvenEmpty: (checker: ts.TypeChecker, flow: ValueFlowIndex, array: ts.Expression) => boolean;
192
190
  /**
193
191
  * The array-callee extension of `closedCallableAuthorityOf`, for a consumer
194
192
  * that has to pass a real `CallableArrayOriginAuthority` to
@@ -392,12 +392,10 @@ export const closedCallableAuthorityOf = (checker, flow, receiverTypeAt, argumen
392
392
  });
393
393
  };
394
394
  /**
395
- * Every value the array `array` names can ever hold, under the shared
396
- * closed-frame authority, or `null` when that set is not closed. For a census
397
- * outside this module's own proofs; intrinsic obligations go to the caller's
398
- * active ledger capture.
395
+ * Prove the array can never hold a value under the shared closed-frame
396
+ * authority. Intrinsic obligations go to the caller's active ledger capture.
399
397
  */
400
- export const closedArrayStoredValuesOf = (checker, flow, array) => arrayStoredValuesOf(checker, flow, array, closedCallableAuthorityOf(checker, flow, checkerTypeAtOf(checker), argumentsUsesAtOf(checker, flow)));
398
+ export const closedArrayIsProvenEmpty = (checker, flow, array) => arrayStoredValuesOf(checker, flow, array, closedCallableAuthorityOf(checker, flow, checkerTypeAtOf(checker), argumentsUsesAtOf(checker, flow)), 'empty')?.length === 0;
401
399
  /**
402
400
  * The array-callee extension of `closedCallableAuthorityOf`, for a consumer
403
401
  * that has to pass a real `CallableArrayOriginAuthority` to
@@ -321,6 +321,7 @@ export declare abstract class FactState<K, V, R> implements ReadonlySet<V>, Comp
321
321
  * mistaken for a collection (`isLoneFact`) is held as a one-element array.
322
322
  */
323
323
  private facts;
324
+ private factOrder;
324
325
  /**
325
326
  * Carried on the state so `dependents` and the propagation queue can hold
326
327
  * states directly instead of keys. Both used to hold `K`, and every drain
@@ -351,6 +352,7 @@ export declare abstract class FactState<K, V, R> implements ReadonlySet<V>, Comp
351
352
  get size(): number;
352
353
  has(value: V): boolean;
353
354
  add(value: V): void;
355
+ factsFrom(start: number): IterableIterator<V>;
354
356
  /**
355
357
  * Holds `other`'s fact collection when it is the same facts in the same
356
358
  * order, so iteration is unchanged; both are marked shared, and `add`
@@ -634,6 +634,9 @@ export class FactState {
634
634
  * mistaken for a collection (`isLoneFact`) is held as a one-element array.
635
635
  */
636
636
  facts = NO_FACT;
637
+ // Only large states read through a delta cursor need random access to their
638
+ // insertion order. Each state owns its index even when it shares its Set.
639
+ factOrder;
637
640
  /** Seeded: this state's facts are visible to `holdersOf`. */
638
641
  get indexed() {
639
642
  return (this.flags & INDEXED) !== 0;
@@ -714,14 +717,20 @@ export class FactState {
714
717
  return;
715
718
  }
716
719
  if (facts instanceof Set) {
717
- if ((this.flags & SHARED_FACTS) === 0) {
720
+ if ((this.flags & SHARED_FACTS) !== 0) {
721
+ if (facts.has(value))
722
+ return;
723
+ this.facts = new Set(facts).add(value);
724
+ this.flags &= ~SHARED_FACTS;
725
+ }
726
+ else {
727
+ const size = facts.size;
718
728
  facts.add(value);
719
- return;
729
+ if (facts.size === size)
730
+ return;
720
731
  }
721
- if (facts.has(value))
722
- return;
723
- this.facts = new Set(facts).add(value);
724
- this.flags &= ~SHARED_FACTS;
732
+ // Match Set's canonicalization of -0 in iteration.
733
+ this.factOrder?.push(Object.is(value, -0) ? 0 : value);
725
734
  return;
726
735
  }
727
736
  if (this.has(value))
@@ -733,6 +742,23 @@ export class FactState {
733
742
  this.facts = small.length < SMALL_EDGES ? small.concat([value]) : new Set(small).add(value);
734
743
  this.flags &= ~SHARED_FACTS;
735
744
  }
745
+ *factsFrom(start) {
746
+ const facts = this.facts;
747
+ if (facts === NO_FACT || start >= this.size)
748
+ return;
749
+ if (facts instanceof Set) {
750
+ const order = (this.factOrder ??= [...facts]);
751
+ for (let index = start; index < order.length; index++)
752
+ yield order[index];
753
+ return;
754
+ }
755
+ if (Array.isArray(facts)) {
756
+ for (let index = start; index < facts.length; index++)
757
+ yield facts[index];
758
+ return;
759
+ }
760
+ yield facts;
761
+ }
736
762
  /**
737
763
  * Holds `other`'s fact collection when it is the same facts in the same
738
764
  * order, so iteration is unchanged; both are marked shared, and `add`
@@ -4,7 +4,8 @@ import { outermostErasureOf, unwrapErasedExpression } from '../producers/erasure
4
4
  import { deferredIntrinsicProtocolLedgerOf } from '../deferred-intrinsic-protocols.js';
5
5
  import { isVacuousOrigin } from './seeded-origins.js';
6
6
  import { sourceRecordDataWritePlanOf } from './source-record-data.js';
7
- import { calleeDeclarationOf, isModuleExportedDeclaration, isTypePositionReference, resolveFlowSymbolAlias } from './targets.js';
7
+ import { calleeDeclarationOf, exportIsUnimported, isModuleExportedDeclaration, isTypePositionReference, resolveFlowSymbolAlias } from './targets.js';
8
+ import { inProgramImportReferencesOf } from './export-importers.js';
8
9
  import { sourceClassFamilyOf } from './owned-class-receivers.js';
9
10
  const refusalMarks = new WeakSet();
10
11
  const refuse = (reason, at) => {
@@ -506,6 +507,48 @@ export const computedKeySetVerdictOf = (checker, flow, keyExpression, authority)
506
507
  }
507
508
  };
508
509
  // ---- The key's own origins. ----
510
+ /**
511
+ * The elements of the array a `const` names, when that array can only ever
512
+ * hold its literal's elements: the binding is never rebound, and every
513
+ * mention of it -- in its own module and, for an export, in every importer
514
+ * -- only iterates it or reads an element or its length. No mention can
515
+ * hand the array onward, so no alias exists through which an element could
516
+ * be replaced or one pushed.
517
+ */
518
+ const constArrayElementsOf = (name) => {
519
+ const declaration = flow.targetOf(name)?.declaration;
520
+ if (!declaration || !ts.isVariableDeclaration(declaration) || !ts.isIdentifier(declaration.name))
521
+ return null;
522
+ if ((ts.getCombinedNodeFlags(declaration) & ts.NodeFlags.Const) === 0 || !declaration.initializer)
523
+ return null;
524
+ const literal = unwrapErasedExpression(declaration.initializer);
525
+ if (!ts.isArrayLiteralExpression(literal))
526
+ return null;
527
+ if (literal.elements.some((element) => ts.isOmittedExpression(element) || ts.isSpreadElement(element)))
528
+ return null;
529
+ if (flow.writesToDeclaration(declaration).some((write) => write.slot !== 'whole' || write.edge !== 'declaration-initializer'))
530
+ return null;
531
+ const exported = isModuleExportedDeclaration(checker, declaration, checker.getSymbolAtLocation(declaration.name) ?? null);
532
+ const importers = !exported || exportIsUnimported(checker, flow, declaration) ? [] : inProgramImportReferencesOf(checker, flow, declaration);
533
+ if (importers === null)
534
+ return null;
535
+ const readOnly = (reference) => {
536
+ if (reference === declaration.name || isTypePositionReference(reference))
537
+ return true;
538
+ if (ts.isTypeQueryNode(reference.parent) || (reference.flags & ts.NodeFlags.JSDoc) !== 0)
539
+ return true;
540
+ const positioned = outermostErasureOf(reference);
541
+ const parent = positioned.parent;
542
+ if (ts.isForOfStatement(parent) && parent.expression === positioned)
543
+ return true;
544
+ if (isWriteTarget(parent) || ts.isDeleteExpression(parent.parent))
545
+ return false;
546
+ if (ts.isPropertyAccessExpression(parent) && parent.expression === positioned)
547
+ return parent.name.text === 'length' && !ts.isCallExpression(parent.parent);
548
+ return ts.isElementAccessExpression(parent) && parent.expression === positioned && !ts.isCallExpression(parent.parent);
549
+ };
550
+ return [...flow.referencesToDeclaration(declaration), ...importers].every(readOnly) ? literal.elements : null;
551
+ };
509
552
  const visiting = new Set();
510
553
  const loopKeys = (loop) => {
511
554
  if (ts.isForInStatement(loop))
@@ -524,6 +567,15 @@ export const computedKeySetVerdictOf = (checker, flow, keyExpression, authority)
524
567
  keyValues(element);
525
568
  return;
526
569
  }
570
+ if (ts.isIdentifier(source)) {
571
+ const elements = constArrayElementsOf(source);
572
+ if (!elements)
573
+ return refuse('key-iteration-source-unsupported', loop.expression);
574
+ requireIntrinsic('Array', undefined, source);
575
+ for (const element of elements)
576
+ keyValues(element);
577
+ return;
578
+ }
527
579
  const object = ts.isCallExpression(source) && isObjectStatic(source, ['keys']) ? soleArgumentOf(source) : null;
528
580
  if (!object)
529
581
  return refuse('key-iteration-source-unsupported', loop.expression);