@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
@@ -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)
@@ -481,7 +481,10 @@ export { emitToNumericCoercion } from './emit-tonumber.js';
481
481
  export const emitSpreadCopy = (ctx, lines, operation) => {
482
482
  const receiver = operation.receiver.representation;
483
483
  const source = operation.source.representation;
484
- if (source.kind === 'dynamic' && receiver.kind !== 'dynamic' && !isDynamicCopyableIntoFieldRecord(ctx.deriver, receiver)) {
484
+ if (source.kind === 'dynamic' &&
485
+ receiver.kind !== 'dynamic' &&
486
+ !isDynamicCopyableIntoFieldRecord(ctx.deriver, receiver) &&
487
+ !(receiver.kind === 'dictionary' && receiver.key === 'string')) {
485
488
  throw createCppEmitBlockedError(`runtime-helper:protocol:spread:next:${spreadSourceCarrierKeyOf(source.kind, source, receiver, ctx.deriver)}`, `requires a dynamic object-spread receiver for a dynamic source, but the receiver is a "${representationKey(receiver)}"; this runtime-key walk is installed only for a dynamic receiver`);
486
489
  }
487
490
  if (receiver.kind === 'dynamic') {
@@ -528,8 +531,38 @@ export const emitSpreadCopy = (ctx, lines, operation) => {
528
531
  const receiverText = operandText(ctx, operation.receiver);
529
532
  const receiverRef = memberAccessOperator(receiver.ownership) === '->' ? `(*${receiverText})` : receiverText;
530
533
  const sourceText = operandText(ctx, operation.source);
534
+ if (source.kind === 'dynamic') {
535
+ emitDynamicSpreadIntoDictionary(ctx, lines, source, sourceText, receiver, receiverRef);
536
+ return;
537
+ }
531
538
  emitSpreadSourceCopy(ctx, lines, source, sourceText, receiver, receiverRef, spreadKeysOf(operation));
532
539
  };
540
+ /**
541
+ * `{ ...value }` of a dynamic source into a string-keyed dictionary: mongodb's
542
+ * `mechanismProperties = { ...optionValue }`, where `optionValue` is declared
543
+ * `unknown` and only bounded by an `isRecord` guard
544
+ * (`producers/shared.ts`'s `dynamicSpreadSourceTypeOf`). The keys exist only at
545
+ * runtime, so each own enumerable string key is read as a `gea::Value` and
546
+ * stored through the dictionary's checked value conversion -- the same walk
547
+ * `Object.assign` of a dynamic source into a typed dictionary uses
548
+ * (`host/emit-host-object.ts`). `null`/`undefined` copy nothing.
549
+ */
550
+ const emitDynamicSpreadIntoDictionary = (ctx, lines, source, sourceText, receiver, receiverRef) => {
551
+ const converted = alignedValueText(ctx, 'emit-allocation.ts:dynamic-spread-into-dictionary', source, receiver.value, '__gea_spread_value');
552
+ if (converted === null) {
553
+ throw createCppEmitBlockedError(`conversion:${representationKey(source)}->${representationKey(receiver.value)}`, `copies a dynamic object-spread source into a dictionary of "${representationKey(receiver.value)}" values; ` +
554
+ 'no installed conversion unboxes a dynamic value into that type');
555
+ }
556
+ lines.push('{');
557
+ lines.push(`const auto& __gea_spread_source = ${sourceText};`);
558
+ lines.push('if (__gea_spread_source.tag() != gea::Value::Tag::Null && __gea_spread_source.tag() != gea::Value::Tag::Undefined) {');
559
+ lines.push('for (const std::string& __gea_spread_key : __gea_spread_source.ownEnumerableStringKeys()) {');
560
+ lines.push('const gea::Value __gea_spread_value = __gea_spread_source.getProperty(gea::PropertyKey::string(__gea_spread_key));');
561
+ lines.push(`${receiverRef}[__gea_spread_key] = ${converted};`);
562
+ lines.push('}');
563
+ lines.push('}');
564
+ lines.push('}');
565
+ };
533
566
  /**
534
567
  * The keys a statically fielded source may contribute: its TYPE's own keys
535
568
  * when the operation states them (`SpreadCopyOperation.keys`), since the
@@ -77,7 +77,14 @@ export const unionClassMethodValueReceiverClaim = (ctx, operation) => {
77
77
  // each arm has already bound its own receiver into the value
78
78
  // (`receiverBoundFieldText`), and handing the union back at the call would
79
79
  // pass it as the first ARGUMENT.
80
- const publishedAbi = abiOfCallee(operation.result.representation);
80
+ // A union whose other arms lack the member publishes the method as
81
+ // `optional(callable)`: those arms answer `undefined`. The call behind a
82
+ // guard (`value && value.isColor ? value.getHex() : ...`) still fills the
83
+ // callable's receiver slot, so the claim reads the convention through that
84
+ // absence. three.js's `ShaderMaterial.toJSON` reads `getHex` this way.
85
+ const published = operation.result.representation;
86
+ const callable = published.kind === 'optional' && published.absence === 'undefined' ? published.payload : published;
87
+ const publishedAbi = abiOfCallee(callable);
81
88
  if (publishedAbi === null || publishedAbi.receiver === null)
82
89
  return null;
83
90
  const key = ctx.staticKeyTexts.get(operation.key.value);
@@ -329,7 +336,13 @@ const armRuntimeFieldText = (ctx, arm, armExprText, key, operation) => {
329
336
  // native answer for overload probes such as `number | Vector3` reading
330
337
  // `isVector3`: the scalar arm contributes `undefined`, while the class arm
331
338
  // contributes the declared boolean marker.
332
- if (!objectPrototypeMemberNames.has(key) && published.kind === 'optional' && published.absence === 'undefined') {
339
+ //
340
+ // A `dynamic` result holds that `undefined` as well as an optional does:
341
+ // three.js's `ShaderMaterial.toJSON` reads `value.toJSON` off a uniform
342
+ // whose arms are numbers, booleans and textures, and the member's result is
343
+ // the open carrier because the class arms publish a method there.
344
+ if (!objectPrototypeMemberNames.has(key) &&
345
+ (published.kind === 'dynamic' || (published.kind === 'optional' && published.absence === 'undefined'))) {
333
346
  return cppUndefinedIn(published);
334
347
  }
335
348
  // A canonical index on a number or boolean: no wrapper prototype holds an
@@ -1212,7 +1225,7 @@ export const taggedUnionGetText = (ctx, lines, operation) => {
1212
1225
  // No native recipe is not proof of absence: a prototype or accessor
1213
1226
  // may answer this key. Keep that case visible instead of inventing an
1214
1227
  // undefined result or boxing the typed receiver.
1215
- throw createCppEmitBlockedError('property-access:tagged-union:get:false', `a "get" of "${key}" on a tagged union reaches an arm carried as "${representationKey(leaf.representation)}" with no native property recipe ` +
1228
+ throw createCppEmitBlockedError('property-access:tagged-union:get:false', `a "get" of "${key}" on the tagged union "${representationKey(receiver)}" reaches an arm carried as "${representationKey(leaf.representation)}" with no native property recipe ` +
1216
1229
  `producing "${representationKey(published)}"; boxing a typed receiver is not a property implementation`);
1217
1230
  }
1218
1231
  if (representationKey(site.representation) === representationKey(published))
@@ -1516,7 +1516,7 @@ export const currentCppRuntimeCapabilities = Object.freeze({
1516
1516
  // filters its descriptors for enumerability, gets each value, then creates
1517
1517
  // a data property on the receiver. The `dynamic->dynamic` suffix is
1518
1518
  // mandatory: a dictionary receiver requires a different key-domain
1519
- // contract and remains deliberately unclaimed.
1519
+ // contract, claimed separately below as `dynamic->dictionary(string)`.
1520
1520
  'protocol:spread:next:dynamic->dynamic',
1521
1521
  'protocol:spread:next:indexed-record<-copyable',
1522
1522
  // The same field-by-field copy into a literal with NO index signature
@@ -1533,6 +1533,15 @@ export const currentCppRuntimeCapabilities = Object.freeze({
1533
1533
  // names is read and lands in its field through the checked conversion
1534
1534
  // from `dynamic` -- `carrier-keys.ts`'s `isDynamicCopyableIntoFieldRecord`.
1535
1535
  'protocol:spread:next:field-record<-dynamic',
1536
+ // A genuinely dynamic source into a STRING-keyed dictionary receiver --
1537
+ // mongodb's `mechanismProperties = { ...optionValue }` over an `unknown`
1538
+ // bounded only by `isRecord`. `emit-allocation.ts`'s
1539
+ // `emitDynamicSpreadIntoDictionary` walks the source's own enumerable
1540
+ // string keys and stores each value through the dictionary's checked
1541
+ // conversion from `dynamic`, the walk `Object.assign` of a dynamic source
1542
+ // into a typed dictionary already uses. The `(string)` suffix keeps a
1543
+ // number-keyed table, whose key contract differs, unclaimed.
1544
+ 'protocol:spread:next:dynamic->dictionary(string)',
1536
1545
  'protocol:spread:next:indexed-record(copyable)',
1537
1546
  'protocol:spread:next:optional(indexed-record(copyable))',
1538
1547
  // `yield x` inside a `function*`, and the resume point paired with it.
@@ -2971,7 +2971,14 @@ attributesConstant = false,
2971
2971
  */
2972
2972
  methodStateUntraced = false) => {
2973
2973
  const isNarrowed = (field) => narrowedSlots.has(integerStorageSlot(structName, field.key));
2974
- const tailFields = tailFieldsOf(layout, celled, reactive.cell, isNarrowed);
2974
+ // A class keeps every field inline. Its fields are stored by the
2975
+ // constructor views, the property-store emitter and callable frames, which
2976
+ // all address a class member by name; only the record paths spell a tail
2977
+ // block (`tailAwareFieldWriteText`). A tailed class therefore rendered
2978
+ // `gea_this->precision = ...` against a struct whose `precision` lived in
2979
+ // its tail -- three.js's `Material` crossed the sparse-layout threshold and
2980
+ // its own constructor no longer compiled.
2981
+ const tailFields = classDispatch ? emptyStringSet : tailFieldsOf(layout, celled, reactive.cell, isNarrowed);
2975
2982
  const tailStructName = cppRecordTailStructName(structName);
2976
2983
  const tailLines = [];
2977
2984
  if (tailFields.size > 0) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geastack/compiler",
3
- "version": "1.0.21",
3
+ "version": "1.0.22",
4
4
  "description": "The geastack TypeScript-to-C++ compiler: one semantic spine, no source-shaped authority, no boxing of statically typed values.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -71,7 +71,7 @@
71
71
  "test:node-project": "node test/node-project.mjs"
72
72
  },
73
73
  "dependencies": {
74
- "@geastack/node-compat": "^1.0.12",
74
+ "@geastack/node-compat": "^1.0.16",
75
75
  "typescript": "^5.9.3"
76
76
  },
77
77
  "devDependencies": {
@@ -80,19 +80,19 @@
80
80
  "find-my-way": "9.6.0",
81
81
  "prettier": "^3.8.3",
82
82
  "@geastack/core": "0.1.35",
83
- "@geastack/host": "0.1.12",
83
+ "@geastack/host": "0.1.14",
84
84
  "@geastack/engine": "0.1.11",
85
85
  "@geastack/elements": "0.1.4",
86
86
  "@geastack/geaos": "0.1.3",
87
- "@geastack/apple": "0.2.8",
88
- "@geastack/geatsc-plugin-gea": "0.1.6",
89
- "@geastack/geatsc-plugin-apple-native": "0.1.3",
90
- "@geastack/native-webgl-angle": "0.1.6"
87
+ "@geastack/apple": "0.2.13",
88
+ "@geastack/geatsc-plugin-gea": "0.1.17",
89
+ "@geastack/geatsc-plugin-apple-native": "0.1.4",
90
+ "@geastack/native-webgl-angle": "0.1.8"
91
91
  },
92
92
  "peerDependencies": {
93
- "@geastack/apple": ">=0.2.8",
94
- "@geastack/geatsc-plugin-apple-native": ">=0.1.3",
95
- "@geastack/geatsc-plugin-gea": ">=0.1.6"
93
+ "@geastack/apple": ">=0.2.13",
94
+ "@geastack/geatsc-plugin-apple-native": ">=0.1.4",
95
+ "@geastack/geatsc-plugin-gea": ">=0.1.17"
96
96
  },
97
97
  "peerDependenciesMeta": {
98
98
  "@geastack/apple": {