@geastack/compiler 1.0.21 → 1.0.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/compiler.js +2 -1
  2. package/dist/conversion/build.d.ts +12 -0
  3. package/dist/conversion/build.js +15 -0
  4. package/dist/ir/callable-class-flow.d.ts +3 -1
  5. package/dist/ir/callable-class-flow.js +27 -1
  6. package/dist/ir/certificate.js +87 -16
  7. package/dist/ir/certify/carrier-keys.js +3 -1
  8. package/dist/ir/lower-invocation.js +7 -1
  9. package/dist/ir/proven-branches.js +3 -1
  10. package/dist/ir/reflection-demand.js +10 -0
  11. package/dist/project-preparation.js +20 -0
  12. package/dist/semantics/class-alias.d.ts +16 -1
  13. package/dist/semantics/class-alias.js +21 -2
  14. package/dist/semantics/class-heritage.js +2 -2
  15. package/dist/semantics/frontend.js +35 -7
  16. package/dist/semantics/normalize/bivariant-slot-parameter.js +21 -6
  17. package/dist/semantics/normalize/commonjs-require.d.ts +9 -5
  18. package/dist/semantics/normalize/commonjs-require.js +127 -44
  19. package/dist/semantics/normalize/host-mutation-key-reader.js +35 -10
  20. package/dist/semantics/normalize/identities.js +15 -0
  21. package/dist/semantics/normalize/object-bag-bindings.js +16 -2
  22. package/dist/semantics/normalize/omitted-stated-parameter.d.ts +1 -1
  23. package/dist/semantics/normalize/omitted-stated-parameter.js +34 -4
  24. package/dist/semantics/normalize/parameter-bindings.js +33 -7
  25. package/dist/semantics/normalize/structural.js +17 -0
  26. package/dist/semantics/program.js +42 -20
  27. package/dist/semantics/shared-declaration-files.d.ts +44 -0
  28. package/dist/semantics/shared-declaration-files.js +42 -0
  29. package/dist/semantics/subclass-member-overlay-transform.js +95 -53
  30. package/dist/targets/cpp/emit-allocation.js +34 -1
  31. package/dist/targets/cpp/emit-union-properties.js +16 -3
  32. package/dist/targets/cpp/manifest/capabilities.js +10 -1
  33. package/dist/targets/cpp/records.js +8 -1
  34. package/package.json +10 -10
  35. package/src/targets/cpp/runtime/gea_runtime.h +66 -14
package/dist/compiler.js CHANGED
@@ -2,7 +2,7 @@ import { readFileSync } from 'fs';
2
2
  import { projectAbis } from './projection/abi.js';
3
3
  import { projectBindingPlacements } from './projection/bindings.js';
4
4
  import { physicalClassInstanceResolverOf, physicalClassLayoutsOf, projectClasses } from './projection/classes.js';
5
- import { buildConversionGraph } from './conversion/build.js';
5
+ import { buildConversionGraph, resetNarrowingMemos } from './conversion/build.js';
6
6
  import { createConversionNodes } from './conversion/nodes.js';
7
7
  import { sweepDiagnostics } from './diagnostics/sweep.js';
8
8
  import { refusalsOf } from './ir/refusal.js';
@@ -174,6 +174,7 @@ export const sourceTransformsFor = (plugins) => [
174
174
  ...plugins.flatMap((plugin) => (plugin.transformSource ? [plugin.transformSource] : []))
175
175
  ];
176
176
  export const compile = (request) => {
177
+ resetNarrowingMemos();
177
178
  // One instance per compilation. A plugin that learns something from a program
178
179
  // and acts on it later has to remember it in between, and a registry of
179
180
  // long-lived instances would let a fact derived from one program be read back
@@ -26,6 +26,18 @@ export interface ConversionGraph {
26
26
  * hidden behind a capability nobody implemented.
27
27
  */
28
28
  export declare const emptyConversionRegistry: ConversionRuntimeRegistry;
29
+ /**
30
+ * Forgets both narrowing memos. "A pure function of the representation" holds
31
+ * only within one program: `representationKey` names a class by its
32
+ * declaration id (`class-ref(decl|f168|20,...)`), and every single-file program
33
+ * numbers its file the same, so the next compile in this process reads another
34
+ * program's class -- with other `ancestors`, which `reaches` tests but the key
35
+ * omits -- under the same key. The emitted-set gate, which compiles hundreds
36
+ * of programs in one process, emitted `native-reflection-virtual-class`'s
37
+ * `instanceof` narrowing differently after `native-default-merge-field-flow`.
38
+ * `compile` calls this first; within one compile the memos stay as measured.
39
+ */
40
+ export declare const resetNarrowingMemos: () => void;
29
41
  export declare const narrowingReachesTarget: (source: Representation, target: Representation) => boolean;
30
42
  /**
31
43
  * A base-class handle read at a UNION of its descendants -- `instanceof Mesh ||
@@ -243,6 +243,21 @@ const buildNarrowingClosure = (source) => {
243
243
  * graph proposal and backend admission so they cannot disagree.
244
244
  */
245
245
  const reachesMemo = new Map();
246
+ /**
247
+ * Forgets both narrowing memos. "A pure function of the representation" holds
248
+ * only within one program: `representationKey` names a class by its
249
+ * declaration id (`class-ref(decl|f168|20,...)`), and every single-file program
250
+ * numbers its file the same, so the next compile in this process reads another
251
+ * program's class -- with other `ancestors`, which `reaches` tests but the key
252
+ * omits -- under the same key. The emitted-set gate, which compiles hundreds
253
+ * of programs in one process, emitted `native-reflection-virtual-class`'s
254
+ * `instanceof` narrowing differently after `native-default-merge-field-flow`.
255
+ * `compile` calls this first; within one compile the memos stay as measured.
256
+ */
257
+ export const resetNarrowingMemos = () => {
258
+ narrowingClosures.clear();
259
+ reachesMemo.clear();
260
+ };
246
261
  export const narrowingReachesTarget = (source, target) => {
247
262
  const targetKey = representationKey(target);
248
263
  if (narrowingClosureKeysOf(source).has(targetKey))
@@ -20,8 +20,10 @@ export interface NativeCallableFlow {
20
20
  * which that demand needs. Unsupported transports fail closed. In particular,
21
21
  * an arbitrary matching callable signature is never an implementation source.
22
22
  */
23
- export declare const nativeCallableFlowOf: (bodies: readonly IrBody[], placements: ReadonlyMap<DeclarationId, BindingPlacement>, classes: ReadonlyMap<DeclarationId, ClassLayout>, conversions?: Pick<ConversionCensus, "nodeById"> & Partial<Pick<ConversionCensus, "nodeFor">>, trace?: (read: Extract<IrOperation, {
23
+ declare const computeNativeCallableFlow: (bodies: readonly IrBody[], placements: ReadonlyMap<DeclarationId, BindingPlacement>, classes: ReadonlyMap<DeclarationId, ClassLayout>, conversions?: Pick<ConversionCensus, "nodeById"> & Partial<Pick<ConversionCensus, "nodeFor">>, trace?: (read: Extract<IrOperation, {
24
24
  kind: "get";
25
25
  }>, reason: string) => void, deriver?: Pick<RepresentationDeriver, "layoutOf"> | null) => NativeCallableFlow;
26
+ export declare const nativeCallableFlowOf: (...args: Parameters<typeof computeNativeCallableFlow>) => NativeCallableFlow;
26
27
  /** Compatibility view of the same execution/escape census; no second analysis policy. */
27
28
  export declare const closedClassFieldCallablesOf: (...args: Parameters<typeof nativeCallableFlowOf>) => ReadonlyMap<IrValueId, CallCalleeIdentity>;
29
+ export {};
@@ -29,7 +29,7 @@ import { observesNativeCarrierOnly, operandsOfIrOperation, resultOfIrOperation }
29
29
  * which that demand needs. Unsupported transports fail closed. In particular,
30
30
  * an arbitrary matching callable signature is never an implementation source.
31
31
  */
32
- export const nativeCallableFlowOf = (bodies, placements, classes, conversions, trace, deriver) => {
32
+ const computeNativeCallableFlow = (bodies, placements, classes, conversions, trace, deriver) => {
33
33
  const propertyLayoutCache = new Map();
34
34
  const nativePropertyLayoutOf = (representation) => hasNativePropertyLayout(representation, deriver ?? null, classes, new Set(), propertyLayoutCache);
35
35
  const cells = [];
@@ -1392,5 +1392,31 @@ export const nativeCallableFlowOf = (bodies, placements, classes, conversions, t
1392
1392
  }
1393
1393
  return { callables: result, enteredBodies: new Set([...entered].map((body) => body.owner)) };
1394
1394
  };
1395
+ /**
1396
+ * The flow is solved three times per compile over bodies that are, for the
1397
+ * second and third, the very same objects (the reflection census and the first
1398
+ * round of the call-dispatch fixed point both read the dispatched program).
1399
+ * Its answer is a function of those objects alone -- the conversion census it
1400
+ * consults is append-only and `nodeFor` is idempotent per pair -- so the last
1401
+ * answer per class map is reused when every input is identical. A traced run
1402
+ * reports reads as it solves and is always solved.
1403
+ */
1404
+ const rememberedFlows = new WeakMap();
1405
+ export const nativeCallableFlowOf = (...args) => {
1406
+ const [bodies, placements, classes, conversions, trace, deriver] = args;
1407
+ if (trace !== undefined)
1408
+ return computeNativeCallableFlow(...args);
1409
+ const held = rememberedFlows.get(classes);
1410
+ if (held &&
1411
+ held.placements === placements &&
1412
+ held.conversions === conversions &&
1413
+ held.deriver === (deriver ?? null) &&
1414
+ held.bodies.length === bodies.length &&
1415
+ held.bodies.every((body, index) => body === bodies[index]))
1416
+ return held.flow;
1417
+ const flow = computeNativeCallableFlow(...args);
1418
+ rememberedFlows.set(classes, { bodies, placements, conversions, deriver: deriver ?? null, flow });
1419
+ return flow;
1420
+ };
1395
1421
  /** Compatibility view of the same execution/escape census; no second analysis policy. */
1396
1422
  export const closedClassFieldCallablesOf = (...args) => nativeCallableFlowOf(...args).callables;
@@ -10,20 +10,91 @@ const sha256Lines = (lines) => {
10
10
  return hash.digest('hex');
11
11
  };
12
12
  /**
13
- * `Map`/`Set` are not JSON-serializable on their own; this replacer expands
14
- * them structurally so the plan's `selected`/`evidence` maps and the graph's
15
- * `operations`/`edges`/`results` tables actually contribute to the digest
16
- * instead of silently vanishing into `{}`. Functions (`manifest.spellable`)
17
- * are dropped by `JSON.stringify` as they always were; the predicate's
18
- * answers are what the demanded keys already record.
13
+ * The digest of a value, streamed into the hash rather than built as one
14
+ * string: the plan and the semantic graph of a large program stringify to
15
+ * hundreds of megabytes, and holding that (and running a replacer callback
16
+ * per property) cost seconds.
17
+ *
18
+ * `Map`/`Set` are not JSON-serializable on their own; they are expanded
19
+ * structurally so the plan's `selected`/`evidence` maps and the graph's
20
+ * `operations`/`edges`/`results` tables contribute to the digest instead of
21
+ * silently vanishing into `{}`. Functions (`manifest.spellable`) and
22
+ * `undefined` object members are skipped as `JSON.stringify` skips them; the
23
+ * predicate's answers are what the demanded keys already record.
24
+ *
25
+ * The byte stream is a prefix code: every value starts with a tag, every
26
+ * string and key is length-prefixed, every container is closed, so two
27
+ * different values cannot produce the same stream. Insertion order is kept
28
+ * (as `JSON.stringify` kept it); a `Set` is sorted as before.
19
29
  */
20
- const canonicalize = (value) => JSON.stringify(value, (_key, val) => {
21
- if (val instanceof Map)
22
- return { __map__: [...val.entries()] };
23
- if (val instanceof Set)
24
- return { __set__: [...val.values()].sort() };
25
- return val;
26
- });
30
+ const digestOf = (value) => {
31
+ const hash = createHash('sha256');
32
+ let pending = '';
33
+ const write = (text) => {
34
+ pending += text;
35
+ if (pending.length >= 1 << 16) {
36
+ hash.update(pending, 'utf8');
37
+ pending = '';
38
+ }
39
+ };
40
+ const text = (value) => write(`s${value.length}:${value}`);
41
+ const visit = (val) => {
42
+ if (val === null)
43
+ return write('z');
44
+ switch (typeof val) {
45
+ case 'string':
46
+ return text(val);
47
+ case 'number':
48
+ return write(Number.isFinite(val) ? `n${val};` : 'z');
49
+ case 'boolean':
50
+ return write(val ? 't' : 'f');
51
+ case 'bigint':
52
+ return write(`b${val};`);
53
+ case 'object':
54
+ break;
55
+ default:
56
+ // undefined, symbol, function: absent from an object, null in an array.
57
+ return write('z');
58
+ }
59
+ const object = val;
60
+ if (typeof object.toJSON === 'function')
61
+ return visit(object.toJSON());
62
+ if (Array.isArray(val)) {
63
+ write(`A${val.length}[`);
64
+ for (const element of val)
65
+ visit(element);
66
+ return write(']');
67
+ }
68
+ if (val instanceof Map) {
69
+ write(`M${val.size}[`);
70
+ for (const [key, entry] of val) {
71
+ visit(key);
72
+ visit(entry);
73
+ }
74
+ return write(']');
75
+ }
76
+ if (val instanceof Set) {
77
+ const members = [...val.values()].sort();
78
+ write(`S${members.length}[`);
79
+ for (const member of members)
80
+ visit(member);
81
+ return write(']');
82
+ }
83
+ const record = val;
84
+ write('O{');
85
+ for (const key of Object.keys(record)) {
86
+ const member = record[key];
87
+ if (member === undefined || typeof member === 'function' || typeof member === 'symbol')
88
+ continue;
89
+ text(key);
90
+ visit(member);
91
+ }
92
+ write('}');
93
+ };
94
+ visit(value);
95
+ hash.update(pending, 'utf8');
96
+ return hash.digest('hex');
97
+ };
27
98
  /**
28
99
  * Mints a certificate from a clean certification, or returns `null` for one
29
100
  * that refused anything.
@@ -38,9 +109,9 @@ const canonicalize = (value) => JSON.stringify(value, (_key, val) => {
38
109
  export const mintCapabilityCertificate = (certification, subjects) => {
39
110
  if (!certification.certified)
40
111
  return null;
41
- const planDigest = sha256(canonicalize(subjects.plan));
42
- const semanticSnapshotDigest = sha256(canonicalize(subjects.semanticSnapshot));
43
- const manifestDigest = sha256(canonicalize(subjects.manifest));
112
+ const planDigest = digestOf(subjects.plan);
113
+ const semanticSnapshotDigest = digestOf(subjects.semanticSnapshot);
114
+ const manifestDigest = digestOf(subjects.manifest);
44
115
  const certificationDigest = sha256Lines(certification.demanded.map((key) => `${key}\n`));
45
116
  const id = sha256([planDigest, semanticSnapshotDigest, manifestDigest, certificationDigest].join('|'));
46
117
  return Object.freeze({ id, planDigest, semanticSnapshotDigest, manifestDigest, certificationDigest });
@@ -335,7 +335,9 @@ export const spreadSourceCarrierKeyOf = (kind, representation, receiver, deriver
335
335
  ? `dictionary(${candidate.key}->${receiver.key})`
336
336
  : `dictionary(${candidate.key}->${receiver?.kind ?? 'absent'})`;
337
337
  if (representation.kind === 'dynamic') {
338
- return isDynamicCopyableIntoFieldRecord(deriver, receiver) ? 'field-record<-dynamic' : `dynamic->${receiver?.kind ?? 'absent'}`;
338
+ if (isDynamicCopyableIntoFieldRecord(deriver, receiver))
339
+ return 'field-record<-dynamic';
340
+ return receiver?.kind === 'dictionary' ? `dynamic->dictionary(${receiver.key})` : `dynamic->${receiver?.kind ?? 'absent'}`;
339
341
  }
340
342
  if (spreadFieldRecordReceiverOf(deriver, receiver) !== null)
341
343
  return isCopyableIntoFieldRecord(deriver, representation) ? 'field-record<-copyable' : `field-record<-${kind}`;
@@ -470,7 +470,13 @@ export const lowerInvocation = (ctx, block, operation) => {
470
470
  // A host may additionally publish a borrowed numeric rest spelling, proved
471
471
  // separately below. Merely seeing number[] does not authorize skipping the
472
472
  // array: ordinary rest functions and first-class builtin values observe it.
473
- const calleeAbi = abiOfCallee(callee.representation);
473
+ // A callee that may be absent is invoked through its payload: emission
474
+ // presence-checks it and calls what it holds (`unwrapPresentValue`), so the
475
+ // payload's convention is the frame these arguments fill. Packing against
476
+ // the optional itself states no convention and hands a rest function its
477
+ // loose arguments -- three's `...arguments` shims read off a dynamic key.
478
+ const invoked = callee.representation.kind === 'optional' ? callee.representation.payload : callee.representation;
479
+ const calleeAbi = abiOfCallee(invoked);
474
480
  const restElement = calleeAbi?.restFrom === null || calleeAbi === null ? null : (calleeAbi.parameters[calleeAbi.restFrom]?.value ?? null);
475
481
  const textJoined = restElement?.kind === 'array-object' && restElement.element.kind === 'dynamic';
476
482
  // Only numeric operands use the borrowed host frame. Unknown values still
@@ -271,7 +271,9 @@ export const pruneProvenBranches = (bodies, graph, slotDrift = []) => {
271
271
  // condition itself, a `compute` carrying the equality's own lineage.
272
272
  if (operation.kind === 'compute' && operation.form === 'equality') {
273
273
  const truth = semantic.get(operation.lineage);
274
- if (truth !== undefined && operation.operands.length === 2 && operation.operands.every((operand) => operand.representation.kind === 'string'))
274
+ if (truth !== undefined &&
275
+ operation.operands.length === 2 &&
276
+ operation.operands.every((operand) => operand.representation.kind === 'string'))
275
277
  facts.set(operation.result.id, truth);
276
278
  continue;
277
279
  }
@@ -184,9 +184,18 @@ const directChildrenOf = (representation, classes, deriver) => {
184
184
  return [...representation.fields.map((field) => field.value), ...representation.indexes.map((index) => index.value)];
185
185
  case 'class-ref': {
186
186
  const layout = classes.get(representation.declaration);
187
+ // A boxed instance answers a dynamic read of a prototype method with the
188
+ // method itself (the class's `gea_getPrototypeProperty` boxes it), so a
189
+ // dynamic caller can invoke it and receive its result. The method's
190
+ // convention is therefore one of the instance's published values; its
191
+ // result is what `publishedChildrenOf` keeps of it. Without this a record
192
+ // returned by such a method had no own-field protocol, the box adapter
193
+ // could not carry it, and the boxed method was not callable at all.
194
+ const methods = layout?.methods.flatMap((method) => (method.representation ? [method.representation] : [])) ?? [];
187
195
  if (layout?.nativeStorage !== undefined) {
188
196
  const raw = deriver?.layoutOf(representation.shapeId);
189
197
  return [
198
+ ...methods,
190
199
  ...layout.nativeStorage.fields.map((field) => field.value),
191
200
  ...layout.staticFields.flatMap((field) => (field.representation ? [field.representation] : [])),
192
201
  ...(raw?.kind === 'record' ? raw.accessors.map((accessor) => accessor.value) : []),
@@ -194,6 +203,7 @@ const directChildrenOf = (representation, classes, deriver) => {
194
203
  ];
195
204
  }
196
205
  return [
206
+ ...methods,
197
207
  ...(layout?.fields.flatMap((field) => (field.representation ? [field.representation] : [])) ?? []),
198
208
  ...(layout?.staticFields.flatMap((field) => (field.representation ? [field.representation] : [])) ?? []),
199
209
  ...(deriver ? [deriver.layoutOf(representation.shapeId)] : [])
@@ -9,6 +9,9 @@ const disk = {
9
9
  exists: existsSync,
10
10
  read: (file) => readFileSync(file, 'utf8'),
11
11
  write: (file, text) => {
12
+ // The negative marker is the first thing written into a package's cache
13
+ // directory when nothing was checked out there.
14
+ mkdirSync(dirname(file), { recursive: true });
12
15
  writeFileSync(file, text);
13
16
  },
14
17
  realpath: realpathSync,
@@ -432,7 +435,19 @@ export const preparePackageSources = async (root, options = {}) => {
432
435
  // once per `node_modules` it appeared in.
433
436
  const cache = join(root, 'node_modules', '.cache', 'geatsc', 'sources', createHash('sha256').update(`${manifest.name}@${manifest.version}`).digest('hex').slice(0, 24));
434
437
  const record = join(cache, 'source.json');
438
+ // A registry that names no pinned source for a published version names none
439
+ // later either (a version is published once), but asking costs a serial
440
+ // `npm view` per package on every build. Recorded beside the positive
441
+ // record; only this definite answer is cached, never a failed request.
442
+ const unpinned = join(cache, 'no-source.json');
435
443
  try {
444
+ if (files.exists(unpinned)) {
445
+ const saved = object(JSON.parse(files.read(unpinned)));
446
+ if (saved.name === manifest.name && saved.version === manifest.version && saved.unpinned === true) {
447
+ log(`[geatsc] ${manifest.name}@${manifest.version}: no pinned source metadata (cached); using installed JavaScript`);
448
+ continue;
449
+ }
450
+ }
436
451
  if (files.exists(record)) {
437
452
  const saved = object(JSON.parse(files.read(record)));
438
453
  if (saved.name === manifest.name &&
@@ -453,6 +468,11 @@ export const preparePackageSources = async (root, options = {}) => {
453
468
  identity = provenanceSourceIdentity(published, await attestations(provenanceUrl, directory));
454
469
  if (!identity) {
455
470
  log(`[geatsc] ${manifest.name}@${manifest.version}: no pinned source metadata; using installed JavaScript`);
471
+ // Best effort: a cache that cannot be written only costs the next build its lookup.
472
+ try {
473
+ files.write(unpinned, `${JSON.stringify({ name: manifest.name, version: manifest.version, unpinned: true })}\n`);
474
+ }
475
+ catch { }
456
476
  continue;
457
477
  }
458
478
  const destination = join(cache, identity.commit);
@@ -11,7 +11,22 @@ export declare const transparentConstClassAliasTarget: (checker: ts.TypeChecker,
11
11
  * `physical-class-alias` rule reads both through here).
12
12
  */
13
13
  export declare const transparentClassAliasDeclarationTarget: (checker: ts.TypeChecker, declaration: ts.VariableDeclaration) => ts.Identifier | null;
14
- /** The class value evaluated by extends, shared by layout, ancestry and super. */
14
+ /**
15
+ * The class `extends` names, for IDENTITY: ancestry and layout. It follows a
16
+ * transparent `const` alias anywhere, an imported one included, because the
17
+ * question is which class declaration the base is.
18
+ */
19
+ export declare const classHeritageTarget: (checker: ts.TypeChecker, expression: ts.Expression) => ts.Expression;
20
+ /**
21
+ * The class VALUE `extends` evaluates, for lowering: the alias target only when
22
+ * it is in the same file, since an expression from another module has no
23
+ * result in this owner. node-compat's `whatwg-url.ts` exports
24
+ * `const URLAlias = URL`; `mongodb-connection-string-url`'s
25
+ * `class URLWithoutHost extends URL` resolved through that import to the
26
+ * `URL` read inside `whatwg-url.ts`, and lowering its module body refused
27
+ * ("a value produced by a different owner needs capture lowering"). The import
28
+ * itself reads the same class object through its binding.
29
+ */
15
30
  export declare const evaluatedClassHeritage: (checker: ts.TypeChecker, expression: ts.Expression) => ts.Expression;
16
31
  /**
17
32
  * The class symbol a read of a `const` alias of a GENERIC class denotes.
@@ -35,11 +35,30 @@ export const transparentClassAliasDeclarationTarget = (checker, declaration) =>
35
35
  const targetSymbol = checker.getSymbolAtLocation(target);
36
36
  return targetSymbol && classDeclarationOf(checker, targetSymbol) ? target : null;
37
37
  };
38
- /** The class value evaluated by extends, shared by layout, ancestry and super. */
39
- export const evaluatedClassHeritage = (checker, expression) => {
38
+ /**
39
+ * The class `extends` names, for IDENTITY: ancestry and layout. It follows a
40
+ * transparent `const` alias anywhere, an imported one included, because the
41
+ * question is which class declaration the base is.
42
+ */
43
+ export const classHeritageTarget = (checker, expression) => {
40
44
  const value = unwrapErasedExpression(expression);
41
45
  return transparentConstClassAliasTarget(checker, value) ?? value;
42
46
  };
47
+ /**
48
+ * The class VALUE `extends` evaluates, for lowering: the alias target only when
49
+ * it is in the same file, since an expression from another module has no
50
+ * result in this owner. node-compat's `whatwg-url.ts` exports
51
+ * `const URLAlias = URL`; `mongodb-connection-string-url`'s
52
+ * `class URLWithoutHost extends URL` resolved through that import to the
53
+ * `URL` read inside `whatwg-url.ts`, and lowering its module body refused
54
+ * ("a value produced by a different owner needs capture lowering"). The import
55
+ * itself reads the same class object through its binding.
56
+ */
57
+ export const evaluatedClassHeritage = (checker, expression) => {
58
+ const value = unwrapErasedExpression(expression);
59
+ const target = transparentConstClassAliasTarget(checker, value);
60
+ return target !== null && target.getSourceFile() === value.getSourceFile() ? target : value;
61
+ };
43
62
  /**
44
63
  * The class symbol a read of a `const` alias of a GENERIC class denotes.
45
64
  *
@@ -1,6 +1,6 @@
1
1
  import ts from 'typescript';
2
2
  import { heritageCopyOf } from './normalize/structural-generics.js';
3
- import { evaluatedClassHeritage } from './class-alias.js';
3
+ import { classHeritageTarget } from './class-alias.js';
4
4
  /**
5
5
  * Which classes each class INHERITS FROM, transitively -- the one fact two
6
6
  * separate carrier questions both need and neither can answer on its own.
@@ -60,7 +60,7 @@ reparentedBaseOf = () => null) => {
60
60
  const declared = symbol ? checker.getDeclaredTypeOfSymbol(symbol) : null;
61
61
  const chain = [];
62
62
  const syntacticBase = node.heritageClauses?.find((clause) => clause.token === ts.SyntaxKind.ExtendsKeyword)?.types[0]?.expression;
63
- const aliasedBase = syntacticBase ? evaluatedClassHeritage(checker, syntacticBase) : null;
63
+ const aliasedBase = syntacticBase ? classHeritageTarget(checker, syntacticBase) : null;
64
64
  const aliasedSymbol = aliasedBase ? checker.getSymbolAtLocation(aliasedBase) : undefined;
65
65
  const aliasedDeclaration = aliasedSymbol ? identities.declarationOfSymbol(aliasedSymbol) : null;
66
66
  if (aliasedDeclaration && ts.isClassLike(aliasedDeclaration)) {
@@ -243,6 +243,34 @@ const reachableCodeNamesAny = (files, reachable, names) => {
243
243
  const visit = (node) => (ts.isIdentifier(node) && names.has(node.text)) || ts.forEachChild(node, visit) === true;
244
244
  return files.some((file) => !file.isDeclarationFile && reachable.statementsOf(file).some(visit));
245
245
  };
246
+ /**
247
+ * The named ambient classes and the ambient variable declarations of one file,
248
+ * in source order: every node the native-constructor scan can admit.
249
+ *
250
+ * Which nodes those are is a pure function of the tree, and a declaration
251
+ * file's tree is shared across compiles (`shared-declaration-files.ts`), so the
252
+ * whole-file walk is done once per file rather than once per compile. Ambient
253
+ * declarations cannot nest inside a function or expression body, but the walk
254
+ * stays a full one rather than assuming that: it is the cached part, so its cost
255
+ * is paid once.
256
+ */
257
+ const nativeConstructorCandidates = new WeakMap();
258
+ const nativeConstructorCandidatesOf = (file) => {
259
+ const known = nativeConstructorCandidates.get(file);
260
+ if (known !== undefined)
261
+ return known;
262
+ const found = [];
263
+ const visit = (node) => {
264
+ if (ts.isClassDeclaration(node) && node.name && isAmbientDeclaration(node))
265
+ found.push(node);
266
+ else if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && isAmbientDeclaration(node))
267
+ found.push(node);
268
+ ts.forEachChild(node, visit);
269
+ };
270
+ visit(file);
271
+ nativeConstructorCandidates.set(file, found);
272
+ return found;
273
+ };
246
274
  export const runFrontend = (input) => {
247
275
  const timing = createFrontendTiming('phases');
248
276
  const compiled = createProgram({
@@ -1056,30 +1084,30 @@ export const runFrontend = (input) => {
1056
1084
  admitNativeConstructor(compiled.checker.resolveName(name, file, ts.SymbolFlags.Value, false), file);
1057
1085
  }
1058
1086
  }
1059
- const visitNativeConstructorDeclaration = (node) => {
1087
+ for (const node of nativeConstructorCandidatesOf(file)) {
1060
1088
  // A declaration-bound host class states its constructor identity as
1061
1089
  // well as its instance carrier. Reading only standardClasses here left
1062
1090
  // `new HostView()` opaque even though hosts.protocols had already sealed
1063
1091
  // that very class as native. Do not admit a structurally compatible
1064
1092
  // constructor signature: the ambient class declaration must be the one
1065
1093
  // the host bound.
1066
- if (ts.isClassDeclaration(node) && node.name && isAmbientDeclaration(node)) {
1094
+ if (ts.isClassDeclaration(node)) {
1095
+ if (!node.name)
1096
+ continue;
1067
1097
  const symbol = compiled.checker.getSymbolAtLocation(node.name);
1068
1098
  const declaration = symbol ? identities.symbolDeclarationId(symbol, node.name) : null;
1069
1099
  const binding = declaration === null ? undefined : hosts.protocols.get(declaration);
1070
1100
  if (binding && binding.native !== null)
1071
1101
  admitNativeConstructor(symbol, node.name);
1102
+ continue;
1072
1103
  }
1073
1104
  if (executableSourceFiles.has(file) &&
1074
1105
  ts.isVariableDeclaration(node) &&
1075
1106
  ts.isIdentifier(node.name) &&
1076
- standardClassNames.has(node.name.text) &&
1077
- isAmbientDeclaration(node)) {
1107
+ standardClassNames.has(node.name.text)) {
1078
1108
  admitNativeConstructor(compiled.checker.getSymbolAtLocation(node.name), node.name);
1079
1109
  }
1080
- ts.forEachChild(node, visitNativeConstructorDeclaration);
1081
- };
1082
- visitNativeConstructorDeclaration(file);
1110
+ }
1083
1111
  }
1084
1112
  // `absorb`, not a copy of the set: the census's per-key facts are not in
1085
1113
  // its legacy set view, and dropping them would lose writes.
@@ -73,6 +73,18 @@ const contextualSignatureOf = (checker, declaration) => {
73
73
  return signature.typeParameters === undefined ? signature : null;
74
74
  };
75
75
  const ownParametersOf = (declaration) => declaration.parameters.filter((parameter) => !(ts.isIdentifier(parameter.name) && parameter.name.text === 'this'));
76
+ /**
77
+ * The three memos below hold `ts.Type`s, which are one checker's. A declaration
78
+ * file's nodes are shared across compiles (`shared-declaration-files.ts`), so a
79
+ * memo keyed by node alone would hand a later compile the earlier checker's
80
+ * types. Each is keyed by the checker first.
81
+ */
82
+ const memoOf = (memos, checker) => {
83
+ let memo = memos.get(checker);
84
+ if (memo === undefined)
85
+ memos.set(checker, (memo = new WeakMap()));
86
+ return memo;
87
+ };
76
88
  const slotParameterTypes = new WeakMap();
77
89
  /**
78
90
  * The slot's own type for `parameter`, when the stated annotation is one the
@@ -80,11 +92,12 @@ const slotParameterTypes = new WeakMap();
80
92
  * stands (it is the slot's, wider than it, or no slot states one).
81
93
  */
82
94
  export const bivariantSlotParameterTypeOf = (checker, parameter) => {
83
- const remembered = slotParameterTypes.get(parameter);
95
+ const memo = memoOf(slotParameterTypes, checker);
96
+ const remembered = memo.get(parameter);
84
97
  if (remembered !== undefined)
85
98
  return remembered;
86
99
  const answer = computeSlotParameterType(checker, parameter);
87
- slotParameterTypes.set(parameter, answer);
100
+ memo.set(parameter, answer);
88
101
  return answer;
89
102
  };
90
103
  const computeSlotParameterType = (checker, parameter) => {
@@ -203,7 +216,8 @@ const aliasVisiting = new WeakSet();
203
216
  * copying it.
204
217
  */
205
218
  export const bivariantSlotArrayAliasTypeOf = (checker, node) => {
206
- const remembered = aliasTypes.get(node);
219
+ const memo = memoOf(aliasTypes, checker);
220
+ const remembered = memo.get(node);
207
221
  if (remembered !== undefined)
208
222
  return remembered;
209
223
  if (aliasVisiting.has(node))
@@ -216,7 +230,7 @@ export const bivariantSlotArrayAliasTypeOf = (checker, node) => {
216
230
  finally {
217
231
  aliasVisiting.delete(node);
218
232
  }
219
- aliasTypes.set(node, answer);
233
+ memo.set(node, answer);
220
234
  return answer;
221
235
  };
222
236
  const seedReadTypeOf = (checker, node) => {
@@ -319,11 +333,12 @@ const elementTypes = new WeakMap();
319
333
  * narrowed read after that test is the checked one.
320
334
  */
321
335
  export const bivariantSlotElementTypeOf = (checker, node) => {
322
- const remembered = elementTypes.get(node);
336
+ const memo = memoOf(elementTypes, checker);
337
+ const remembered = memo.get(node);
323
338
  if (remembered !== undefined)
324
339
  return remembered;
325
340
  const answer = computeElementType(checker, node);
326
- elementTypes.set(node, answer);
341
+ memo.set(node, answer);
327
342
  return answer;
328
343
  };
329
344
  const computeElementType = (checker, node) => {
@@ -4,13 +4,17 @@ export type CommonJsRequireStatus = 'static' | 'possibly-reassigned' | 'ordinary
4
4
  export interface CommonJsRequireCensus {
5
5
  readonly statusOf: (expression: ts.Expression) => CommonJsRequireStatus;
6
6
  }
7
+ export declare const createCommonJsRequireCensus: (checker: ts.TypeChecker, files: readonly ts.SourceFile[], globals: ReadonlyMap<string, CommonJsWrapperDeclaration>) => CommonJsRequireCensus;
7
8
  /**
8
- * CommonJS static dispatch is a reaching-definition proof over one wrapper
9
- * cell per source module. The cell starts at Node's original loader and every
10
- * possible write replaces that proof with unknown. Const aliases snapshot the
11
- * definition at their own initializer; later cell writes cannot alter them.
9
+ * The census restricted to what a program that is about to be REBUILT needs:
10
+ * which `require` calls are static. Valid only when no file can write the
11
+ * wrapper cell, where the full census's answer is `static` for every read of
12
+ * the wrapper (`requireStatusOf`) and its fact and summary passes compute
13
+ * nothing anyone consults. Null otherwise -- the caller then asks the full
14
+ * census. Never used for the program the compile keeps: the full census also
15
+ * puts the checker in the state later queries (and so emitted names) depend on.
12
16
  */
13
- export declare const createCommonJsRequireCensus: (checker: ts.TypeChecker, files: readonly ts.SourceFile[], globals: ReadonlyMap<string, CommonJsWrapperDeclaration>) => CommonJsRequireCensus;
17
+ export declare const createCommonJsRequireTargetCensus: (checker: ts.TypeChecker, files: readonly ts.SourceFile[], globals: ReadonlyMap<string, CommonJsWrapperDeclaration>) => CommonJsRequireCensus | null;
14
18
  /** What a checker-authenticated static `require( 'x' )` does when it runs. */
15
19
  export type StaticRequireOutcome =
16
20
  /** Evaluates this compiled, non-declaration module body (once) and answers its exports. */