@geastack/compiler 1.0.21 → 1.0.23

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 (63) 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/borrow-effects.js +55 -1
  5. package/dist/ir/callable-class-flow.d.ts +3 -1
  6. package/dist/ir/callable-class-flow.js +27 -1
  7. package/dist/ir/certificate.js +87 -16
  8. package/dist/ir/certify/carrier-keys.js +3 -1
  9. package/dist/ir/dense-loops.d.ts +16 -2
  10. package/dist/ir/dense-loops.js +66 -21
  11. package/dist/ir/facts.d.ts +6 -29
  12. package/dist/ir/facts.js +46 -1
  13. package/dist/ir/floats.d.ts +46 -0
  14. package/dist/ir/floats.js +196 -0
  15. package/dist/ir/hoist.d.ts +11 -2
  16. package/dist/ir/hoist.js +17 -2
  17. package/dist/ir/integer-storage.js +8 -4
  18. package/dist/ir/integers.d.ts +14 -0
  19. package/dist/ir/integers.js +55 -1
  20. package/dist/ir/lower-invocation.js +7 -1
  21. package/dist/ir/numeric-intrinsics.d.ts +1 -1
  22. package/dist/ir/numeric-intrinsics.js +3 -2
  23. package/dist/ir/proven-branches.js +3 -1
  24. package/dist/ir/reflection-demand.js +10 -0
  25. package/dist/project-preparation.js +20 -0
  26. package/dist/semantics/class-alias.d.ts +16 -1
  27. package/dist/semantics/class-alias.js +21 -2
  28. package/dist/semantics/class-heritage.js +2 -2
  29. package/dist/semantics/frontend.js +35 -7
  30. package/dist/semantics/normalize/bivariant-slot-parameter.js +21 -6
  31. package/dist/semantics/normalize/commonjs-require.d.ts +9 -5
  32. package/dist/semantics/normalize/commonjs-require.js +127 -44
  33. package/dist/semantics/normalize/host-mutation-key-reader.js +35 -10
  34. package/dist/semantics/normalize/identities.js +15 -0
  35. package/dist/semantics/normalize/object-bag-bindings.js +16 -2
  36. package/dist/semantics/normalize/omitted-stated-parameter.d.ts +1 -1
  37. package/dist/semantics/normalize/omitted-stated-parameter.js +34 -4
  38. package/dist/semantics/normalize/parameter-bindings.js +33 -7
  39. package/dist/semantics/normalize/structural.js +17 -0
  40. package/dist/semantics/program.js +42 -20
  41. package/dist/semantics/shared-declaration-files.d.ts +44 -0
  42. package/dist/semantics/shared-declaration-files.js +42 -0
  43. package/dist/semantics/subclass-member-overlay-transform.js +95 -53
  44. package/dist/targets/cpp/emit-allocation.js +34 -1
  45. package/dist/targets/cpp/emit-arrays.d.ts +2 -1
  46. package/dist/targets/cpp/emit-arrays.js +7 -3
  47. package/dist/targets/cpp/emit-bindings.js +4 -2
  48. package/dist/targets/cpp/emit-callable.js +13 -0
  49. package/dist/targets/cpp/emit-carrier-members.d.ts +3 -1
  50. package/dist/targets/cpp/emit-carrier-members.js +18 -2
  51. package/dist/targets/cpp/emit-context.d.ts +13 -0
  52. package/dist/targets/cpp/emit-context.js +18 -2
  53. package/dist/targets/cpp/emit-properties.js +16 -3
  54. package/dist/targets/cpp/emit-union-properties.js +16 -3
  55. package/dist/targets/cpp/emit.js +36 -4
  56. package/dist/targets/cpp/host/emit-host-invoke.js +10 -1
  57. package/dist/targets/cpp/host/host-members.js +43 -30
  58. package/dist/targets/cpp/manifest/capabilities.js +10 -1
  59. package/dist/targets/cpp/records.js +8 -1
  60. package/dist/targets/cpp/types.d.ts +2 -0
  61. package/dist/targets/cpp/types.js +2 -0
  62. package/package.json +13 -13
  63. package/src/targets/cpp/runtime/gea_runtime.h +146 -18
@@ -1,5 +1,5 @@
1
1
  import ts from 'typescript';
2
- import { annotationStatesNothing, containsUnstatedPosition, isUnusableEvidence, jsDocTypeStatesNothing } from './derived-expression-type.js';
2
+ import { annotationStatesNothing, containsUnstatedPosition, isUnusableEvidence, jsDocTypeStatesNothing, withoutUndefinedMember } from './derived-expression-type.js';
3
3
  /** The JSDoc statement of a JavaScript parameter this rule may widen, or `null`. */
4
4
  export const omissionStatedTypeOf = (checker, parameter) => {
5
5
  if ((parameter.flags & ts.NodeFlags.JavaScriptFile) === 0)
@@ -28,7 +28,7 @@ export const omissionStatedTypeOf = (checker, parameter) => {
28
28
  };
29
29
  /**
30
30
  * `stated | undefined` when some caller in the (already closed) caller set
31
- * omits the argument at `index`.
31
+ * omits the argument at `index`, or passes one that can itself be `undefined`.
32
32
  *
33
33
  * `null` when no caller provably omits it -- every caller passes it, or there
34
34
  * is no attributed caller at all -- so the statement stands as written and
@@ -41,7 +41,33 @@ export const statedParameterWithOmission = (checker, stated, index, calls, argum
41
41
  const argumentLists = calls.map((call) => argumentsOf(call) ?? []);
42
42
  // A spread at or before the position may or may not reach it.
43
43
  const reachedBySpread = (args) => args.slice(0, index + 1).some(ts.isSpreadElement);
44
- if (!argumentLists.some((args) => args[index] === undefined && !reachedBySpread(args)))
44
+ // Absence reaches the parameter two ways: a call that leaves the argument
45
+ // out, and a call that passes a value which can itself be `undefined`. The
46
+ // second is the first with a forwarding hop in between -- three's
47
+ // `refreshMaterialUniforms( ..., transmissionRenderTarget )` hands its own
48
+ // parameter (`state.transmissionRenderTarget[ camera.id ]`, undefined until
49
+ // the first transmissive draw) to `refreshUniformsPhysical`, which reads it
50
+ // only under `material.transmission > 0`. Forwarding an absent value is no
51
+ // read of it, so the callee's slot must be able to hold it; refusing the
52
+ // widening left a required slot that threw at the call.
53
+ const carriesAbsence = (type) => (type.isUnion() ? type.types : [type]).some((part) => (part.flags & ts.TypeFlags.Undefined) !== 0);
54
+ const omitted = argumentLists.some((args) => args[index] === undefined && !reachedBySpread(args));
55
+ const passedAbsent = argumentLists.some((args) => {
56
+ const argument = args[index];
57
+ if (argument === undefined || reachedBySpread(args))
58
+ return false;
59
+ const type = argumentType(argument);
60
+ return type !== null && carriesAbsence(type);
61
+ });
62
+ if (!omitted && !passedAbsent)
63
+ return null;
64
+ // A statement that already admits `undefined` holds a passed absent value as
65
+ // written, so this rule has nothing to add -- and binding it anyway would
66
+ // pre-empt every later rule that refines the parameter. The native-webgl
67
+ // overlay states three's uniform setters as `NativeUniformValue`, which
68
+ // includes `undefined`; claiming those left `array[ 0 ]` reading the whole
69
+ // value union. (An omitted argument keeps its existing answer.)
70
+ if (!omitted && carriesAbsence(stated))
45
71
  return null;
46
72
  for (const args of argumentLists) {
47
73
  if (reachedBySpread(args))
@@ -52,7 +78,11 @@ export const statedParameterWithOmission = (checker, stated, index, calls, argum
52
78
  const type = argumentType(argument);
53
79
  if (!type || isUnusableEvidence(type) || (type.flags & ts.TypeFlags.Unknown) !== 0)
54
80
  return { refused: 'stated-omission-argument-unresolved' };
55
- if (!checker.isTypeAssignableTo(type, stated))
81
+ // A bare `undefined` is pure absence, which is what widens the slot; otherwise the rest of the
82
+ // argument is held to the statement.
83
+ if ((type.flags & ts.TypeFlags.Undefined) !== 0)
84
+ continue;
85
+ if (!checker.isTypeAssignableTo(withoutUndefinedMember(checker, type), stated))
56
86
  return { refused: 'stated-omission-argument-not-assignable' };
57
87
  }
58
88
  return { type: checker.getNullableType(stated, ts.TypeFlags.Undefined) };
@@ -3313,6 +3313,9 @@ hostProvided = noHostProvidedNames) => {
3313
3313
  // like any inference, and its obligations are kept with the binding.
3314
3314
  propagating.reset();
3315
3315
  // `GEA_STATED_OMISSION_OFF` keeps the arm without this rule runnable, the way `GEA_BAG_OFF` is.
3316
+ // The parameters this rule widened. The class-instance rule below still owns
3317
+ // their LAYOUT -- see its own comment -- and keeps this rule's absence arm.
3318
+ const omissionWidened = new Set();
3316
3319
  for (const site of process.env['GEA_STATED_OMISSION_OFF'] ? [] : index.omissionSites) {
3317
3320
  if (bindings.has(site.parameter) || unionArms.has(site.parameter))
3318
3321
  continue;
@@ -3338,6 +3341,7 @@ hostProvided = noHostProvidedNames) => {
3338
3341
  bindings.set(site.parameter, answer.type);
3339
3342
  statedBindings.set(site.parameter, answer.type);
3340
3343
  protocolRequirements.set(site.parameter, captured.requirements);
3344
+ omissionWidened.add(site.parameter);
3341
3345
  if (process.env['GEA_BINDING_DEBUG'])
3342
3346
  console.error(`[STATED-OMISSION] ${describeParameter(site.parameter)} :: ${checker.typeToString(answer.type)}`);
3343
3347
  }
@@ -3380,7 +3384,14 @@ hostProvided = noHostProvidedNames) => {
3380
3384
  // converts into it, and the class arm only holds what a caller it CAN see
3381
3385
  // provably passes -- the object itself, never a copy of it.
3382
3386
  for (const site of index.classInstanceSites) {
3383
- if (bindings.has(site.parameter) || unionArms.has(site.parameter) || recordHomeArms.has(site.parameter))
3387
+ // A parameter the omission rule widened is still this rule's: widening
3388
+ // answers only "may it be absent", while this answers which object the
3389
+ // record statement holds. memory-pager's `updated(page)` receives a `Page`
3390
+ // instance the census types `Page | undefined`; bound as the bare widened
3391
+ // statement, the instance was viewed into the record's struct -- a copy --
3392
+ // and `pager.updates[0] === one` compared a record with a `Page`.
3393
+ const widened = omissionWidened.has(site.parameter);
3394
+ if ((bindings.has(site.parameter) && !widened) || unionArms.has(site.parameter) || recordHomeArms.has(site.parameter))
3384
3395
  continue;
3385
3396
  if (!ts.isIdentifier(site.parameter.name))
3386
3397
  continue;
@@ -3397,7 +3408,12 @@ hostProvided = noHostProvidedNames) => {
3397
3408
  if (classes.length === 0)
3398
3409
  continue;
3399
3410
  const declaredArms = site.stated.isUnion() ? site.stated.types : [site.stated];
3400
- recordHomeArms.set(site.parameter, withDeclaredAbsenceArms(site.parameter, [...declaredArms, ...classes]));
3411
+ const absence = widened ? [checker.getUndefinedType()] : [];
3412
+ recordHomeArms.set(site.parameter, withDeclaredAbsenceArms(site.parameter, [...declaredArms, ...classes, ...absence]));
3413
+ if (widened) {
3414
+ bindings.delete(site.parameter);
3415
+ statedBindings.delete(site.parameter);
3416
+ }
3401
3417
  if (process.env['GEA_BINDING_DEBUG'])
3402
3418
  console.error(`[CLASS-INSTANCE] ${describeParameter(site.parameter)} :: ${classes.map((arm) => checker.typeToString(arm)).join(' | ')}`);
3403
3419
  }
@@ -3543,14 +3559,24 @@ hostProvided = noHostProvidedNames) => {
3543
3559
  * construct path. Only the absence members are taken from the checker --
3544
3560
  * everything else the read holds is still the census's answer.
3545
3561
  */
3546
- const withReadAbsenceOf = (read, bound) => {
3562
+ const withReadAbsenceOf = (read, parameter, bound) => {
3547
3563
  if (!bound.isUnion())
3548
3564
  return bound;
3549
3565
  const checked = checker.getTypeAtLocation(read);
3550
3566
  if ((checked.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) !== 0)
3551
3567
  return bound;
3552
- const present = (checked.isUnion() ? checked.types : [checked]).reduce((flags, part) => flags | part.flags, 0);
3553
- const dropped = (ts.TypeFlags.Undefined | ts.TypeFlags.Null) & ~present;
3568
+ const flagsOf = (type) => (type.isUnion() ? type.types : [type]).reduce((flags, part) => flags | part.flags, 0);
3569
+ const present = flagsOf(checked);
3570
+ // The checker's read lacks an absence only as evidence that its flow ruled
3571
+ // it out when the parameter's own declaration admits it. A binding that
3572
+ // ADDS an absence the statement never spelled -- `omitted-stated-
3573
+ // parameter.ts`'s `@param {boolean} premultipliedAlpha` that
3574
+ // `colorBuffer.setClear( 0, 0, 0, 1 )` leaves out -- reads as `boolean` at
3575
+ // every mention, so stripping on that basis undid the widening at each
3576
+ // read: three's `premultipliedAlpha === true` converted the omitted
3577
+ // argument to a bare boolean and threw where the language answers false.
3578
+ const declared = flagsOf(checker.getTypeAtLocation(parameter));
3579
+ const dropped = (ts.TypeFlags.Undefined | ts.TypeFlags.Null) & ~present & declared;
3554
3580
  // A narrowed `BufferSource` read under `ArrayBuffer.isView(data)` is an
3555
3581
  // `ArrayBufferView` to the checker: the arms its flow ruled out are the
3556
3582
  // callers' arms not assignable to what it reads there.
@@ -3625,7 +3651,7 @@ hostProvided = noHostProvidedNames) => {
3625
3651
  continue;
3626
3652
  if (guardNarrowsDynamicBinding(node, narrowed))
3627
3653
  return null;
3628
- return withReadAbsenceOf(node, bodyBindingOf(declaration, narrowed));
3654
+ return withReadAbsenceOf(node, declaration, bodyBindingOf(declaration, narrowed));
3629
3655
  }
3630
3656
  return null;
3631
3657
  };
@@ -3671,7 +3697,7 @@ hostProvided = noHostProvidedNames) => {
3671
3697
  const narrowed = ordinal === null ? undefined : copyBindings.get(parameter)?.get(ordinal);
3672
3698
  if (!narrowed)
3673
3699
  return null;
3674
- return node === parameter || !ts.isIdentifier(node) ? narrowed : withReadAbsenceOf(node, bodyBindingOf(parameter, narrowed));
3700
+ return node === parameter || !ts.isIdentifier(node) ? narrowed : withReadAbsenceOf(node, parameter, bodyBindingOf(parameter, narrowed));
3675
3701
  };
3676
3702
  // Implicit slots have an owning signature but no parameter declaration.
3677
3703
  // Reuse the settled call attribution and resolver; never start a second
@@ -2169,6 +2169,23 @@ const buildMapper = (checker, identities, table, instantiations, specializations
2169
2169
  .find((candidate) => candidate.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown));
2170
2170
  if (absorbing)
2171
2171
  return remember(type, typeOf(absorbing));
2172
+ // The global `Object` interface absorbs it too. It is interned as `any`
2173
+ // (above), and a union with a member that is `any` IS `any`; but the
2174
+ // checker keeps `Object | string` as a two-member union, because it only
2175
+ // reduces by `any` flags, so the member reached here as an `any` arm
2176
+ // BESIDE a string one. A sum with an open arm is not a sum: its arms are
2177
+ // not disjoint (every value is the open arm's), a `false` handed to the
2178
+ // parameter matched neither arm, and a live string was ambiguous between
2179
+ // them at the unbox. three.js's `Object3D.toJSON( meta )` is documented
2180
+ // `{?(Object|string)}` and `LightShadow.toJSON` passes `false`. `Object`
2181
+ // admits every non-nullish value -- strings included -- so the union
2182
+ // states nothing the open carrier does not.
2183
+ const objectMember = type.types.find((member) => {
2184
+ const anchor = member.getSymbol()?.declarations?.[0];
2185
+ return anchor !== undefined && isGlobalObjectInterface(checker, anchor, member);
2186
+ });
2187
+ if (objectMember)
2188
+ return remember(type, typeOf(objectMember));
2172
2189
  // An arm naming a type the host says is ABSENT is not an arm this
2173
2190
  // program can ever take. `absentGlobals` already folds the VALUE
2174
2191
  // (`typeof HTMLImageElement !== 'undefined'` is `false` on a headless
@@ -1,9 +1,10 @@
1
1
  import ts from 'typescript';
2
2
  import { withStableTypeQueries } from './stable-checker.js';
3
+ import { sharedDeclarationReader } from './shared-declaration-files.js';
3
4
  import { basename, dirname, join, resolve } from 'node:path';
4
5
  import { isBuiltin } from 'node:module';
5
6
  import { createModuleResolver, isDeclarationPath, mappedTypeScriptSource, moduleExtension, typeOnlyModuleUse } from './module-resolution.js';
6
- import { createCommonJsRequireCensus } from './normalize/commonjs-require.js';
7
+ import { createCommonJsRequireCensus, createCommonJsRequireTargetCensus } from './normalize/commonjs-require.js';
7
8
  import { withoutBareWrapperRedeclarations } from './commonjs-wrapper.js';
8
9
  import { withoutModuleAmbientGlobalRedeclarations } from './ambient.js';
9
10
  import { resolveHostMethod } from './host-methods.js';
@@ -383,11 +384,12 @@ const withoutShadowedAmbientModules = (file, shadowed, version) => {
383
384
  }
384
385
  return ts.createSourceFile(file.fileName, text, version, true, scriptKindOf(file.fileName));
385
386
  };
386
- const transformingHost = (input, options, resolutionDiagnostics, preparedSourceText, timing, requiredJsonFiles = new Set()) => {
387
+ const transformingHost = (input, options, resolutionDiagnostics, preparedSourceText, timing, requiredJsonFiles = new Set(), transformed = new Map()) => {
387
388
  const transforms = input.sourceTransforms ?? [];
388
389
  const overlay = input.sourceOverlay;
389
390
  const host = ts.createCompilerHost(options, true);
390
- const read = host.getSourceFile.bind(host);
391
+ // Declaration files (`lib.*.d.ts`, `@types`) are parsed once per process; see `shared-declaration-files.ts`.
392
+ const read = sharedDeclarationReader(host.getSourceFile.bind(host), options, host.getDefaultLibFileName(options));
391
393
  // An overlaid path must answer every question the filesystem would, not just
392
394
  // the one that reads it: module resolution asks `fileExists` first and never
393
395
  // reaches `getSourceFile` for a path it believes is absent, which is exactly
@@ -465,20 +467,31 @@ const transformingHost = (input, options, resolutionDiagnostics, preparedSourceT
465
467
  return file;
466
468
  if (file.isDeclarationFile)
467
469
  return withoutShadowedAmbientModules(file, shadowedSpecifiers, languageVersionOrOptions);
468
- let text = jsonModuleAsTypeScript(fileName, file.text, requiredJsonFiles) ?? file.text;
470
+ const original = jsonModuleAsTypeScript(fileName, file.text, requiredJsonFiles) ?? file.text;
469
471
  const declarationFileName = declarations.get(resolve(fileName));
470
- for (const [index, transform] of transforms.entries()) {
471
- text = timing.measure(`transform:${index}:${transform.name}`, () => transform({ fileName, text, ...(declarationFileName ? { declarationFileName } : {}) }) ?? text);
472
+ let text = original;
473
+ // The transforms are a pure function of (file, text, declaration): every
474
+ // program the preparation loop rebuilds re-reads the same unchanged files,
475
+ // and re-running 17 transforms over 1650 of them is 1.5 s a program. Only
476
+ // the TEXT is reused -- each program parses its own SourceFile below.
477
+ const remembered = transformed.get(fileName);
478
+ if (remembered && remembered.input === original && remembered.declarationFileName === declarationFileName)
479
+ text = remembered.output;
480
+ else {
481
+ for (const [index, transform] of transforms.entries()) {
482
+ text = timing.measure(`transform:${index}:${transform.name}`, () => transform({ fileName, text, ...(declarationFileName ? { declarationFileName } : {}) }) ?? text);
483
+ }
484
+ transformed.set(fileName, { input: original, declarationFileName, output: text });
472
485
  }
473
- const transformed = text === file.text ? file : ts.createSourceFile(fileName, text, languageVersionOrOptions, true, scriptKindOf(fileName));
486
+ const transformedFile = text === file.text ? file : ts.createSourceFile(fileName, text, languageVersionOrOptions, true, scriptKindOf(fileName));
474
487
  // Asked of the TRANSFORMED file, not the one on disk: a plugin (or the
475
488
  // `.json` rewrite above) can add the import or export that already makes
476
489
  // the file a module, and can equally introduce the top-level `await` that
477
490
  // asks for one. Either way the question is about the text this program
478
491
  // actually compiles.
479
- const marked = moduleMarkerForTopLevelAwait(transformed);
492
+ const marked = moduleMarkerForTopLevelAwait(transformedFile);
480
493
  if (marked === null)
481
- return transformed;
494
+ return transformedFile;
482
495
  return ts.createSourceFile(fileName, marked, languageVersionOrOptions, true, scriptKindOf(fileName));
483
496
  };
484
497
  return host;
@@ -499,11 +512,11 @@ const packageNameOf = (specifier) => {
499
512
  const packageName = specifier.startsWith('@') ? (segments.length >= 2 ? `${segments[0]}/${segments[1]}` : '') : (segments[0] ?? '');
500
513
  return packageName === '' || packageName.startsWith('@/') || packageName.endsWith('/') ? null : packageName;
501
514
  };
502
- const staticCommonJsTargetsOf = (program, globals, targetOf) => {
515
+ const staticCommonJsTargetsOf = (program, globals, targetOf, requireCensus = null) => {
503
516
  if (globals.size === 0)
504
517
  return [];
505
518
  const checker = program.getTypeChecker();
506
- const requireCensus = createCommonJsRequireCensus(checker, program.getSourceFiles(), globals);
519
+ requireCensus ??= createCommonJsRequireCensus(checker, program.getSourceFiles(), globals);
507
520
  const targets = new Set();
508
521
  const visit = (node, sourceFile) => {
509
522
  const argument = ts.isCallExpression(node) && node.arguments.length === 1 ? node.arguments[0] : undefined;
@@ -550,7 +563,7 @@ const staticBuiltinModuleTargetsOf = (program, bindings, names, sources) => {
550
563
  visit(sourceFile);
551
564
  return [...targets];
552
565
  };
553
- const configuredProgram = (input, resolutionDiagnostics, preparedSourceText, timing) => {
566
+ const configuredProgram = (input, resolutionDiagnostics, preparedSourceText, timing, transformed) => {
554
567
  const typesOnlyPackageOf = (specifier) => {
555
568
  if (!input.typesOnlyPackages || isBuiltin(specifier))
556
569
  return false;
@@ -622,9 +635,17 @@ const configuredProgram = (input, resolutionDiagnostics, preparedSourceText, tim
622
635
  const roots = new Set(rootNames);
623
636
  const commonJsTargetPaths = new Set();
624
637
  let program = timing.measure('create-program', () => ts.createProgram({ rootNames: [...roots], options, host }));
638
+ const globals = input.commonJsGlobals ?? new Map();
625
639
  for (;;) {
640
+ // A program this iteration is about to replace is never read again, so
641
+ // the full census (0.7-1 s, and a checker warm-up only the kept program
642
+ // needs) is spent only when no rebuild follows from the static requires.
643
+ const leanCensus = createCommonJsRequireTargetCensus(program.getTypeChecker(), program.getSourceFiles(), globals);
644
+ const leanTargets = leanCensus ? staticCommonJsTargetsOf(program, globals, targetOf, leanCensus) : null;
645
+ const rebuildFollows = (found) => found.some((target) => !roots.has(target) && program.getSourceFile(target) === undefined) ||
646
+ found.some((target) => target.endsWith('.json') && !requiredJsonFiles.has(target) && program.getSourceFile(target) !== undefined);
626
647
  const targets = [
627
- ...staticCommonJsTargetsOf(program, input.commonJsGlobals ?? new Map(), targetOf),
648
+ ...(leanTargets !== null && rebuildFollows(leanTargets) ? leanTargets : staticCommonJsTargetsOf(program, globals, targetOf)),
628
649
  ...staticBuiltinModuleTargetsOf(program, input.hostMethodBindings ?? new Map(), input.commonJsBuiltinModules ?? new Map(), input.commonJsBuiltinModuleSources ?? new Map())
629
650
  ];
630
651
  for (const target of targets)
@@ -656,7 +677,7 @@ const configuredProgram = (input, resolutionDiagnostics, preparedSourceText, tim
656
677
  };
657
678
  if (!projectFileName) {
658
679
  const options = { ...input.options, ...(input.dynamicFallback ? { noImplicitAny: false, checkJs: false } : {}) };
659
- const host = transformingHost(input, options, resolutionDiagnostics, preparedSourceText, timing, requiredJsonFiles);
680
+ const host = transformingHost(input, options, resolutionDiagnostics, preparedSourceText, timing, requiredJsonFiles, transformed);
660
681
  const rootNames = [
661
682
  ...new Set([
662
683
  ...input.rootFileNames,
@@ -699,7 +720,7 @@ const configuredProgram = (input, resolutionDiagnostics, preparedSourceText, tim
699
720
  ...fixedOptions,
700
721
  ...(input.dynamicFallback ? { noImplicitAny: false, checkJs: false } : {})
701
722
  };
702
- const host = transformingHost(input, options, resolutionDiagnostics, preparedSourceText, timing, requiredJsonFiles);
723
+ const host = transformingHost(input, options, resolutionDiagnostics, preparedSourceText, timing, requiredJsonFiles, transformed);
703
724
  return buildProgram(rootNames, options, host ?? ts.createCompilerHost(options, true));
704
725
  };
705
726
  /**
@@ -724,7 +745,8 @@ const entryFilesOf = (program, rootFileNames) => {
724
745
  export const createProgram = (input) => {
725
746
  const timing = createFrontendTiming('program');
726
747
  const resolutionDiagnostics = [];
727
- let configured = configuredProgram(input, resolutionDiagnostics, new Map(), timing);
748
+ const transformOutputs = new Map();
749
+ let configured = configuredProgram(input, resolutionDiagnostics, new Map(), timing, transformOutputs);
728
750
  const preparation = timing.measure('diagnostic-source-preparation', () => diagnosticSourcePreparation(ts, configured.program, input.packageSources ?? []));
729
751
  // A bare `var require` in a CommonJS module redeclares the wrapper's own
730
752
  // parameter; blanked here so the checker types the name from the host's
@@ -738,7 +760,7 @@ export const createProgram = (input) => {
738
760
  if (preparation.audit.length > 0 || redeclarations.size > 0 || ambientRestatements.size > 0) {
739
761
  resolutionDiagnostics.length = 0;
740
762
  prepared = new Map([...preparation.sourceText, ...redeclarations, ...ambientRestatements]);
741
- configured = configuredProgram(input, resolutionDiagnostics, prepared, timing);
763
+ configured = configuredProgram(input, resolutionDiagnostics, prepared, timing, transformOutputs);
742
764
  }
743
765
  // Asked of the program the preparations above produced, so each rewritten
744
766
  // text already carries theirs (`unchecked-guard-argument-copies.ts`).
@@ -746,7 +768,7 @@ export const createProgram = (input) => {
746
768
  if (guardCopies.sourceText.size > 0) {
747
769
  resolutionDiagnostics.length = 0;
748
770
  prepared = new Map([...prepared, ...guardCopies.sourceText]);
749
- configured = configuredProgram(input, resolutionDiagnostics, prepared, timing);
771
+ configured = configuredProgram(input, resolutionDiagnostics, prepared, timing, transformOutputs);
750
772
  }
751
773
  // A declaration a write the checker does not check stores a value outside
752
774
  // of is restated to admit it (`unchecked-write-member-declarations.ts`). Asked last, of the text every
@@ -755,14 +777,14 @@ export const createProgram = (input) => {
755
777
  if (uncheckedWriteMembers.size > 0) {
756
778
  resolutionDiagnostics.length = 0;
757
779
  prepared = new Map([...prepared, ...uncheckedWriteMembers]);
758
- configured = configuredProgram(input, resolutionDiagnostics, prepared, timing);
780
+ configured = configuredProgram(input, resolutionDiagnostics, prepared, timing, transformOutputs);
759
781
  }
760
782
  // A private static predicate over `unknown` is restated over what its callers
761
783
  // pass (`known-caller-predicate-parameters.ts`). Asked of the final text.
762
784
  const predicateParameters = timing.measure('known-caller-predicate-parameters', () => knownCallerPredicateParameters(configured.program, configured.program.getTypeChecker()));
763
785
  if (predicateParameters.size > 0) {
764
786
  resolutionDiagnostics.length = 0;
765
- configured = configuredProgram(input, resolutionDiagnostics, new Map([...prepared, ...predicateParameters]), timing);
787
+ configured = configuredProgram(input, resolutionDiagnostics, new Map([...prepared, ...predicateParameters]), timing, transformOutputs);
766
788
  }
767
789
  const program = configured.program;
768
790
  const checker = withStableTypeQueries(program.getTypeChecker(), program);
@@ -0,0 +1,44 @@
1
+ import ts from 'typescript';
2
+ /**
3
+ * A process-wide cache of the PARSED declaration files every program re-reads:
4
+ * TypeScript's own `lib.*.d.ts` and `node_modules/@types/**`.
5
+ *
6
+ * WHY. A compile reads the same few hundred declaration files every time --
7
+ * `lib.dom.d.ts` alone is over a megabyte -- and a process that compiles more
8
+ * than one program (the emitted-set gate compiles ~1330 per shard, and one
9
+ * compile builds several `ts.Program`s) paid `createSourceFile` and the parent
10
+ * walk for each of them again. Measured on the gate's runtime set: parsing was
11
+ * 41% of CPU, and the binder walking the same files again for each new checker
12
+ * was another 12%.
13
+ *
14
+ * WHAT IS SHARED, AND WHAT IS NOT. Only the `ts.SourceFile` -- the parse tree.
15
+ * Every checker is still created per compile, exactly as before, so no
16
+ * `ts.Type`, no checker answer and no query history is shared: those live in
17
+ * the checker's own tables, keyed by node id. Sharing the tree is the
18
+ * arrangement TypeScript's language service itself uses across programs: the
19
+ * binder's `symbol`/`locals` on a node are checker-independent (a checker that
20
+ * merges a shared symbol clones it first and records the merge in its own
21
+ * array).
22
+ *
23
+ * THE RULE THIS PUTS ON THE REST OF THE COMPILER. A node of a shared file
24
+ * outlives the compile that read it, so module-level state keyed by such a node
25
+ * must hold only facts that are a pure function of the file. A checker answer
26
+ * (`ts.Type`, `ts.Symbol` obtained through a checker) must be keyed by the
27
+ * checker first. `bivariant-slot-parameter.ts` is the one that did not, and now
28
+ * does. Nothing may write to a node of a declaration file.
29
+ *
30
+ * THE KEY. Everything the parse depends on: the exact file name, the language
31
+ * version, the implied module format, and the compiler options that decide the
32
+ * external-module indicator (`moduleDetection`, `module`, `jsx`) -- plus the
33
+ * file's mtime and size, so an edited `.d.ts` is re-read rather than served
34
+ * stale by a long-lived process.
35
+ *
36
+ * NOT SHARED: a declaration file the caller's source transforms, overlay or
37
+ * ambient-module shadowing would rewrite. `transformingHost` consults those
38
+ * before it ever reaches this reader, and applies shadowing to whatever this
39
+ * returns -- it builds a NEW file when it blanks a block and returns the shared
40
+ * one untouched otherwise.
41
+ */
42
+ type SourceFileReader = ts.CompilerHost['getSourceFile'];
43
+ export declare const sharedDeclarationReader: (read: SourceFileReader, options: ts.CompilerOptions, defaultLibFileName: string) => SourceFileReader;
44
+ export {};
@@ -0,0 +1,42 @@
1
+ import { statSync } from 'node:fs';
2
+ import { basename, dirname, resolve } from 'node:path';
3
+ const shared = new Map();
4
+ const typesDirectoryMarker = '/node_modules/@types/';
5
+ const isDeclarationFileName = (fileName) => /\.d\.[cm]?ts$/.test(fileName);
6
+ const optionsKeyOf = (options) => [options.moduleDetection, options.module, options.jsx, options.target].map((value) => String(value)).join(',');
7
+ export const sharedDeclarationReader = (read, options, defaultLibFileName) => {
8
+ const libDirectory = dirname(resolve(defaultLibFileName));
9
+ const optionsKey = optionsKeyOf(options);
10
+ const isShared = (fileName) => {
11
+ if (!isDeclarationFileName(fileName))
12
+ return false;
13
+ const absolute = resolve(fileName);
14
+ if (absolute.split('\\').join('/').includes(typesDirectoryMarker))
15
+ return true;
16
+ return dirname(absolute) === libDirectory && basename(absolute).startsWith('lib.');
17
+ };
18
+ return (fileName, languageVersionOrOptions, onError, shouldCreateNewSourceFile) => {
19
+ if (shouldCreateNewSourceFile === true || !isShared(fileName))
20
+ return read(fileName, languageVersionOrOptions, onError, shouldCreateNewSourceFile);
21
+ let stat;
22
+ try {
23
+ stat = statSync(fileName, { throwIfNoEntry: false });
24
+ }
25
+ catch {
26
+ stat = undefined;
27
+ }
28
+ if (stat === undefined)
29
+ return read(fileName, languageVersionOrOptions, onError, shouldCreateNewSourceFile);
30
+ const version = typeof languageVersionOrOptions === 'number'
31
+ ? String(languageVersionOrOptions)
32
+ : `${languageVersionOrOptions.languageVersion},${languageVersionOrOptions.impliedNodeFormat},${languageVersionOrOptions.jsDocParsingMode}`;
33
+ const key = `${fileName}\0${version}\0${optionsKey}`;
34
+ const held = shared.get(key);
35
+ if (held !== undefined && held.modifiedMs === stat.mtimeMs && held.size === stat.size)
36
+ return held.file;
37
+ const file = read(fileName, languageVersionOrOptions, onError, shouldCreateNewSourceFile);
38
+ if (file !== undefined)
39
+ shared.set(key, { file, modifiedMs: stat.mtimeMs, size: stat.size });
40
+ return file;
41
+ };
42
+ };
@@ -720,6 +720,87 @@ const classImportLine = (info, hereDir) => {
720
720
  const exported = info.exportName === info.name ? info.name : `${info.exportName} as ${info.name}`;
721
721
  return `@import { ${exported} } from '${specifier}'`;
722
722
  };
723
+ const scanPackageFile = (filePath, text) => {
724
+ const file = ts.createSourceFile(filePath, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
725
+ const untrustedClassNames = [];
726
+ const externallyReadNames = [];
727
+ const unresolvedHeritageTexts = [];
728
+ const constants = [];
729
+ const classes = [];
730
+ const scanForMutation = (node) => {
731
+ const target = prototypeMutationTarget(node);
732
+ if (target)
733
+ untrustedClassNames.push(target);
734
+ if (ts.isPropertyAccessExpression(node) && node.expression.kind !== ts.SyntaxKind.ThisKeyword && ts.isIdentifier(node.name)) {
735
+ externallyReadNames.push(node.name.text);
736
+ }
737
+ ts.forEachChild(node, scanForMutation);
738
+ };
739
+ scanForMutation(file);
740
+ for (const statement of file.statements) {
741
+ if (!ts.isVariableStatement(statement) || (statement.declarationList.flags & ts.NodeFlags.Const) === 0)
742
+ continue;
743
+ if (!statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword))
744
+ continue;
745
+ for (const declaration of statement.declarationList.declarations) {
746
+ const domain = declaration.initializer ? literalShapeText(declaration.initializer) : null;
747
+ if (!ts.isIdentifier(declaration.name) || (domain !== 'number' && domain !== 'string' && domain !== 'boolean'))
748
+ continue;
749
+ constants.push({ name: declaration.name.text, domain });
750
+ }
751
+ }
752
+ for (const statement of file.statements) {
753
+ if (!ts.isClassDeclaration(statement) || !statement.name)
754
+ continue;
755
+ const className = statement.name.text;
756
+ let baseName = null;
757
+ const heritage = statement.heritageClauses?.find((h) => h.token === ts.SyntaxKind.ExtendsKeyword);
758
+ const heritageExpr = heritage?.types[0]?.expression;
759
+ if (heritageExpr) {
760
+ if (ts.isIdentifier(heritageExpr))
761
+ baseName = heritageExpr.text;
762
+ // Anything else -- a call, a property access, a mixin factory -- is
763
+ // a base this scan cannot name outright; recorded so any base whose
764
+ // name it mentions can be refused (see `unresolvedHeritageTexts`).
765
+ else
766
+ unresolvedHeritageTexts.push(heritageExpr.getText(file));
767
+ }
768
+ const evidence = memberTypeTextsOf(statement, file);
769
+ classes.push({
770
+ name: className,
771
+ filePath,
772
+ exportName: classExportName(file, statement),
773
+ baseName,
774
+ declaredNames: evidence.declaredNames,
775
+ ownMembers: evidence.text,
776
+ ownObjectShapes: evidence.objectShape
777
+ });
778
+ }
779
+ return { untrustedClassNames, externallyReadNames, unresolvedHeritageTexts, constants, classes };
780
+ };
781
+ /**
782
+ * Per-file scans, kept for the life of the process and validated by TEXT.
783
+ *
784
+ * The package index is rebuilt per compile (its own caches are per reader, and
785
+ * two readers can see two texts for one path), yet a package's files do not
786
+ * change between the compiles of one process -- the gate compiles hundreds of
787
+ * programs against the same three.js tree. Re-parsing and re-walking all of
788
+ * them each time was a visible share of a JavaScript compile. The key is the
789
+ * path and the text the reader returned for it, so a plugin transform or an
790
+ * edited file is a miss rather than a stale hit; the reader is still called for
791
+ * every file, which is the cheap part. Process-wide state on purpose: the
792
+ * scan is a pure function of (path, text), so nothing here can differ between
793
+ * compiles.
794
+ */
795
+ const fileScans = new Map();
796
+ const scanOf = (filePath, text) => {
797
+ const held = fileScans.get(filePath);
798
+ if (held !== undefined && held.text === text)
799
+ return held.scan;
800
+ const scan = scanPackageFile(filePath, text);
801
+ fileScans.set(filePath, { text, scan });
802
+ return scan;
803
+ };
723
804
  const buildPackageIndex = (root, read, neverSkip) => {
724
805
  const key = indexKey(root, neverSkip);
725
806
  const cached = cachesFor(read).index.get(key);
@@ -740,60 +821,21 @@ const buildPackageIndex = (root, read, neverSkip) => {
740
821
  catch {
741
822
  continue;
742
823
  }
743
- const file = ts.createSourceFile(filePath, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
744
- const scanForMutation = (node) => {
745
- const target = prototypeMutationTarget(node);
746
- if (target)
747
- untrustedClassNames.add(target);
748
- if (ts.isPropertyAccessExpression(node) && node.expression.kind !== ts.SyntaxKind.ThisKeyword && ts.isIdentifier(node.name)) {
749
- externallyReadNames.add(node.name.text);
750
- }
751
- ts.forEachChild(node, scanForMutation);
752
- };
753
- scanForMutation(file);
754
- for (const statement of file.statements) {
755
- if (!ts.isVariableStatement(statement) || (statement.declarationList.flags & ts.NodeFlags.Const) === 0)
756
- continue;
757
- if (!statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword))
758
- continue;
759
- for (const declaration of statement.declarationList.declarations) {
760
- const domain = declaration.initializer ? literalShapeText(declaration.initializer) : null;
761
- if (!ts.isIdentifier(declaration.name) || (domain !== 'number' && domain !== 'string' && domain !== 'boolean'))
762
- continue;
763
- if (constantDomainsByName.has(declaration.name.text))
764
- duplicateConstants.add(declaration.name.text);
765
- constantDomainsByName.set(declaration.name.text, domain);
766
- }
824
+ const scan = scanOf(filePath, text);
825
+ for (const name of scan.untrustedClassNames)
826
+ untrustedClassNames.add(name);
827
+ for (const name of scan.externallyReadNames)
828
+ externallyReadNames.add(name);
829
+ unresolvedHeritageTexts.push(...scan.unresolvedHeritageTexts);
830
+ for (const { name, domain } of scan.constants) {
831
+ if (constantDomainsByName.has(name))
832
+ duplicateConstants.add(name);
833
+ constantDomainsByName.set(name, domain);
767
834
  }
768
- for (const statement of file.statements) {
769
- if (!ts.isClassDeclaration(statement) || !statement.name)
770
- continue;
771
- const className = statement.name.text;
772
- let baseName = null;
773
- const heritage = statement.heritageClauses?.find((h) => h.token === ts.SyntaxKind.ExtendsKeyword);
774
- const heritageExpr = heritage?.types[0]?.expression;
775
- if (heritageExpr) {
776
- if (ts.isIdentifier(heritageExpr))
777
- baseName = heritageExpr.text;
778
- // Anything else -- a call, a property access, a mixin factory -- is
779
- // a base this scan cannot name outright; recorded so any base whose
780
- // name it mentions can be refused (see `unresolvedHeritageTexts`).
781
- else
782
- unresolvedHeritageTexts.push(heritageExpr.getText(file));
783
- }
784
- const evidence = memberTypeTextsOf(statement, file);
785
- const info = {
786
- name: className,
787
- filePath,
788
- exportName: classExportName(file, statement),
789
- baseName,
790
- declaredNames: evidence.declaredNames,
791
- ownMembers: evidence.text,
792
- ownObjectShapes: evidence.objectShape
793
- };
794
- if (classesByName.has(className))
795
- duplicateNames.add(className);
796
- classesByName.set(className, info);
835
+ for (const info of scan.classes) {
836
+ if (classesByName.has(info.name))
837
+ duplicateNames.add(info.name);
838
+ classesByName.set(info.name, info);
797
839
  }
798
840
  }
799
841
  for (const name of duplicateNames)