@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
@@ -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. */
@@ -1474,13 +1474,66 @@ const collectFunctions = (files) => {
1474
1474
  visit(file);
1475
1475
  return functions;
1476
1476
  };
1477
+ /**
1478
+ * What a read of `require` is, given the files that can write the wrapper cell
1479
+ * and the definition states the flow computed for them. Shared by the full
1480
+ * census and by `createCommonJsRequireTargetCensus`, which has no writer and
1481
+ * so no state to read: one definition of "static" for both.
1482
+ */
1483
+ const requireStatusOf = (checker, identity, requireWriters, reads) => {
1484
+ const statusOf = (expression, seen = new Set()) => {
1485
+ const node = unwrapExpression(expression);
1486
+ if (!ts.isIdentifier(node))
1487
+ return 'ordinary';
1488
+ const identityAtNode = identity.classify(node);
1489
+ if (identityAtNode.kind === 'provenance-failure')
1490
+ return 'provenance-failure';
1491
+ if (identityAtNode.kind === 'wrapper') {
1492
+ if (identityAtNode.global !== 'require')
1493
+ return 'ordinary';
1494
+ // A module whose source never writes its wrapper `require` (see
1495
+ // `requireWriters`) keeps Node's loader in that cell for its whole
1496
+ // lifetime, so every read of it is static -- including reads the
1497
+ // per-file flow never reaches (an exported function or a class method
1498
+ // only other modules call, which get no entry state here) and reads it
1499
+ // reaches as `unknown` only because an unresolved call *might* have been
1500
+ // one of this file's writers. Sound because the cell is a parameter of
1501
+ // this module's own wrapper function: no other module can name it, so
1502
+ // the only possible writers are syntactic writes in this file, and
1503
+ // `wrapperWrite` sees every one of them -- the first pass analyzes every
1504
+ // function body and every top level from a reachable state, and records
1505
+ // the writer before any reachability filter (a write the flow proves
1506
+ // dead never runs). A `var require`/`function require` rebinding either
1507
+ // is such a write or resolves the read to a user declaration, which is
1508
+ // not the wrapper and never gets here; the non-syntactic aliases (direct
1509
+ // `eval`, the wrapper's `arguments`) are `canAliasWrapperCells`.
1510
+ if (!requireWriters.has(node.getSourceFile()))
1511
+ return 'static';
1512
+ const definitions = reads.get(node) ?? unreachable;
1513
+ if (definitions === originalDefinition)
1514
+ return 'static';
1515
+ return definitions === unreachable ? 'ordinary' : 'possibly-reassigned';
1516
+ }
1517
+ const symbol = resolvedSymbolAt(checker, node);
1518
+ if (!symbol || seen.has(symbol))
1519
+ return 'ordinary';
1520
+ seen.add(symbol);
1521
+ const declaration = symbol.valueDeclaration;
1522
+ if (!declaration || !ts.isVariableDeclaration(declaration) || !declaration.initializer)
1523
+ return 'ordinary';
1524
+ if (!ts.isVariableDeclarationList(declaration.parent) || (declaration.parent.flags & ts.NodeFlags.Const) === 0)
1525
+ return 'ordinary';
1526
+ return statusOf(declaration.initializer, seen);
1527
+ };
1528
+ return statusOf;
1529
+ };
1477
1530
  /**
1478
1531
  * CommonJS static dispatch is a reaching-definition proof over one wrapper
1479
1532
  * cell per source module. The cell starts at Node's original loader and every
1480
1533
  * possible write replaces that proof with unknown. Const aliases snapshot the
1481
1534
  * definition at their own initializer; later cell writes cannot alter them.
1482
1535
  */
1483
- export const createCommonJsRequireCensus = (checker, files, globals) => {
1536
+ const analyseCommonJsRequireCensus = (checker, files, globals) => {
1484
1537
  // Without any installed wrapper declarations, no identifier can authenticate
1485
1538
  // as Node's loader. Ordinary user functions need no wrapper-effect analysis.
1486
1539
  if (globals.size === 0)
@@ -1685,51 +1738,81 @@ export const createCommonJsRequireCensus = (checker, files, globals) => {
1685
1738
  }
1686
1739
  if (process.env['GEA_STAGE_TIMING'])
1687
1740
  process.stderr.write(`[census] ${JSON.stringify({ ...stats, requireWriters: requireWriters.size })}\n`);
1688
- const statusOf = (expression, seen = new Set()) => {
1689
- const node = unwrapExpression(expression);
1690
- if (!ts.isIdentifier(node))
1691
- return 'ordinary';
1692
- const identityAtNode = identity.classify(node);
1693
- if (identityAtNode.kind === 'provenance-failure')
1694
- return 'provenance-failure';
1695
- if (identityAtNode.kind === 'wrapper') {
1696
- if (identityAtNode.global !== 'require')
1697
- return 'ordinary';
1698
- // A module whose source never writes its wrapper `require` (see
1699
- // `requireWriters`) keeps Node's loader in that cell for its whole
1700
- // lifetime, so every read of it is static -- including reads the
1701
- // per-file flow never reaches (an exported function or a class method
1702
- // only other modules call, which get no entry state here) and reads it
1703
- // reaches as `unknown` only because an unresolved call *might* have been
1704
- // one of this file's writers. Sound because the cell is a parameter of
1705
- // this module's own wrapper function: no other module can name it, so
1706
- // the only possible writers are syntactic writes in this file, and
1707
- // `wrapperWrite` sees every one of them -- the first pass analyzes every
1708
- // function body and every top level from a reachable state, and records
1709
- // the writer before any reachability filter (a write the flow proves
1710
- // dead never runs). A `var require`/`function require` rebinding either
1711
- // is such a write or resolves the read to a user declaration, which is
1712
- // not the wrapper and never gets here; the non-syntactic aliases (direct
1713
- // `eval`, the wrapper's `arguments`) are `canAliasWrapperCells`.
1714
- if (!requireWriters.has(node.getSourceFile()))
1715
- return 'static';
1716
- const definitions = reads.get(node) ?? unreachable;
1717
- if (definitions === originalDefinition)
1718
- return 'static';
1719
- return definitions === unreachable ? 'ordinary' : 'possibly-reassigned';
1741
+ return { statusOf: requireStatusOf(checker, identity, requireWriters, reads) };
1742
+ };
1743
+ const sameGlobals = (left, right) => left === right || (left.size === right.size && [...left].every(([name, declaration]) => right.get(name) === declaration));
1744
+ /**
1745
+ * The census is a pure function of the checker, the program's file list and
1746
+ * the wrapper declarations, and the frontend asks it twice with exactly those
1747
+ * inputs (the module-record census and the invocation producer), 0.4 s a
1748
+ * time. The last answer per checker is kept so the second ask is the first's
1749
+ * instance -- same proof, so nothing downstream can see two.
1750
+ */
1751
+ const lastCensus = new WeakMap();
1752
+ export const createCommonJsRequireCensus = (checker, files, globals) => {
1753
+ const held = lastCensus.get(checker);
1754
+ if (held && held.files === files && sameGlobals(held.globals, globals))
1755
+ return held.census;
1756
+ const census = analyseCommonJsRequireCensus(checker, files, globals);
1757
+ lastCensus.set(checker, { files, globals, census });
1758
+ return census;
1759
+ };
1760
+ /**
1761
+ * Whether a file can name the wrapper's `require` cell as something to WRITE:
1762
+ * any identifier `require` that is not the callee of a call, the receiver or
1763
+ * member name of a property access, or a property name. Every write form (an
1764
+ * assignment or update, a destructuring target, a `var`/parameter/function
1765
+ * redeclaration, an import binding, a shorthand property) puts such an
1766
+ * identifier in a position outside those, so a file without one cannot write
1767
+ * the cell syntactically; `eval` and the wrapper's `arguments` are the
1768
+ * non-syntactic routes (`canAliasWrapperCells`).
1769
+ */
1770
+ const mayWriteRequireCell = (file) => {
1771
+ let found = false;
1772
+ const visit = (node) => {
1773
+ if (found)
1774
+ return;
1775
+ if (ts.isIdentifier(node)) {
1776
+ if (node.text !== 'require')
1777
+ return;
1778
+ const parent = node.parent;
1779
+ if (ts.isCallExpression(parent) && parent.expression === node)
1780
+ return;
1781
+ if ((ts.isPropertyAccessExpression(parent) || ts.isElementAccessExpression(parent)) && parent.expression === node)
1782
+ return;
1783
+ if (ts.isPropertyAccessExpression(parent) && parent.name === node)
1784
+ return;
1785
+ if ((ts.isPropertyAssignment(parent) ||
1786
+ ts.isPropertyDeclaration(parent) ||
1787
+ ts.isMethodDeclaration(parent) ||
1788
+ ts.isPropertySignature(parent) ||
1789
+ ts.isMethodSignature(parent)) &&
1790
+ parent.name === node)
1791
+ return;
1792
+ found = true;
1793
+ return;
1720
1794
  }
1721
- const symbol = resolvedSymbolAt(checker, node);
1722
- if (!symbol || seen.has(symbol))
1723
- return 'ordinary';
1724
- seen.add(symbol);
1725
- const declaration = symbol.valueDeclaration;
1726
- if (!declaration || !ts.isVariableDeclaration(declaration) || !declaration.initializer)
1727
- return 'ordinary';
1728
- if (!ts.isVariableDeclarationList(declaration.parent) || (declaration.parent.flags & ts.NodeFlags.Const) === 0)
1729
- return 'ordinary';
1730
- return statusOf(declaration.initializer, seen);
1795
+ ts.forEachChild(node, visit);
1731
1796
  };
1732
- return { statusOf };
1797
+ visit(file);
1798
+ return found;
1799
+ };
1800
+ /**
1801
+ * The census restricted to what a program that is about to be REBUILT needs:
1802
+ * which `require` calls are static. Valid only when no file can write the
1803
+ * wrapper cell, where the full census's answer is `static` for every read of
1804
+ * the wrapper (`requireStatusOf`) and its fact and summary passes compute
1805
+ * nothing anyone consults. Null otherwise -- the caller then asks the full
1806
+ * census. Never used for the program the compile keeps: the full census also
1807
+ * puts the checker in the state later queries (and so emitted names) depend on.
1808
+ */
1809
+ export const createCommonJsRequireTargetCensus = (checker, files, globals) => {
1810
+ if (globals.size === 0)
1811
+ return { statusOf: () => 'ordinary' };
1812
+ const implementationFiles = files.filter((file) => !file.isDeclarationFile);
1813
+ if (implementationFiles.some((file) => canAliasWrapperCells(file) || mayWriteRequireCell(file)))
1814
+ return null;
1815
+ return { statusOf: requireStatusOf(checker, createCommonJsWrapperIdentity(checker, files, globals), new Set(), new Map()) };
1733
1816
  };
1734
1817
  /**
1735
1818
  * The one admission the invocation producer applies before it lowers a call
@@ -175,18 +175,43 @@ export const createMutationKeyReader = (checker, computedKeysOf, publishedTypeAt
175
175
  */
176
176
  export const hostAccessorNamesOf = (declarationFiles, files) => {
177
177
  const names = new Set(['__proto__']);
178
- const visit = (node, ambientOnly) => {
179
- if (ts.isSetAccessorDeclaration(node) && (!ambientOnly || isAmbientDeclaration(node)) && !declarationStatesHostInert(node)) {
180
- const name = node.name;
181
- if (ts.isIdentifier(name) || ts.isStringLiteralLike(name) || ts.isNumericLiteral(name))
182
- names.add(name.text);
183
- }
184
- ts.forEachChild(node, (child) => visit(child, ambientOnly));
185
- };
186
178
  for (const file of declarationFiles)
187
- visit(file, false);
179
+ for (const name of setterNamesOf(file, false))
180
+ names.add(name);
188
181
  for (const file of files)
189
182
  if (!file.isDeclarationFile)
190
- visit(file, true);
183
+ for (const name of setterNamesOf(file, true))
184
+ names.add(name);
191
185
  return names;
192
186
  };
187
+ /**
188
+ * The names of the uncovered setters one file declares, in encounter order.
189
+ *
190
+ * A pure function of the tree -- `declarationStatesHostInert` reads only the
191
+ * declaration and its own JSDoc -- and a declaration file's tree is shared
192
+ * across compiles (`shared-declaration-files.ts`), so the whole-file walk is
193
+ * kept per file instead of repeated for the same standard library every compile.
194
+ */
195
+ const setterNames = new WeakMap();
196
+ const setterNamesOf = (file, ambientOnly) => {
197
+ const known = setterNames.get(file);
198
+ if (known !== undefined)
199
+ return ambientOnly ? known.ambient : known.any;
200
+ const any = [];
201
+ const ambient = [];
202
+ const visit = (node) => {
203
+ if (ts.isSetAccessorDeclaration(node) && !declarationStatesHostInert(node)) {
204
+ const name = node.name;
205
+ if (ts.isIdentifier(name) || ts.isStringLiteralLike(name) || ts.isNumericLiteral(name)) {
206
+ any.push(name.text);
207
+ if (isAmbientDeclaration(node))
208
+ ambient.push(name.text);
209
+ }
210
+ }
211
+ ts.forEachChild(node, visit);
212
+ };
213
+ visit(file);
214
+ const held = { any, ambient };
215
+ setterNames.set(file, held);
216
+ return ambientOnly ? held.ambient : held.any;
217
+ };
@@ -35,6 +35,21 @@ export const specializationKey = (path) => path.map((step) => step.ordinal).join
35
35
  * order and visits each node's tags in source order.
36
36
  */
37
37
  const walkOrdinals = (file) => {
38
+ const known = ordinalWalks.get(file);
39
+ if (known !== undefined)
40
+ return known;
41
+ const walked = computeOrdinals(file);
42
+ ordinalWalks.set(file, walked);
43
+ return walked;
44
+ };
45
+ /**
46
+ * The walk is a pure function of the tree, and a declaration file's tree is
47
+ * shared across compiles (`shared-declaration-files.ts`), so its walk is kept
48
+ * with it -- weakly, so a source file's walk dies with the file. The returned
49
+ * map is only ever read.
50
+ */
51
+ const ordinalWalks = new WeakMap();
52
+ const computeOrdinals = (file) => {
38
53
  const ordinals = new Map();
39
54
  let next = 0;
40
55
  const assign = (node) => {
@@ -1238,7 +1238,17 @@ export const bagShapeTypeAt = (table, typeOf, bags, node) => {
1238
1238
  // is not a new rule, it is the same rule reaching the node that stands for
1239
1239
  // the same value.
1240
1240
  const assignment = ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken ? node : null;
1241
- const asked = ts.isExpression(node) ? node : ts.isVariableDeclaration(node) ? node.initializer : undefined;
1241
+ // A literal's member `targets: {}` is the same: the enclosing record's field
1242
+ // is asked with the `PropertyAssignment`, every `state.targets[ k ]` with an
1243
+ // expression. Answering only the reads left the field at the checker's `{}`,
1244
+ // so each access recast it into the bag's layout -- a fresh COPY -- and
1245
+ // three's `transmissionRenderTarget[ camera.id ] = target` wrote into a
1246
+ // temporary the next read never saw.
1247
+ const asked = ts.isExpression(node)
1248
+ ? node
1249
+ : ts.isVariableDeclaration(node) || ts.isPropertyAssignment(node)
1250
+ ? node.initializer
1251
+ : undefined;
1242
1252
  const optional = bagSlotTypeOf(typeOf, bags);
1243
1253
  // A cell whose bag arrives by assignment rather than by its initializer --
1244
1254
  // see `shapeForOwner`. Asked only after the initializer, so a declaration
@@ -1252,7 +1262,11 @@ export const bagShapeTypeAt = (table, typeOf, bags, node) => {
1252
1262
  // carriers. `shapeForOwner` is identity-keyed and returns nothing for an
1253
1263
  // ordinary assignment to an existing variable, so this admits only the
1254
1264
  // checker-proven JS-field form rather than guessing from assignment syntax.
1255
- const owned = ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isParameter(node) || assignment !== null
1265
+ const owned = ts.isVariableDeclaration(node) ||
1266
+ ts.isPropertyDeclaration(node) ||
1267
+ ts.isPropertyAssignment(node) ||
1268
+ ts.isParameter(node) ||
1269
+ assignment !== null
1256
1270
  ? bags.shapeForOwner(node)
1257
1271
  : null;
1258
1272
  if (asked === undefined)
@@ -42,7 +42,7 @@ export type OmittedStatedParameterAnswer = {
42
42
  export declare const omissionStatedTypeOf: (checker: ts.TypeChecker, parameter: ts.ParameterDeclaration) => ts.Type | null;
43
43
  /**
44
44
  * `stated | undefined` when some caller in the (already closed) caller set
45
- * omits the argument at `index`.
45
+ * omits the argument at `index`, or passes one that can itself be `undefined`.
46
46
  *
47
47
  * `null` when no caller provably omits it -- every caller passes it, or there
48
48
  * is no attributed caller at all -- so the statement stands as written and