@geastack/compiler 1.0.63 → 1.0.65

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/dist/cli-emit.js +14 -5
  2. package/dist/conversion/dictionary-view.js +13 -2
  3. package/dist/conversion/document-record-view.d.ts +0 -1
  4. package/dist/conversion/document-record-view.js +30 -3
  5. package/dist/conversion/impossible-field-read.d.ts +9 -0
  6. package/dist/conversion/impossible-field-read.js +26 -0
  7. package/dist/conversion/nodes.d.ts +12 -0
  8. package/dist/conversion/nodes.js +106 -2
  9. package/dist/conversion/record-view.js +21 -0
  10. package/dist/ir/build.d.ts +5 -2
  11. package/dist/ir/build.js +9 -2
  12. package/dist/ir/callable-class-flow.js +233 -13
  13. package/dist/ir/certify/parallel-region.js +1 -0
  14. package/dist/ir/certify.js +32 -2
  15. package/dist/ir/hoist.js +15 -1
  16. package/dist/ir/host-template-conversions.js +12 -0
  17. package/dist/ir/lower-invocation.js +42 -2
  18. package/dist/ir/lower-property.js +2 -2
  19. package/dist/ir/model.d.ts +18 -6
  20. package/dist/ir/native-callable-data-reads.js +15 -2
  21. package/dist/ir/native-field-view-domains.d.ts +8 -0
  22. package/dist/ir/native-field-view-domains.js +44 -3
  23. package/dist/ir/native-field-view-facts.d.ts +2 -2
  24. package/dist/ir/native-field-view-facts.js +57 -13
  25. package/dist/ir/native-own-assignment.js +20 -2
  26. package/dist/ir/program-conversions.js +38 -7
  27. package/dist/ir/property-read-conversions.js +14 -5
  28. package/dist/ir/publish-native-field-view-facts.js +1 -1
  29. package/dist/ir/queries.js +2 -0
  30. package/dist/ir/read-only-dictionary.js +138 -15
  31. package/dist/ir/reflection-demand.js +7 -1
  32. package/dist/ir/shake.js +26 -6
  33. package/dist/ir/typed-property-access.d.ts +20 -0
  34. package/dist/ir/typed-property-access.js +56 -0
  35. package/dist/projection/bindings.js +14 -19
  36. package/dist/projection/fields.js +7 -1
  37. package/dist/projection/native-object-data.d.ts +8 -1
  38. package/dist/projection/native-object-data.js +16 -4
  39. package/dist/representation/derive.js +67 -1
  40. package/dist/representation/proxy-carriers.js +17 -2
  41. package/dist/representation/publish.js +34 -0
  42. package/dist/semantics/callable-own-data-slots.js +71 -6
  43. package/dist/semantics/model/operations.d.ts +15 -4
  44. package/dist/semantics/native-own-assignment.d.ts +3 -0
  45. package/dist/semantics/normalize/collection-bindings.js +2 -2
  46. package/dist/semantics/normalize/flow/array-element-continuation.d.ts +1 -1
  47. package/dist/semantics/normalize/flow/array-element-continuation.js +32 -9
  48. package/dist/semantics/normalize/flow/callable-reach.d.ts +3 -5
  49. package/dist/semantics/normalize/flow/callable-reach.js +3 -5
  50. package/dist/semantics/normalize/flow/component-solver.d.ts +2 -0
  51. package/dist/semantics/normalize/flow/component-solver.js +32 -6
  52. package/dist/semantics/normalize/flow/computed-key-set.js +53 -1
  53. package/dist/semantics/normalize/flow/source-value-session.js +16 -14
  54. package/dist/semantics/normalize/producers/invocations.js +40 -1
  55. package/dist/semantics/normalize/producers/native-own-assignment.js +12 -4
  56. package/dist/semantics/normalize/reachability.js +18 -8
  57. package/dist/semantics/normalize/structural-mutable-field.d.ts +1 -0
  58. package/dist/semantics/normalize/structural-mutable-field.js +170 -4
  59. package/dist/semantics/normalize/structural-parts.js +6 -1
  60. package/dist/semantics/normalize/structural-self-reference.d.ts +1 -1
  61. package/dist/semantics/normalize/structural-self-reference.js +9 -1
  62. package/dist/semantics/normalize/structural.js +10 -1
  63. package/dist/semantics/program.js +102 -1
  64. package/dist/targets/cpp/class-properties/emit-class-properties.js +9 -0
  65. package/dist/targets/cpp/emit-allocation.js +22 -1
  66. package/dist/targets/cpp/emit-bindings.js +5 -5
  67. package/dist/targets/cpp/emit-exceptions.js +6 -0
  68. package/dist/targets/cpp/emit-narrowing.js +24 -2
  69. package/dist/targets/cpp/emit-native-field-view.d.ts +1 -1
  70. package/dist/targets/cpp/emit-native-field-view.js +37 -5
  71. package/dist/targets/cpp/emit-native-own-assignment.js +5 -1
  72. package/dist/targets/cpp/emit-record-view.js +6 -1
  73. package/dist/targets/cpp/emit-tonumber.d.ts +22 -11
  74. package/dist/targets/cpp/emit-tonumber.js +86 -25
  75. package/dist/targets/cpp/emit.js +3 -0
  76. package/dist/targets/cpp/host/emit-host-invoke.js +6 -6
  77. package/dist/targets/cpp/prototype/emit-prototype-array.js +13 -1
  78. package/dist/targets/cpp/records.js +15 -7
  79. package/dist/targets/cpp/recursive-containers.js +5 -1
  80. package/dist/targets/cpp/translation-unit.js +17 -2
  81. package/package.json +4 -2
  82. package/src/targets/cpp/runtime/gea_runtime.h +212 -7
@@ -2189,27 +2189,25 @@ const createSession = (checker, flow) => {
2189
2189
  facts.add(held);
2190
2190
  return;
2191
2191
  }
2192
- let before = 0;
2192
+ let delta = values;
2193
2193
  if (!whole) {
2194
2194
  let through = addedThrough.get(query);
2195
2195
  if (through === undefined)
2196
2196
  addedThrough.set(query, (through = new Map()));
2197
- before = through.get(values) ?? 0;
2197
+ const before = through.get(values) ?? 0;
2198
2198
  const size = values.size;
2199
2199
  if (before === size)
2200
2200
  return;
2201
2201
  through.set(values, size);
2202
+ if (before !== 0)
2203
+ delta = values.factsFrom(before);
2202
2204
  }
2203
- let at = 0;
2204
2205
  if (gating === null) {
2205
- for (const held of values)
2206
- if (at++ >= before)
2207
- facts.add(held);
2206
+ for (const held of delta)
2207
+ facts.add(held);
2208
2208
  return;
2209
2209
  }
2210
- for (const held of values) {
2211
- if (at++ < before)
2212
- continue;
2210
+ for (const held of delta) {
2213
2211
  if (held.kind === ts.SyntaxKind.OmittedExpression && gates.has(held)) {
2214
2212
  if (!gating.seen.has(held)) {
2215
2213
  gating.seen.add(held);
@@ -4960,10 +4958,8 @@ const createSession = (checker, flow) => {
4960
4958
  if (through === undefined)
4961
4959
  addedThrough.set(query, (through = new Map()));
4962
4960
  const before = through.get(held) ?? 0;
4963
- let at = 0;
4964
- for (const value of held)
4965
- if (at++ >= before)
4966
- facts.add(value);
4961
+ for (const value of before === 0 ? held : held.factsFrom(before))
4962
+ facts.add(value);
4967
4963
  through.set(held, size);
4968
4964
  }
4969
4965
  return facts;
@@ -5255,6 +5251,12 @@ const createSession = (checker, flow) => {
5255
5251
  // literal held in an `any` position was handed to dynamic code as a
5256
5252
  // Document, and a typed read of it is a live view over those entries.
5257
5253
  const declared = new Set(keys);
5254
+ // A source typed with a string index of `any` entries types none of its
5255
+ // undeclared keys: whatever a held literal adds is one of those entries,
5256
+ // copied as its Value like every other run-time key.
5257
+ const anyEntries = checker
5258
+ .getIndexInfosOfType(checker.getTypeAtLocation(expression))
5259
+ .some((info) => (info.keyType.flags & ts.TypeFlags.String) !== 0 && (info.type.flags & ts.TypeFlags.Any) !== 0);
5258
5260
  for (const root of admitted(value(expression)) ?? []) {
5259
5261
  if (!ts.isObjectLiteralExpression(root))
5260
5262
  continue;
@@ -5262,7 +5264,7 @@ const createSession = (checker, flow) => {
5262
5264
  if (contextual !== undefined && (contextual.flags & ts.TypeFlags.Any) !== 0)
5263
5265
  continue;
5264
5266
  const owned = admitted(nodeQuery('own-keys', root));
5265
- if (owned === null || owned.some((key) => !ts.isStringLiteral(key) || !declared.has(key.text)))
5267
+ if (owned === null || owned.some((key) => !ts.isStringLiteral(key) || (!anyEntries && !declared.has(key.text))))
5266
5268
  return null;
5267
5269
  const writes = admitted(nodeQuery('closure', root));
5268
5270
  if (writes === null || writes.some((write) => ts.isCallExpression(write) && definitionPlans.has(write)))
@@ -1656,9 +1656,14 @@ export const createInvocationProducer = (context) => ({
1656
1656
  if (!targetFile || targetFile.isDeclarationFile) {
1657
1657
  return { kind: 'blocked', reason: `host builtin module "${builtinModule}" has no compiled runtime source record` };
1658
1658
  }
1659
+ const namespace = esModuleNamespaceOf(context.checker, context.identities, targetFile);
1659
1660
  return {
1660
1661
  kind: 'lookup',
1661
- value: { target: regionId(context.identities.nodeIdOf(targetFile), 'module-body'), builtinModule }
1662
+ value: {
1663
+ target: regionId(context.identities.nodeIdOf(targetFile), 'module-body'),
1664
+ builtinModule,
1665
+ ...(namespace === null ? {} : { namespace })
1666
+ }
1662
1667
  };
1663
1668
  })()
1664
1669
  : null;
@@ -2271,3 +2276,37 @@ const deadEventCallFactOf = (context, node) => {
2271
2276
  return { deadEventRegistration: true };
2272
2277
  return {};
2273
2278
  };
2279
+ /**
2280
+ * The export cells an ES-module builtin's namespace object reads. Node answers
2281
+ * `getBuiltinModule(id)` for such a module with its namespace -- what
2282
+ * `import * as m` binds -- never a CommonJS `module.exports`, which an ES
2283
+ * module does not populate. A namespace property is a live view of its
2284
+ * binding; a record filled once agrees with that view only when no export can
2285
+ * be reassigned, so a mutable export leaves the lookup on its dynamic path.
2286
+ */
2287
+ const esModuleNamespaceOf = (checker, identities, file) => {
2288
+ if (!ts.isExternalModule(file) || file.commonJsModuleIndicator)
2289
+ return null;
2290
+ const module = checker.getSymbolAtLocation(file);
2291
+ if (module === undefined)
2292
+ return null;
2293
+ const fields = [];
2294
+ for (const exported of checker.getExportsOfModule(module)) {
2295
+ const target = (exported.flags & ts.SymbolFlags.Alias) !== 0 ? checker.getAliasedSymbol(exported) : exported;
2296
+ if ((target.flags & ts.SymbolFlags.Value) === 0)
2297
+ continue;
2298
+ const declaration = target.valueDeclaration;
2299
+ if (declaration === undefined || declaration.getSourceFile().isDeclarationFile)
2300
+ return null;
2301
+ const immutable = ts.isFunctionDeclaration(declaration) ||
2302
+ ts.isClassDeclaration(declaration) ||
2303
+ (ts.isVariableDeclaration(declaration) &&
2304
+ ts.isIdentifier(declaration.name) &&
2305
+ ts.isVariableDeclarationList(declaration.parent) &&
2306
+ (declaration.parent.flags & ts.NodeFlags.Const) !== 0);
2307
+ if (!immutable)
2308
+ return null;
2309
+ fields.push({ key: ts.symbolName(exported), declaration: identities.declarationIdOf(declaration) });
2310
+ }
2311
+ return fields;
2312
+ };
@@ -7,7 +7,8 @@ const storedValueOf = (context, value) => {
7
7
  const absence = ts.isVoidExpression(value) && value.parent === undefined;
8
8
  return {
9
9
  type: absence ? context.table.intern({ kind: 'primitive', primitive: 'undefined' }) : context.types.typeAt(value),
10
- source: absence ? { kind: 'constant', text: 'undefined', literal: 'undefined' } : sourceForValue(context, value)
10
+ source: absence ? { kind: 'constant', text: 'undefined', literal: 'undefined' } : sourceForValue(context, value),
11
+ ...(absence ? { absence: true } : {})
11
12
  };
12
13
  }
13
14
  if ((ts.isFunctionDeclaration(value) || ts.isMethodDeclaration(value)) && value.body)
@@ -38,11 +39,15 @@ export const nativeOwnSlotOf = (context, expression, key) => {
38
39
  /** A source's own data keys, read from the structural type its
39
40
  * representation is laid out under -- the one key authority both the IR's
40
41
  * copy and the session's absence obligation range over. Nullish arms copy
41
- * nothing; any arm that is not a plain data record (an index, an accessor, a
42
- * symbol key, dropped callable members, a type parameter) bounds no key set.
42
+ * nothing; any arm that is not a plain data record (a typed index, an accessor,
43
+ * a symbol key, dropped callable members, a type parameter) bounds no key set.
43
44
  */
44
45
  const representedDataKeysOf = (context, expression) => {
45
46
  const keys = new Set();
47
+ const declaredAnyStringIndex = (index) => {
48
+ const value = context.table.get(index.value).shape;
49
+ return index.key === 'string' && value.kind === 'primitive' && value.primitive === 'any';
50
+ };
46
51
  const visit = (id, depth) => {
47
52
  if (depth > 16)
48
53
  return false;
@@ -58,7 +63,10 @@ const representedDataKeysOf = (context, expression) => {
58
63
  case 'intersection':
59
64
  return shape.resolved !== null && visit(shape.resolved, depth + 1);
60
65
  case 'object':
61
- if (shape.index.length !== 0 || shape.membersDropped)
66
+ // A string index of declared `any` entries owes no typed storage for
67
+ // any key: each run-time key it holds is copied as the Value it
68
+ // already is (the described source's open, unknown-key write).
69
+ if (shape.index.some((index) => !declaredAnyStringIndex(index)) || shape.membersDropped)
62
70
  return false;
63
71
  for (const member of shape.members) {
64
72
  if (member.accessor !== null || member.key.kind === 'symbol')
@@ -650,6 +650,12 @@ const evaluatesNothing = (file) => file.statements.every((statement) => {
650
650
  export const fileEvaluates = (reachable, file) => reachable.statementsOf(file).some((statement) => {
651
651
  if (ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement))
652
652
  return false;
653
+ // `export { a }` names bindings for importers and runs nothing, and
654
+ // `export {}` only marks the file a module. One that names a specifier is a
655
+ // module edge, which the evaluation order already accounts for, so none of
656
+ // them makes this file's own body run.
657
+ if (ts.isExportDeclaration(statement))
658
+ return false;
653
659
  if (ts.isClassDeclaration(statement) && reachable.classIsLayoutOnly(statement))
654
660
  return false;
655
661
  return !(ts.canHaveModifiers(statement) &&
@@ -796,19 +802,23 @@ export const censusReachability = (input) => {
796
802
  // parameters no call site ever
797
803
  // types -- a refusal inside a body no program reaches denied thousands of
798
804
  // cases their certificate.
799
- const whole = entries.has(file) && ts.isExternalModule(file);
805
+ //
806
+ // So it is the EXPORTS that keep a module whole, not the goal symbol: an
807
+ // entry module that exports nothing -- `export {}`, or only imports -- has
808
+ // the script's roots exactly, and keeping it whole only brings back its
809
+ // never-called helpers with their refusals.
810
+ const entryModule = entries.has(file) && ts.isExternalModule(file) ? input.checker.getSymbolAtLocation(file) : undefined;
811
+ const exports = entryModule ? input.checker.getExportsOfModule(entryModule) : [];
812
+ const whole = exports.length > 0;
800
813
  for (const statement of file.statements)
801
814
  if (whole || !isPrunableDeclaration(input.checker, statement))
802
815
  openStatement(statement);
803
816
  for (const target of moduleTargetsOf(input.checker, file, { verbatim: input.verbatimModuleSyntax === true }))
804
817
  fileQueue.push(target);
805
- if (entries.has(file) && ts.isExternalModule(file)) {
806
- const module = input.checker.getSymbolAtLocation(file);
807
- for (const exported of module ? input.checker.getExportsOfModule(module) : []) {
808
- const value = input.runtimeExportOf?.(file, exported.getName());
809
- if (value?.kind !== 'missing')
810
- markSymbol(value?.kind === 'binding' ? value.symbol : exported);
811
- }
818
+ for (const exported of exports) {
819
+ const value = input.runtimeExportOf?.(file, exported.getName());
820
+ if (value?.kind !== 'missing')
821
+ markSymbol(value?.kind === 'binding' ? value.symbol : exported);
812
822
  }
813
823
  };
814
824
  const spellKey = (text) => {
@@ -5,4 +5,5 @@ import type { ValueFlowIndex } from './flow/model.js';
5
5
  export declare const createMutableFieldResolver: (checker: ts.TypeChecker, table: StructuralTypeTable, flow: ValueFlowIndex | undefined, typeOf: (type: ts.Type) => StructuralTypeId, read: (node: ts.Node) => StructuralTypeId) => {
6
6
  readonly storageTypeOf: (symbol: ts.Symbol, stated: StructuralTypeId) => StructuralTypeId | null;
7
7
  readonly readTypeAt: (node: ts.Node) => StructuralTypeId | null;
8
+ readonly readerLayoutOf: (node: ts.ArrayLiteralExpression) => StructuralTypeId | null;
8
9
  };
@@ -17,6 +17,7 @@ const openType = (checker, type) => (type.flags & (ts.TypeFlags.Any | ts.TypeFla
17
17
  (type.isUnionOrIntersection() && type.types.some((member) => openType(checker, member)));
18
18
  /** Actual alias writes size a native data slot; a covariant public annotation does not. */
19
19
  const NO_WRITES = new Map();
20
+ const NO_VALUES = new Map();
20
21
  // Every structural copy builds its own resolver, and the alias writes it sizes
21
22
  // slots from are the program's, not the copy's: indexed per copy, the same
22
23
  // whole-program table was rebuilt and held once per copy.
@@ -26,6 +27,7 @@ const writesByKeyOf = (flow) => {
26
27
  if (known !== undefined)
27
28
  return known;
28
29
  const writes = new Map();
30
+ const values = new Map();
29
31
  for (const write of flow.allWrites) {
30
32
  const access = write.propertyAccess;
31
33
  if (!access || write.value === null)
@@ -37,13 +39,20 @@ const writesByKeyOf = (flow) => {
37
39
  if (!entries.includes(access))
38
40
  entries.push(access);
39
41
  writes.set(key, entries);
42
+ const written = values.get(access) ?? [];
43
+ if (!written.includes(write.value))
44
+ written.push(write.value);
45
+ values.set(access, written);
40
46
  }
41
- writesByKey.set(flow, writes);
42
- return writes;
47
+ const indexed = { byKey: writes, values };
48
+ writesByKey.set(flow, indexed);
49
+ return indexed;
43
50
  };
44
51
  export const createMutableFieldResolver = (checker, table, flow, typeOf, read) => {
45
52
  const session = flow && sourceValueSessionOf(checker, flow);
46
- const writes = flow === undefined ? NO_WRITES : writesByKeyOf(flow);
53
+ const indexed = flow === undefined ? undefined : writesByKeyOf(flow);
54
+ const writes = indexed?.byKey ?? NO_WRITES;
55
+ const writtenValues = indexed?.values ?? NO_VALUES;
47
56
  const pending = new Set();
48
57
  const cache = new Map();
49
58
  const join = (values) => {
@@ -61,10 +70,129 @@ export const createMutableFieldResolver = (checker, table, flow, typeOf, read) =
61
70
  values.forEach(include);
62
71
  return members.size === 1 ? [...members][0] : table.intern({ kind: 'union', members: [...members] });
63
72
  };
73
+ // Every access that names a key, indexed once: the readers an uncontextual
74
+ // array literal's slot is checked against below.
75
+ let accessesByKey;
76
+ const accessesOf = (key) => {
77
+ if (accessesByKey === undefined) {
78
+ accessesByKey = new Map();
79
+ for (const access of flow?.propertyAccesses ?? []) {
80
+ const accessKey = keyOf(access);
81
+ if (accessKey === null)
82
+ continue;
83
+ const entries = accessesByKey.get(accessKey) ?? [];
84
+ entries.push(access);
85
+ accessesByKey.set(accessKey, entries);
86
+ }
87
+ }
88
+ return accessesByKey.get(key) ?? [];
89
+ };
90
+ const readerLayouts = new Map();
91
+ /**
92
+ * The array type a fresh array literal is laid out at when it fills a slot
93
+ * of an object literal nothing gives a contextual type, and every read of
94
+ * that slot states one wider array type the literal is assignable to.
95
+ *
96
+ * `Object.assign({ relaxed: true }, options, { seenObjects: [{ propertyName:
97
+ * '(root)', obj: null }] })` handed to a parameter typed
98
+ * `{ seenObjects: { obj: unknown; propertyName: string }[] }` is the shape.
99
+ * The assign source has no contextual type, so the checker types the array
100
+ * `{ propertyName: string; obj: null }[]`, while every function that reads
101
+ * the slot reads `{ obj: unknown; ... }[]` and pushes such entries into it.
102
+ * Two element layouts for one array have no conversion between them: an
103
+ * array is shared storage, and a copy would drop the reader's pushes. The
104
+ * literal is fresh, so no other name holds it at its own narrower type, and
105
+ * the readers' type IS the array the program uses. Laid out there, the
106
+ * literal and its slot agree with every reader.
107
+ *
108
+ * Every reader whose receiver reaches this literal through the source
109
+ * session must agree on one array type; disagreeing readers, a reader at the
110
+ * literal's own type, or a reader whose element is open at the top, keep
111
+ * the literal's own type.
112
+ */
113
+ const readerLayoutOf = (node) => {
114
+ if (!session || node.elements.length === 0)
115
+ return null;
116
+ if (readerLayouts.has(node))
117
+ return readerLayouts.get(node);
118
+ readerLayouts.set(node, null);
119
+ let arm = node;
120
+ while (arm.parent && ts.isParenthesizedExpression(arm.parent))
121
+ arm = arm.parent;
122
+ const property = arm.parent;
123
+ if (!property || !ts.isPropertyAssignment(property) || property.initializer !== arm || !ts.isObjectLiteralExpression(property.parent))
124
+ return null;
125
+ const key = ts.isIdentifier(property.name) || ts.isStringLiteral(property.name) ? property.name.text : null;
126
+ if (key === null)
127
+ return null;
128
+ const own = checker.getTypeAtLocation(node);
129
+ if (!checker.isArrayType(own) || openType(checker, own))
130
+ return null;
131
+ const ownId = typeOf(own);
132
+ // A generic parameter's inference (`Object.assign`'s `U`) hands the
133
+ // literal its own type back as its context: that states nothing.
134
+ const contextual = checker.getContextualType(node);
135
+ if (contextual !== undefined && !openType(checker, contextual) && typeOf(contextual) !== ownId)
136
+ return null;
137
+ let chosen = null;
138
+ for (const access of accessesOf(key)) {
139
+ const roots = session.valuesOf(access.expression);
140
+ // A receiver the session cannot attribute (a parameter fed an
141
+ // `Object.assign` result) is a reader of this slot whenever its type
142
+ // admits the literal, exactly as `storageTypeOf` treats such a write,
143
+ // or when the member it reads IS this property (the assign result
144
+ // itself, whose type carries the source literal's declaration).
145
+ const receiver = roots === null ? checker.getTypeAtLocation(access.expression) : null;
146
+ const member = receiver === null ? undefined : checker.getPropertyOfType(receiver, key);
147
+ const reaches = receiver !== null
148
+ ? !openType(checker, receiver) &&
149
+ member !== undefined &&
150
+ ((member.declarations ?? []).includes(property) ||
151
+ checker.isTypeAssignableTo(checker.getTypeAtLocation(property.parent), receiver))
152
+ : roots.some((root) => {
153
+ if (!ts.isObjectLiteralExpression(root) && !ts.isCallExpression(root) && !ts.isNewExpression(root))
154
+ return false;
155
+ const values = session.memberValuesOf(root, key);
156
+ return values !== null && values.some((value) => value === node || value === arm);
157
+ });
158
+ if (!reaches)
159
+ continue;
160
+ const readType = checker.getNonNullableType(checker.getTypeAtLocation(access));
161
+ const [element] = checker.isArrayType(readType) ? checker.getTypeArguments(readType) : [];
162
+ // An unattributed reader that states no closed array (`any`, an open
163
+ // element) names no layout; only an attributed one vetoes.
164
+ if (element === undefined || openType(checker, element)) {
165
+ if (receiver !== null)
166
+ continue;
167
+ return null;
168
+ }
169
+ const readId = typeOf(readType);
170
+ // A read at the literal's own narrower type would see the readers'
171
+ // stores through a view that claims they cannot exist (`obj: null`
172
+ // holding 7): no layout serves both, so the slot keeps refusing.
173
+ if (readId === ownId)
174
+ return null;
175
+ if (!checker.isTypeAssignableTo(own, readType))
176
+ return null;
177
+ if (chosen !== null && chosen !== readId)
178
+ return null;
179
+ chosen = readId;
180
+ }
181
+ readerLayouts.set(node, chosen);
182
+ return chosen;
183
+ };
64
184
  const storageTypeOf = (symbol, stated) => {
65
185
  const declaration = dataDeclarationOf(symbol);
66
186
  if (!session || !declaration || pending.has(declaration))
67
187
  return null;
188
+ if (ts.isPropertyAssignment(declaration)) {
189
+ let initializer = declaration.initializer;
190
+ while (ts.isParenthesizedExpression(initializer))
191
+ initializer = initializer.expression;
192
+ const readers = ts.isArrayLiteralExpression(initializer) ? readerLayoutOf(initializer) : null;
193
+ if (readers !== null && typeOf(checker.getTypeAtLocation(initializer)) === stated)
194
+ return readers;
195
+ }
68
196
  const known = cache.get(declaration);
69
197
  if (known?.has(stated))
70
198
  return known.get(stated) ?? null;
@@ -76,10 +204,47 @@ export const createMutableFieldResolver = (checker, table, flow, typeOf, read) =
76
204
  try {
77
205
  const extra = new Set();
78
206
  const roots = new Map();
207
+ // An object literal's own slot is sized from its own initializer, so a
208
+ // write the session cannot attribute (its receiver is a parameter fed
209
+ // from callers the session does not enumerate) must still reach every
210
+ // literal that receiver's type admits: JavaScript stores the value in
211
+ // that literal's slot when the literal is what arrives. A receiver typed
212
+ // `any` or `unknown` admits everything and states nothing; its stores
213
+ // take the dynamic protocol instead.
214
+ const literal = ts.isObjectLiteralExpression(declaration.parent) ? declaration.parent : null;
215
+ const literalMember = literal === null ? undefined : checker.getPropertyOfType(checker.getTypeAtLocation(literal), key);
216
+ const literalFloor = literal === null || literalMember === undefined || dataDeclarationOf(literalMember) !== declaration
217
+ ? null
218
+ : checker.getTypeOfSymbolAtLocation(literalMember, literal);
219
+ const unattributed = literal !== null && literalFloor !== null && !openType(checker, literalFloor) && typeOf(literalFloor) === stated ? literal : null;
79
220
  for (const access of candidates) {
80
221
  const origins = session.valuesOf(access.expression);
81
- if (origins === null)
222
+ if (origins === null) {
223
+ if (unattributed === null)
224
+ continue;
225
+ const receiver = checker.getTypeAtLocation(access.expression);
226
+ if (openType(checker, receiver) || !checker.isTypeAssignableTo(checker.getTypeAtLocation(unattributed), receiver))
227
+ continue;
228
+ // An open value joins only a slot its receiver itself declares
229
+ // `any`/`unknown` (`seenObjects[i].obj = value` into `obj: unknown`);
230
+ // anywhere else it would box a typed slot, so the slot keeps refusing.
231
+ // A receiver that reaches the key only through an index signature
232
+ // (`log: Record<string, any>`) admits every literal and names none of
233
+ // them, exactly like `any`: it is no evidence about this literal.
234
+ const declaredMember = checker.getPropertyOfType(receiver, key);
235
+ if (declaredMember === undefined)
236
+ continue;
237
+ const declared = checker.getTypeOfSymbolAtLocation(declaredMember, access);
238
+ const declaredOpen = (declared.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) !== 0;
239
+ for (const value of writtenValues.get(access) ?? []) {
240
+ const actual = checker.getTypeAtLocation(value);
241
+ if (openType(checker, actual) && !declaredOpen)
242
+ return null;
243
+ if (!checker.isTypeAssignableTo(actual, literalFloor))
244
+ extra.add(read(value));
245
+ }
82
246
  continue;
247
+ }
83
248
  for (const root of origins) {
84
249
  if (!ts.isNewExpression(root) && !ts.isObjectLiteralExpression(root))
85
250
  continue;
@@ -125,6 +290,7 @@ export const createMutableFieldResolver = (checker, table, flow, typeOf, read) =
125
290
  };
126
291
  return {
127
292
  storageTypeOf,
293
+ readerLayoutOf,
128
294
  readTypeAt: (node) => {
129
295
  if (!session || (!ts.isPropertyAccessExpression(node) && !ts.isElementAccessExpression(node)))
130
296
  return null;
@@ -612,7 +612,12 @@ export const createStructuralParts = (input) => {
612
612
  // checker answer that IS usable is never second-guessed here, the same
613
613
  // discipline `parameter-bindings.ts`'s own `known()` keeps for a bound
614
614
  // parameter's narrowed use.
615
- const censusNode = declaration ? (censusValueNodeOf(declaration) ?? declaration) : null;
615
+ // A function or class declaration declares a callable VALUE, not a cell: the censuses key such a node by its signature, and their answer
616
+ // there is the narrowed RESULT (`return-bindings.ts`'s `statedTypeAt`),
617
+ // which as a member type would make `channel(): Channel<unknown, unknown>`
618
+ // a `Channel` field of the module namespace that exports it.
619
+ const callableDeclaration = declaration !== null && (ts.isFunctionDeclaration(declaration) || ts.isClassDeclaration(declaration));
620
+ const censusNode = declaration && !callableDeclaration ? (censusValueNodeOf(declaration) ?? declaration) : null;
616
621
  // `object` and `{}` are upper bounds too. For `{ fields: payload }`,
617
622
  // a closed parameter census can know payload's concrete record even
618
623
  // though the checker retains its vacuous annotation. Storage must use
@@ -148,4 +148,4 @@ export declare const createAliasRecurrence: <T>(checker: ts.TypeChecker) => Alia
148
148
  * minted one `State[]` per copy -- five ids for one array -- and a callable
149
149
  * read out of one copy's cell could not enter another's slot.
150
150
  */
151
- export declare const createViewIndependentRecurrence: (checker: ts.TypeChecker) => ((type: ts.Type) => string | null);
151
+ export declare const createViewIndependentRecurrence: (checker: ts.TypeChecker, storageOf?: (type: ts.Type) => ts.Type) => ((type: ts.Type) => string | null);
@@ -422,7 +422,7 @@ const mentionsTypeParameter = (type) => {
422
422
  * minted one `State[]` per copy -- five ids for one array -- and a callable
423
423
  * read out of one copy's cell could not enter another's slot.
424
424
  */
425
- export const createViewIndependentRecurrence = (checker) => {
425
+ export const createViewIndependentRecurrence = (checker, storageOf = (type) => type) => {
426
426
  const keys = new Map();
427
427
  // A signature written as a TYPE (`(x: T) => T` in an alias, an interface
428
428
  // method) binds its own parameters; only a declaration with a body, or a
@@ -444,6 +444,14 @@ export const createViewIndependentRecurrence = (checker) => {
444
444
  if (seen.size >= budget)
445
445
  return true;
446
446
  seen.add(type);
447
+ // A type laid out as another (`record-link-families.ts`) walks as that
448
+ // other one, so the view reaches whatever the storage mentions: a plain
449
+ // `EmptyNode` stores as `ListNode<T>` at the enclosing class's `T`, and a
450
+ // cycle through it closed at one shared anchor handed every copy of the
451
+ // class the first copy's node layout.
452
+ const stored = storageOf(type);
453
+ if (stored !== type && viewDependent(stored, seen))
454
+ return true;
447
455
  if ((type.flags & ts.TypeFlags.TypeParameter) !== 0) {
448
456
  const owner = type.getSymbol()?.declarations?.[0]?.parent;
449
457
  return owner !== undefined && viewBinds(owner);
@@ -122,7 +122,7 @@ export const createStructuralMapper = (checker, identities, table, instantiation
122
122
  // asks the same question.
123
123
  const instantiatedMembersFor = createInstantiatedMembers(checker, specializations);
124
124
  // And one recurrence key for every view-independent cycle, for the same reason.
125
- const viewIndependentKeyOf = createViewIndependentRecurrence(checker);
125
+ const viewIndependentKeyOf = createViewIndependentRecurrence(checker, (type) => linkFamilies.storageOf(type));
126
126
  // The ids those cycles settled on, for every view: a view that enters the
127
127
  // same cycle at another member (`State` where the first entered at
128
128
  // `State[]`) closes it through these instead of interning a second copy.
@@ -1201,6 +1201,15 @@ const structuralRules = [
1201
1201
  // one other place a type enters from a source position: a binding whose
1202
1202
  // whole declared type is an absent host class, rather than one arm of a
1203
1203
  // union of them.
1204
+ // See `readerLayoutOf` in `structural-mutable-field.ts`: the slot it
1205
+ // fills is laid out at the same type.
1206
+ name: 'array-literal-reader-layout',
1207
+ forms: [ts.SyntaxKind.ArrayLiteralExpression],
1208
+ resolve(node) {
1209
+ return ts.isArrayLiteralExpression(node) ? this.mutableFields.readerLayoutOf(node) : null;
1210
+ }
1211
+ },
1212
+ {
1204
1213
  name: 'array-literal-implied-pattern',
1205
1214
  forms: [ts.SyntaxKind.ArrayLiteralExpression],
1206
1215
  resolve(node) {
@@ -249,6 +249,107 @@ const awaitsAtTopLevel = (file) => {
249
249
  * decide it.
250
250
  */
251
251
  const moduleMarkerForTopLevelAwait = (file) => !file.isDeclarationFile && !ts.isExternalModule(file) && awaitsAtTopLevel(file) ? `${file.text}\nexport {}\n` : null;
252
+ /** Names through which a program reaches the global object, or evaluates text against it. */
253
+ const globalObjectNames = new Set(['globalThis', 'window', 'self', 'global', 'eval', 'Function']);
254
+ /** Whether `node` is the name a property or member is spelled with, rather than a reference. */
255
+ const isMemberName = (node, parent) => (ts.isPropertyAccessExpression(parent) && parent.name === node) ||
256
+ ((ts.isPropertyAssignment(parent) ||
257
+ ts.isPropertyDeclaration(parent) ||
258
+ ts.isMethodDeclaration(parent) ||
259
+ ts.isAccessor(parent) ||
260
+ ts.isEnumMember(parent)) &&
261
+ parent.name === node);
262
+ /**
263
+ * Whether a classic script could tell that it is not running as one.
264
+ *
265
+ * A classic script and a module differ in what reaches the global object:
266
+ * the script's top-level `var` and function declarations are properties of
267
+ * it, and its top-level `this` IS it. Every other difference the checker
268
+ * already reports once the file is a module -- a global interface merge stops
269
+ * merging, a typed `globalThis.name` read stops resolving -- so it cannot
270
+ * change a program silently. What it cannot see is an untyped read: `(globalThis
271
+ * as any).name`, `window[key]`, a top-level `this.name`, or text handed to
272
+ * `eval`/`Function` that names a global. Each needs one of the names above or a
273
+ * top-level `this`, so their absence from the parse tree is the guarantee.
274
+ *
275
+ * A top-level `declare` counts as well, and is not a type: in a classic script
276
+ * `declare function f(): void` says the HOST defines a global `f`, and the
277
+ * call links against it; in a module the same text declares a module-local
278
+ * binding nothing defines, and the call is a ReferenceError.
279
+ *
280
+ * Over-approximate on purpose: a local `const self = this` counts too. Missing
281
+ * a reference would miscompile; counting a harmless one only keeps the file a
282
+ * classic script, which is what it was.
283
+ */
284
+ const observesGlobalObject = (file) => {
285
+ // The parent is carried rather than read off `node.parent`: a host may parse
286
+ // without parent pointers, and this runs inside the host.
287
+ const visit = (node, parent, thisIsGlobal) => {
288
+ if (node.kind === ts.SyntaxKind.ThisKeyword)
289
+ return thisIsGlobal;
290
+ if (ts.isIdentifier(node))
291
+ return globalObjectNames.has(node.text) && !isMemberName(node, parent);
292
+ // A type is erased, so `typeof globalThis` observes nothing -- but a class
293
+ // heritage clause's expression is evaluated, and it is a type node too.
294
+ if (ts.isTypeNode(node) && !ts.isExpressionWithTypeArguments(node))
295
+ return false;
296
+ // A non-arrow function, a field initializer and a static block bind `this`
297
+ // themselves; their computed NAME is still evaluated in the outer scope.
298
+ const bindsThis = (ts.isFunctionLike(node) && !ts.isArrowFunction(node)) || ts.isPropertyDeclaration(node) || ts.isClassStaticBlockDeclaration(node);
299
+ const name = node.name;
300
+ return ts.forEachChild(node, (child) => visit(child, node, child === name ? thisIsGlobal : thisIsGlobal && !bindsThis)) ?? false;
301
+ };
302
+ const declaresGlobal = (statement) => ts.canHaveModifiers(statement) &&
303
+ (ts.getModifiers(statement)?.some((modifier) => modifier.kind === ts.SyntaxKind.DeclareKeyword) ?? false);
304
+ return file.statements.some(declaresGlobal) || (ts.forEachChild(file, (child) => visit(child, file, true)) ?? false);
305
+ };
306
+ /**
307
+ * Whether `file` is an AMBIGUOUS ENTRY POINT: the one root of a compilation
308
+ * that has no project, written in TypeScript, with neither an import nor an
309
+ * export to state its goal symbol.
310
+ *
311
+ * "Ambiguous" in the sense Babel's `sourceType: "unambiguous"` and Node's
312
+ * syntax detection use: its grammar is valid under both of ECMA-262's goals,
313
+ * so the host chooses. A project chooses for its files (`moduleDetection`), so
314
+ * a program with one is left to it. JavaScript is excluded: a `.js` root is a
315
+ * generated bundle (`cli-emit.ts`), written for classic-script scope.
316
+ */
317
+ const isAmbiguousEntry = (file, input) => !input.projectFileName &&
318
+ input.rootFileNames.length === 1 &&
319
+ resolve(file.fileName) === resolve(input.rootFileNames[0]) &&
320
+ /\.[cm]?tsx?$/.test(file.fileName) &&
321
+ !file.isDeclarationFile &&
322
+ !ts.isExternalModule(file);
323
+ /**
324
+ * AN AMBIGUOUS ENTRY POINT TAKES THE MODULE GOAL.
325
+ *
326
+ * A classic script shares one lexical scope with every other classic script in
327
+ * its realm, which is the only thing script scope is for. An entry point
328
+ * compiled alone has no other: nothing can read its top-level bindings, so the
329
+ * script goal buys it nothing -- except collisions with every global the host's
330
+ * declarations name. `class Node {}` in such a file is TS2300 against
331
+ * `lib.dom.d.ts`'s `Node`, and every use of it then resolves to the DOM's; the
332
+ * same file as a module is an ordinary program. Deno gives every file the
333
+ * module goal for this reason, and TypeScript's `moduleDetection: "force"` does
334
+ * the same per project.
335
+ *
336
+ * Unlike `moduleMarkerForTopLevelAwait`, this does fire on programs that
337
+ * compiled, so the argument is not "TypeScript refused it" but that the goal is
338
+ * unobservable:
339
+ *
340
+ * - Strictness does not move. No project means `defaultCompilerOptions`, whose
341
+ * `strict` implies `alwaysStrict`, so the script was already strict code.
342
+ * - Anything that relied on the global namespace and is TYPED becomes a checker
343
+ * error, never a different program.
344
+ * - Anything untyped needs the global object by name or a top-level `this`,
345
+ * which `observesGlobalObject` keeps a classic script.
346
+ *
347
+ * `export {}`, appended, for the same reason as its sibling: every later stage
348
+ * then sees an ordinary module. One that exports nothing, which reachability
349
+ * (`normalize/reachability.ts`) prunes exactly as it prunes a script, so the
350
+ * never-called helpers of a program that compiled before still do not count.
351
+ */
352
+ const moduleGoalForAmbiguousEntry = (file, input) => isAmbiguousEntry(file, input) && !observesGlobalObject(file) ? `${file.text}\nexport {}\n` : null;
252
353
  /**
253
354
  * The compiler host, with the installed plugins' source transforms -- and the
254
355
  * `.json`-module rewrite above, which every compilation gets regardless of
@@ -540,7 +641,7 @@ const transformingHost = (input, options, resolutionDiagnostics, preparedSourceT
540
641
  // the file a module, and can equally introduce the top-level `await` that
541
642
  // asks for one. Either way the question is about the text this program
542
643
  // actually compiles.
543
- const marked = moduleMarkerForTopLevelAwait(transformedFile);
644
+ const marked = moduleMarkerForTopLevelAwait(transformedFile) ?? moduleGoalForAmbiguousEntry(transformedFile, input);
544
645
  if (marked === null)
545
646
  return transformedFile;
546
647
  return ts.createSourceFile(fileName, marked, languageVersionOrOptions, true, scriptKindOf(fileName));