@geastack/compiler 1.0.47 → 1.0.49

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.
@@ -237,5 +237,5 @@ export interface CompilationResult {
237
237
  */
238
238
  readonly generatedSupportIncludes: readonly string[];
239
239
  }
240
- export declare const sourceTransformsFor: (plugins: readonly PluginInstance[]) => readonly SourceTransform[];
240
+ export declare const sourceTransformsFor: (plugins: readonly PluginInstance[], rootFileNames: readonly string[]) => readonly SourceTransform[];
241
241
  export declare const compile: (request: CompilationRequest) => CompilationResult;
package/dist/compiler.js CHANGED
@@ -130,7 +130,7 @@ const declarerReaderFor = (plugins) => {
130
130
  return text;
131
131
  };
132
132
  };
133
- export const sourceTransformsFor = (plugins) => [
133
+ export const sourceTransformsFor = (plugins, rootFileNames) => [
134
134
  // A pre-class constructor function and its `F.prototype.m = function` methods
135
135
  // become the class they are, before anything below reads either as a class.
136
136
  constructorFunctionClassSourceTransform,
@@ -181,8 +181,9 @@ export const sourceTransformsFor = (plugins) => [
181
181
  // left exactly as written -- so it speaks only where the program was silent.
182
182
  declarationOverlayTransform,
183
183
  // The subclass overlay runs on the overlay's output and before the ambient
184
- // realization, so a member it declares is respelled too.
185
- createSubclassMemberOverlayTransform(declarerReaderFor(plugins)),
184
+ // realization, so a member it declares is respelled too. It is given the
185
+ // program's roots so what it reads is this program's own module graph.
186
+ createSubclassMemberOverlayTransform(declarerReaderFor(plugins), rootFileNames),
186
187
  // The alias-this field declaration runs after the subclass overlay so its
187
188
  // "already declared" check sees any member the overlay just added, and
188
189
  // never fights it over the same name. It states no type -- only that a
@@ -345,7 +346,7 @@ export const compile = (request) => {
345
346
  // offered to two plugins is offered to the second the way the first left
346
347
  // it. Only a plugin that installs one appears here, so a compilation whose
347
348
  // plugins state only data parses each file once past this first pass.
348
- sourceTransforms: sourceTransformsFor(plugins)
349
+ sourceTransforms: sourceTransformsFor(plugins, request.rootFileNames)
349
350
  });
350
351
  // The frontend's host-protocol census reaches the deriver as a policy rather
351
352
  // than as a table the deriver reads: `derive.ts` may not know what a JSX
@@ -861,6 +861,9 @@ staticCommonJsRequireOutcomeOf = () => null, trustSeed = initialCensusSeed) => {
861
861
  * intrinsic prototype the component had been merged with, `Map.prototype`
862
862
  * among them, for every `x` and `width` handed to a `readPixels`-style
863
863
  * native, and refused obligations no native could touch.
864
+ *
865
+ * An argument whose own type is primitive as well reaches nothing at all
866
+ * (`primitiveArgumentReachesNothing` below).
864
867
  */
865
868
  const NO_SCALAR_POSITIONS = new Map();
866
869
  const hostNativeScalarParametersOf = (call) => {
@@ -6926,8 +6929,26 @@ staticCommonJsRequireOutcomeOf = () => null, trustSeed = initialCensusSeed) => {
6926
6929
  const component = target ? factsByComponent.get(target) : undefined;
6927
6930
  // A scalar host parameter reaches what its primitive reaches, and
6928
6931
  // nothing else of the cell's component (`hostNativeScalarParametersOf`).
6932
+ //
6933
+ // A primitive argument reaches nothing at all. The wrapper chain is
6934
+ // `Object.prototype` and the `Object` constructor, stamped `every`
6935
+ // for each uncontracted native taking a `number`, which revoked
6936
+ // `Object.assign` and every absent-key read in the program over one
6937
+ // `bindBufferBase( target, index, buffer )`. A native that could
6938
+ // reach those realm intrinsics through a `double` could reach them
6939
+ // with no argument at all, and this stamp has never charged a
6940
+ // zero-argument native with anything: what a native does to the
6941
+ // realm on its own is its contract's business (`host-effect-contracts.ts`).
6942
+ // Only the argument's OWN type answers that: `define as unknown as
6943
+ // number` or an `any` cell may still hold an object, and keeps the
6944
+ // wrapper chain.
6929
6945
  const scalar = scalarParameters.get(position);
6930
- const reach = scalar === undefined ? null : primitivePrototypeReachOf(scalar, current);
6946
+ const primitiveArgumentReachesNothing = scalar !== undefined && primitiveResult(checker.getTypeAtLocation(current));
6947
+ const reach = scalar === undefined
6948
+ ? null
6949
+ : primitiveArgumentReachesNothing
6950
+ ? new Set()
6951
+ : primitivePrototypeReachOf(scalar, current);
6931
6952
  const facts = component === undefined || reach === null
6932
6953
  ? component
6933
6954
  : { ...component, prototypes: new Set([...component.prototypes].filter((declaration) => reach.has(declaration))) };
@@ -27,9 +27,10 @@ export type DeclarerReader = (filePath: string) => string;
27
27
  /**
28
28
  * The overlay, reading declarers through `read` -- see `DeclarerReader`.
29
29
  * `compiler.ts` builds one per compilation with that compilation's plugin
30
- * transforms; a caller with no plugins may pass `readFileSync` itself.
30
+ * transforms and root files; a caller with no plugins may pass `readFileSync`
31
+ * itself. Without `roots`, the file being transformed stands for the program.
31
32
  */
32
- export declare const createSubclassMemberOverlayTransform: (read: DeclarerReader) => (input: {
33
+ export declare const createSubclassMemberOverlayTransform: (read: DeclarerReader, roots?: readonly string[]) => (input: {
33
34
  readonly fileName: string;
34
35
  readonly text: string;
35
36
  }) => string | null;
@@ -271,6 +271,15 @@ const sourceFilesByRoot = new Map();
271
271
  * became a no-op for them. The fix is not to stop skipping `test` -- that
272
272
  * would re-admit a real package's own test fixtures into its class index --
273
273
  * it is to never skip an ancestor of the file actually being compiled.
274
+ *
275
+ * What such a directory is let in for is that program, not everything beside
276
+ * it: `test/runtime` holds some 1,600 independent programs, and indexing all
277
+ * of them as one package let a neighbour's class of the same name (dropped as
278
+ * a duplicate) or a neighbour's subclass (widening the union) change the
279
+ * overlay -- and the text, and every identity after it -- of a program that
280
+ * never mentions the neighbour. So the files found only through this override
281
+ * are `confined` (see `collectSourceFiles`) and indexed only when they belong
282
+ * to the compilation's own module graph (`programGraph`).
274
283
  */
275
284
  const ancestryBetween = (root, filePath) => {
276
285
  const stop = resolve(root);
@@ -300,14 +309,19 @@ const indexKey = (root, neverSkip) => neverSkip.size === 0 ? root : `${root}${[
300
309
  * comment), so a `neverSkip` override must be part of the key -- keying on
301
310
  * `root` alone would let the FIRST program compiled from a directory decide,
302
311
  * for every later one, whether `test/runtime` exists.
312
+ *
313
+ * A file below a directory descended into only because of `neverSkip` is
314
+ * returned in `confined`, not `files`: whether it is indexed depends on the
315
+ * program being compiled (`buildPackageIndex`), not on the package.
303
316
  */
304
317
  const collectSourceFiles = (root, neverSkip) => {
305
318
  const key = indexKey(root, neverSkip);
306
319
  const known = sourceFilesByRoot.get(key);
307
320
  if (known)
308
321
  return known;
309
- const out = [];
310
- const walk = (dir) => {
322
+ const files = [];
323
+ const confined = [];
324
+ const walk = (dir, admitted) => {
311
325
  let entries;
312
326
  try {
313
327
  entries = readdirSync(dir, { withFileTypes: true, encoding: 'utf8' });
@@ -320,18 +334,21 @@ const collectSourceFiles = (root, neverSkip) => {
320
334
  continue;
321
335
  if (entry.isDirectory()) {
322
336
  const childPath = join(dir, entry.name);
323
- if (SKIP_DIRS.has(entry.name) && !neverSkip.has(childPath))
337
+ const skipped = SKIP_DIRS.has(entry.name);
338
+ if (skipped && !neverSkip.has(childPath))
324
339
  continue;
325
- walk(childPath);
340
+ walk(childPath, admitted || skipped);
326
341
  }
327
342
  else if (/\.m?js$/.test(entry.name)) {
328
- out.push(join(dir, entry.name));
343
+ ;
344
+ (admitted ? confined : files).push(join(dir, entry.name));
329
345
  }
330
346
  }
331
347
  };
332
- walk(root);
333
- sourceFilesByRoot.set(key, out);
334
- return out;
348
+ walk(root, false);
349
+ const found = { files, confined };
350
+ sourceFilesByRoot.set(key, found);
351
+ return found;
335
352
  };
336
353
  /**
337
354
  * JSDoc's own vague-object special case, spelled as plain text: `{Object}`
@@ -642,7 +659,7 @@ const memberTypeTextsOf = (klass, file) => {
642
659
  else if (entry.kind === 'object')
643
660
  objectShape.set(name, entry.shape);
644
661
  }
645
- return { declaredNames, text, objectShape };
662
+ return { declaredNames, callableNames: methodNames, text, objectShape };
646
663
  };
647
664
  const readerCaches = new WeakMap();
648
665
  const cachesFor = (read) => {
@@ -770,6 +787,7 @@ const scanPackageFile = (filePath, text) => {
770
787
  exportName: classExportName(file, statement),
771
788
  baseName,
772
789
  declaredNames: evidence.declaredNames,
790
+ callableNames: evidence.callableNames,
773
791
  ownMembers: evidence.text,
774
792
  ownObjectShapes: evidence.objectShape
775
793
  });
@@ -839,8 +857,11 @@ const compactScan = (scan) => {
839
857
  return EMPTY_SCAN;
840
858
  return { ...scan, externallyReadNames: [...new Set(scan.externallyReadNames)].map(sharedName) };
841
859
  };
842
- const buildPackageIndex = (root, read, neverSkip) => {
843
- const key = indexKey(root, neverSkip);
860
+ const buildPackageIndex = (root, read, neverSkip, graph) => {
861
+ const found = collectSourceFiles(root, neverSkip);
862
+ // a confined file is the program's own or not indexed at all (see `ancestryBetween`)
863
+ const confined = found.confined.filter((filePath) => graph.has(resolve(filePath)));
864
+ const key = confined.length === 0 ? indexKey(root, neverSkip) : `${indexKey(root, neverSkip)}\n${confined.join('\n')}`;
844
865
  const cached = cachesFor(read).index.get(key);
845
866
  if (cached)
846
867
  return cached;
@@ -851,7 +872,7 @@ const buildPackageIndex = (root, read, neverSkip) => {
851
872
  const externallyReadNames = new Set();
852
873
  const constantDomainsByName = new Map();
853
874
  const duplicateConstants = new Set();
854
- for (const filePath of collectSourceFiles(root, neverSkip)) {
875
+ for (const filePath of [...found.files, ...confined]) {
855
876
  let text;
856
877
  try {
857
878
  text = read(filePath);
@@ -1169,334 +1190,400 @@ const joinedObjectRecordText = (index, shapes, ctx) => {
1169
1190
  }
1170
1191
  return fields.length > 0 ? `{${fields.join('; ')}}` : null;
1171
1192
  };
1193
+ /**
1194
+ * The compilation's own module graph: its root files and every module they
1195
+ * import at runtime, as absolute paths. The files a skipped directory is let
1196
+ * in for (`ancestryBetween`) are indexed only from here, so what a program's
1197
+ * overlay reads depends on that program alone, whatever else shares its
1198
+ * directory.
1199
+ */
1200
+ const programGraph = (roots, read) => {
1201
+ const graph = new Set();
1202
+ for (const rootFile of roots) {
1203
+ const start = resolve(rootFile);
1204
+ graph.add(start);
1205
+ for (const reached of modulesReachableFrom(start, read))
1206
+ graph.add(reached);
1207
+ }
1208
+ return graph;
1209
+ };
1172
1210
  /**
1173
1211
  * The overlay, reading declarers through `read` -- see `DeclarerReader`.
1174
1212
  * `compiler.ts` builds one per compilation with that compilation's plugin
1175
- * transforms; a caller with no plugins may pass `readFileSync` itself.
1213
+ * transforms and root files; a caller with no plugins may pass `readFileSync`
1214
+ * itself. Without `roots`, the file being transformed stands for the program.
1176
1215
  */
1177
- export const createSubclassMemberOverlayTransform = (read) => (input) => {
1178
- if (!/\.m?js$/.test(input.fileName))
1179
- return null;
1180
- const root = packageRootFor(input.fileName);
1181
- if (!root)
1182
- return null;
1183
- const here = resolve(input.fileName);
1184
- const file = ts.createSourceFile(input.fileName, input.text, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
1185
- // Every edit below is made at a top-level named class, and the index is
1186
- // read nowhere else. Building it reads and transforms every source file of
1187
- // the package, so a file declaring no class does not pay for it.
1188
- if (!file.statements.some((statement) => ts.isClassDeclaration(statement) && statement.name !== undefined))
1189
- return null;
1190
- const index = buildPackageIndex(root, read, ancestryBetween(root, input.fileName));
1191
- const boundHere = new Set();
1192
- let leadingImportEnd = 0;
1193
- let stillLeading = true;
1194
- for (const statement of file.statements) {
1195
- if (ts.isImportDeclaration(statement)) {
1196
- if (stillLeading)
1197
- leadingImportEnd = statement.getEnd();
1198
- if (statement.importClause) {
1199
- const bindings = statement.importClause.namedBindings;
1200
- if (bindings && ts.isNamedImports(bindings))
1201
- for (const element of bindings.elements)
1202
- boundHere.add(element.name.text);
1203
- if (statement.importClause.name)
1204
- boundHere.add(statement.importClause.name.text);
1216
+ export const createSubclassMemberOverlayTransform = (read, roots = []) => {
1217
+ let rootsGraph = null;
1218
+ const graphFor = (fileName) => {
1219
+ if (roots.length === 0)
1220
+ return programGraph([fileName], read);
1221
+ if (rootsGraph === null)
1222
+ rootsGraph = programGraph(roots, read);
1223
+ return rootsGraph;
1224
+ };
1225
+ return (input) => {
1226
+ if (!/\.m?js$/.test(input.fileName))
1227
+ return null;
1228
+ const root = packageRootFor(input.fileName);
1229
+ if (!root)
1230
+ return null;
1231
+ const here = resolve(input.fileName);
1232
+ const file = ts.createSourceFile(input.fileName, input.text, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
1233
+ // Every edit below is made at a top-level named class, and the index is
1234
+ // read nowhere else. Building it reads and transforms every source file of
1235
+ // the package, so a file declaring no class does not pay for it.
1236
+ if (!file.statements.some((statement) => ts.isClassDeclaration(statement) && statement.name !== undefined))
1237
+ return null;
1238
+ const index = buildPackageIndex(root, read, ancestryBetween(root, input.fileName), graphFor(input.fileName));
1239
+ const boundHere = new Set();
1240
+ let leadingImportEnd = 0;
1241
+ let stillLeading = true;
1242
+ for (const statement of file.statements) {
1243
+ if (ts.isImportDeclaration(statement)) {
1244
+ if (stillLeading)
1245
+ leadingImportEnd = statement.getEnd();
1246
+ if (statement.importClause) {
1247
+ const bindings = statement.importClause.namedBindings;
1248
+ if (bindings && ts.isNamedImports(bindings))
1249
+ for (const element of bindings.elements)
1250
+ boundHere.add(element.name.text);
1251
+ if (statement.importClause.name)
1252
+ boundHere.add(statement.importClause.name.text);
1253
+ }
1254
+ continue;
1255
+ }
1256
+ stillLeading = false;
1257
+ if ((ts.isClassDeclaration(statement) || ts.isFunctionDeclaration(statement)) && statement.name)
1258
+ boundHere.add(statement.name.text);
1259
+ else if (ts.isVariableStatement(statement)) {
1260
+ for (const declaration of statement.declarationList.declarations)
1261
+ if (ts.isIdentifier(declaration.name))
1262
+ boundHere.add(declaration.name.text);
1205
1263
  }
1206
- continue;
1207
- }
1208
- stillLeading = false;
1209
- if ((ts.isClassDeclaration(statement) || ts.isFunctionDeclaration(statement)) && statement.name)
1210
- boundHere.add(statement.name.text);
1211
- else if (ts.isVariableStatement(statement)) {
1212
- for (const declaration of statement.declarationList.declarations)
1213
- if (ts.isIdentifier(declaration.name))
1214
- boundHere.add(declaration.name.text);
1215
1264
  }
1216
- }
1217
- // TypeScript does not attach a field's JSDoc when its comment starts on
1218
- // the class opening-brace line. Every member insertion starts a new line
1219
- // so the first generated field retains the type this transform states.
1220
- const edits = [];
1221
- const importLines = new Map();
1222
- /**
1223
- * RESTATE what this class declares for itself.
1224
- *
1225
- * The overlay above writes a member onto an ANCESTOR, and TypeScript treats
1226
- * a JS `this.x = ...` whose base declares `x` as an ASSIGNMENT rather than
1227
- * a declaration -- so the ancestor's field silently replaces the declarer's
1228
- * own `@type` as the answer for the declarer's own reads. With a
1229
- * near-universal `Emitter` as that ancestor, `Item.id`
1230
- * (`@type {string}`) read back `string | undefined` and `Item.origin`
1231
- * (`@type {?Point}`) read back `Point | null | undefined` -- the
1232
- * `| undefined` this module adds for soundness at a BASE-typed read,
1233
- * charged to a class where the constructor assigns the member
1234
- * unconditionally and it can never be absent.
1235
- *
1236
- * A class may redeclare an inherited property with a narrower type, so
1237
- * both facts can be stated at once: the base keeps the union that makes a
1238
- * base-typed read resolve, and the declarer restates its own, which is
1239
- * what its own reads then see. Only a member with ONE unambiguous text and
1240
- * no unresolvable or not-yet-imported name in it -- this adds no `@import`
1241
- * of its own, so a name must already be in scope in the declarer's file.
1242
- */
1243
- const restatementsFor = (statement, info) => {
1244
- if (process.env['GEA_NO_RESTATE'])
1245
- return [];
1246
- if (!info.baseName || !index.classesByName.has(info.baseName))
1247
- return [];
1248
- if (index.untrustedClassNames.has(info.name))
1249
- return [];
1250
- const declaredHere = new Set(statement.members.map((member) => (member.name && ts.isIdentifier(member.name) ? member.name.text : '')));
1251
- const out = [];
1252
- for (const name of [...info.ownMembers.keys()].sort()) {
1253
- if (!index.externallyReadNames.has(name))
1254
- continue;
1255
- if (declaredHere.has(name))
1256
- continue;
1257
- const texts = info.ownMembers.get(name);
1258
- if (!texts || texts.length !== 1)
1265
+ // TypeScript does not attach a field's JSDoc when its comment starts on
1266
+ // the class opening-brace line. Every member insertion starts a new line
1267
+ // so the first generated field retains the type this transform states.
1268
+ const edits = [];
1269
+ const importLines = new Map();
1270
+ /**
1271
+ * RESTATE what this class declares for itself.
1272
+ *
1273
+ * The overlay above writes a member onto an ANCESTOR, and TypeScript treats
1274
+ * a JS `this.x = ...` whose base declares `x` as an ASSIGNMENT rather than
1275
+ * a declaration -- so the ancestor's field silently replaces the declarer's
1276
+ * own `@type` as the answer for the declarer's own reads. With a
1277
+ * near-universal `Emitter` as that ancestor, `Item.id`
1278
+ * (`@type {string}`) read back `string | undefined` and `Item.origin`
1279
+ * (`@type {?Point}`) read back `Point | null | undefined` -- the
1280
+ * `| undefined` this module adds for soundness at a BASE-typed read,
1281
+ * charged to a class where the constructor assigns the member
1282
+ * unconditionally and it can never be absent.
1283
+ *
1284
+ * A class may redeclare an inherited property with a narrower type, so
1285
+ * both facts can be stated at once: the base keeps the union that makes a
1286
+ * base-typed read resolve, and the declarer restates its own, which is
1287
+ * what its own reads then see. Only a member with ONE unambiguous text and
1288
+ * no unresolvable or not-yet-imported name in it -- this adds no `@import`
1289
+ * of its own, so a name must already be in scope in the declarer's file.
1290
+ *
1291
+ * Only a field can be redeclared that way. A member an ancestor declares as
1292
+ * an accessor or a method stays the ancestor's: `this.texture = ...` in a
1293
+ * subclass of a class with `get texture()`/`set texture()` assigns through
1294
+ * the setter, and a restated `texture;` field is a checker error (an
1295
+ * accessor overridden as an instance property) that leaves the program
1296
+ * uncertified.
1297
+ */
1298
+ const restatementsFor = (statement, info) => {
1299
+ if (process.env['GEA_NO_RESTATE'])
1300
+ return [];
1301
+ if (!info.baseName || !index.classesByName.has(info.baseName))
1302
+ return [];
1303
+ if (index.untrustedClassNames.has(info.name))
1304
+ return [];
1305
+ const declaredHere = new Set(statement.members.map((member) => (member.name && ts.isIdentifier(member.name) ? member.name.text : '')));
1306
+ const inheritedCallables = new Set();
1307
+ // a heritage cycle (two classes naming each other) ends the walk rather than looping
1308
+ const walked = new Set([info.name]);
1309
+ for (let ancestorName = info.baseName; ancestorName !== null && !walked.has(ancestorName);) {
1310
+ walked.add(ancestorName);
1311
+ const ancestor = index.classesByName.get(ancestorName);
1312
+ if (!ancestor)
1313
+ break;
1314
+ for (const name of ancestor.callableNames)
1315
+ inheritedCallables.add(name);
1316
+ ancestorName = ancestor.baseName;
1317
+ }
1318
+ const out = [];
1319
+ for (const name of [...info.ownMembers.keys()].sort()) {
1320
+ if (!index.externallyReadNames.has(name))
1321
+ continue;
1322
+ if (declaredHere.has(name) || inheritedCallables.has(name))
1323
+ continue;
1324
+ const texts = info.ownMembers.get(name);
1325
+ if (!texts || texts.length !== 1)
1326
+ continue;
1327
+ const text = texts[0];
1328
+ if (text.length === 0 || text.includes('*/'))
1329
+ continue;
1330
+ const foreign = foreignNamesIn(text);
1331
+ if (!foreign.every((foreignName) => index.classesByName.has(foreignName) && boundHere.has(foreignName)))
1332
+ continue;
1333
+ out.push(`\t/** @type {${text}} */\n\t${name};\n`);
1334
+ }
1335
+ // An object literal the class assigns (`this.parameters = { width: width }`) is its own record just the same:
1336
+ // restated in the literal's own property order, so the record keeps the layout the literal gives it.
1337
+ for (const name of [...info.ownObjectShapes.keys()].sort()) {
1338
+ if (!index.externallyReadNames.has(name))
1339
+ continue;
1340
+ if (declaredHere.has(name) || inheritedCallables.has(name))
1341
+ continue;
1342
+ const shape = info.ownObjectShapes.get(name);
1343
+ if (!shape || shape.size === 0)
1344
+ continue;
1345
+ const properties = [...shape].map(([property, text]) => `${property}: ${text}`);
1346
+ const text = `{${properties.join('; ')}}`;
1347
+ if (text.includes('*/'))
1348
+ continue;
1349
+ const foreign = foreignNamesIn([...shape.values()].join(' '));
1350
+ if (!foreign.every((foreignName) => index.classesByName.has(foreignName) && boundHere.has(foreignName)))
1351
+ continue;
1352
+ out.push(`\t/** @type {${text}} */\n\t${name};\n`);
1353
+ }
1354
+ return out;
1355
+ };
1356
+ for (const statement of file.statements) {
1357
+ if (!ts.isClassDeclaration(statement) || !statement.name)
1259
1358
  continue;
1260
- const text = texts[0];
1261
- if (text.length === 0 || text.includes('*/'))
1359
+ const baseInfo = index.classesByName.get(statement.name.text);
1360
+ if (!baseInfo || resolve(baseInfo.filePath) !== here)
1262
1361
  continue;
1263
- const foreign = foreignNamesIn(text);
1264
- if (!foreign.every((foreignName) => index.classesByName.has(foreignName) && boundHere.has(foreignName)))
1362
+ const restated = restatementsFor(statement, baseInfo);
1363
+ const descendants = transitiveSubclassesOf(index, statement.name.text);
1364
+ if (descendants.length === 0) {
1365
+ if (restated.length > 0)
1366
+ edits.push({ at: statement.members.pos, text: '\n' + restated.join('') });
1265
1367
  continue;
1266
- out.push(`\t/** @type {${text}} */\n\t${name};\n`);
1267
- }
1268
- return out;
1269
- };
1270
- for (const statement of file.statements) {
1271
- if (!ts.isClassDeclaration(statement) || !statement.name)
1272
- continue;
1273
- const baseInfo = index.classesByName.get(statement.name.text);
1274
- if (!baseInfo || resolve(baseInfo.filePath) !== here)
1275
- continue;
1276
- const restated = restatementsFor(statement, baseInfo);
1277
- const descendants = transitiveSubclassesOf(index, statement.name.text);
1278
- if (descendants.length === 0) {
1279
- if (restated.length > 0)
1280
- edits.push({ at: statement.members.pos, text: '\n' + restated.join('') });
1281
- continue;
1282
- }
1283
- // Refuse the WHOLE base when its own name or a descendant's could be the
1284
- // target of a heritage clause this scan could not resolve -- there may
1285
- // be a subclass in this hierarchy it never found.
1286
- const hierarchyNames = [statement.name.text, ...descendants.map((d) => d.name)];
1287
- const refusedHierarchy = index.unresolvedHeritageTexts.some((text) => hierarchyNames.some((name) => wholeWordPresent(text, name))) ||
1288
- index.untrustedClassNames.has(statement.name.text);
1289
- if (refusedHierarchy) {
1290
- if (restated.length > 0)
1291
- edits.push({ at: statement.members.pos, text: '\n' + restated.join('') });
1292
- continue;
1293
- }
1294
- const liveEvidence = memberTypeTextsOf(statement, file);
1295
- const alreadyDeclared = new Set([
1296
- ...liveEvidence.declaredNames,
1297
- ...baseInfo.declaredNames,
1298
- ...liveEvidence.text.keys(),
1299
- ...liveEvidence.objectShape.keys(),
1300
- ...baseInfo.ownMembers.keys(),
1301
- ...baseInfo.ownObjectShapes.keys()
1302
- ]);
1303
- // A member an ancestor already declares is already readable through this
1304
- // class. Re-declaring it here from a descendant's writes does more than
1305
- // make that evidence visible: it shadows the inherited declaration with
1306
- // the descendant union. A `Sprite` was given
1307
- // `autoUpdate: false | undefined` from one specialized descendant,
1308
- // replacing `Item.autoUpdate: boolean` and making every Sprite
1309
- // structurally incompatible with Item. Walk the real heritage chain
1310
- // and keep those inherited declarations authoritative at every
1311
- // intermediate class.
1312
- let ancestorName = baseInfo.baseName;
1313
- while (ancestorName) {
1314
- const ancestor = index.classesByName.get(ancestorName);
1315
- if (!ancestor)
1316
- break;
1317
- for (const name of ancestor.declaredNames)
1318
- alreadyDeclared.add(name);
1319
- for (const name of ancestor.ownMembers.keys())
1320
- alreadyDeclared.add(name);
1321
- for (const name of ancestor.ownObjectShapes.keys())
1322
- alreadyDeclared.add(name);
1323
- ancestorName = ancestor.baseName;
1324
- }
1325
- const candidateNames = new Set();
1326
- for (const descendant of descendants) {
1327
- if (index.untrustedClassNames.has(descendant.name))
1368
+ }
1369
+ // Refuse the WHOLE base when its own name or a descendant's could be the
1370
+ // target of a heritage clause this scan could not resolve -- there may
1371
+ // be a subclass in this hierarchy it never found.
1372
+ const hierarchyNames = [statement.name.text, ...descendants.map((d) => d.name)];
1373
+ const refusedHierarchy = index.unresolvedHeritageTexts.some((text) => hierarchyNames.some((name) => wholeWordPresent(text, name))) ||
1374
+ index.untrustedClassNames.has(statement.name.text);
1375
+ if (refusedHierarchy) {
1376
+ if (restated.length > 0)
1377
+ edits.push({ at: statement.members.pos, text: '\n' + restated.join('') });
1328
1378
  continue;
1329
- for (const name of descendant.ownMembers.keys()) {
1330
- if (index.externallyReadNames.has(name))
1331
- candidateNames.add(name);
1332
1379
  }
1333
- for (const name of descendant.ownObjectShapes.keys()) {
1334
- if (index.externallyReadNames.has(name))
1335
- candidateNames.add(name);
1380
+ const liveEvidence = memberTypeTextsOf(statement, file);
1381
+ const alreadyDeclared = new Set([
1382
+ ...liveEvidence.declaredNames,
1383
+ ...baseInfo.declaredNames,
1384
+ ...liveEvidence.text.keys(),
1385
+ ...liveEvidence.objectShape.keys(),
1386
+ ...baseInfo.ownMembers.keys(),
1387
+ ...baseInfo.ownObjectShapes.keys()
1388
+ ]);
1389
+ // A member an ancestor already declares is already readable through this
1390
+ // class. Re-declaring it here from a descendant's writes does more than
1391
+ // make that evidence visible: it shadows the inherited declaration with
1392
+ // the descendant union. A `Sprite` was given
1393
+ // `autoUpdate: false | undefined` from one specialized descendant,
1394
+ // replacing `Item.autoUpdate: boolean` and making every Sprite
1395
+ // structurally incompatible with Item. Walk the real heritage chain
1396
+ // and keep those inherited declarations authoritative at every
1397
+ // intermediate class.
1398
+ let ancestorName = baseInfo.baseName;
1399
+ while (ancestorName) {
1400
+ const ancestor = index.classesByName.get(ancestorName);
1401
+ if (!ancestor)
1402
+ break;
1403
+ for (const name of ancestor.declaredNames)
1404
+ alreadyDeclared.add(name);
1405
+ for (const name of ancestor.ownMembers.keys())
1406
+ alreadyDeclared.add(name);
1407
+ for (const name of ancestor.ownObjectShapes.keys())
1408
+ alreadyDeclared.add(name);
1409
+ ancestorName = ancestor.baseName;
1336
1410
  }
1337
- }
1338
- for (const name of alreadyDeclared)
1339
- candidateNames.delete(name);
1340
- if (candidateNames.size === 0) {
1341
- if (restated.length > 0)
1342
- edits.push({ at: statement.members.pos, text: '\n' + restated.join('') });
1343
- continue;
1344
- }
1345
- const hereDir = dirname(here);
1346
- const fieldTexts = [...restated];
1347
- for (const name of [...candidateNames].sort()) {
1348
- const objectShapeDescendants = descendants.filter((d) => !index.untrustedClassNames.has(d.name) && d.ownObjectShapes.has(name));
1349
- const textShapeDescendants = descendants.filter((d) => !index.untrustedClassNames.has(d.name) && d.ownMembers.has(name));
1350
- // Mixed evidence -- some declarer states a scalar/reference, another
1351
- // an object literal, for the same name -- is ambiguous the same way a
1352
- // second differently-shaped assignment within ONE class is
1353
- // (`memberTypeTextsOf`'s own `recordObjectLiteral`): refuse rather
1354
- // than guess which shape a caller reaching the member actually sees.
1355
- if (objectShapeDescendants.length > 0 && textShapeDescendants.length > 0)
1356
- continue;
1357
- if (objectShapeDescendants.length > 0) {
1358
- const joined = joinedObjectRecordText(index, objectShapeDescendants.map((d) => d.ownObjectShapes.get(name)), { read, boundHere, importLines, hereDir, here });
1359
- if (joined)
1360
- fieldTexts.push(`\t/** @type {${joined} | undefined}\n\t * @geaSubclassMemberOverlay */\n\t${name};\n`);
1411
+ const candidateNames = new Set();
1412
+ for (const descendant of descendants) {
1413
+ if (index.untrustedClassNames.has(descendant.name))
1414
+ continue;
1415
+ for (const name of descendant.ownMembers.keys()) {
1416
+ if (index.externallyReadNames.has(name))
1417
+ candidateNames.add(name);
1418
+ }
1419
+ for (const name of descendant.ownObjectShapes.keys()) {
1420
+ if (index.externallyReadNames.has(name))
1421
+ candidateNames.add(name);
1422
+ }
1423
+ }
1424
+ for (const name of alreadyDeclared)
1425
+ candidateNames.delete(name);
1426
+ if (candidateNames.size === 0) {
1427
+ if (restated.length > 0)
1428
+ edits.push({ at: statement.members.pos, text: '\n' + restated.join('') });
1361
1429
  continue;
1362
1430
  }
1363
- const typeParts = [];
1364
- const neededImports = [];
1365
- // ALL-OR-NONE.
1366
- //
1367
- // Every per-candidate refusal below used to `continue` and let the
1368
- // REMAINING declarers form the union. That is not the smaller answer it
1369
- // reads as -- it is a DIFFERENT one. The fact this module states is
1370
- // "the member holds what SOME declarer put there, or `undefined`", and
1371
- // it is sound only as an over-approximation; dropping a declarer makes
1372
- // it a SUBSET, and the field it writes onto `Base` then shadows every
1373
- // declarer's own precise declaration with a type that does not contain
1374
- // what that declarer actually assigns.
1375
- //
1376
- // Measured: `Item.parent` is `@type {?Item}`, and that
1377
- // candidate is refused by `modulesReachableFrom` (importing `Item`
1378
- // into `Emitter.js` closes a cycle) -- while an unrelated
1379
- // class's boolean `parent` survives. The overlay wrote `/** @type
1380
- // {boolean | undefined} */ parent;` onto `Emitter`, and because
1381
- // TypeScript treats a JS `this.x = ...` whose base declares `x` as an
1382
- // ASSIGNMENT rather than a declaration, `Item`'s own
1383
- // `@type {?Item}` stopped meaning anything: `this.parent` in
1384
- // `Item.js` typed `boolean | undefined`. Not a widening -- a wrong
1385
- // answer, and one no downstream census can see is wrong.
1386
- //
1387
- // The header already stated the intended rule for the whole-member case
1388
- // ("if EVERY declarer refuses, the member is left exactly as `any`");
1389
- // this is the same rule applied to a PARTIAL refusal, which is the only
1390
- // reading under which the union is still the fact the header claims.
1391
- let refusedDeclarer = false;
1392
- for (const descendant of descendants) {
1393
- const texts = descendant.ownMembers.get(name);
1394
- if (!texts)
1431
+ const hereDir = dirname(here);
1432
+ const fieldTexts = [...restated];
1433
+ for (const name of [...candidateNames].sort()) {
1434
+ const objectShapeDescendants = descendants.filter((d) => !index.untrustedClassNames.has(d.name) && d.ownObjectShapes.has(name));
1435
+ const textShapeDescendants = descendants.filter((d) => !index.untrustedClassNames.has(d.name) && d.ownMembers.has(name));
1436
+ // Mixed evidence -- some declarer states a scalar/reference, another
1437
+ // an object literal, for the same name -- is ambiguous the same way a
1438
+ // second differently-shaped assignment within ONE class is
1439
+ // (`memberTypeTextsOf`'s own `recordObjectLiteral`): refuse rather
1440
+ // than guess which shape a caller reaching the member actually sees.
1441
+ if (objectShapeDescendants.length > 0 && textShapeDescendants.length > 0)
1395
1442
  continue;
1396
- if (index.untrustedClassNames.has(descendant.name)) {
1397
- refusedDeclarer = true;
1443
+ if (objectShapeDescendants.length > 0) {
1444
+ const joined = joinedObjectRecordText(index, objectShapeDescendants.map((d) => d.ownObjectShapes.get(name)), { read, boundHere, importLines, hereDir, here });
1445
+ if (joined)
1446
+ fieldTexts.push(`\t/** @type {${joined} | undefined}\n\t * @geaSubclassMemberOverlay */\n\t${name};\n`);
1398
1447
  continue;
1399
1448
  }
1400
- for (const statedText of texts) {
1401
- const candidateText = withConstantDomains(index, statedText);
1402
- const foreignTypeNames = foreignNamesIn(candidateText);
1403
- // Every foreign name the text ITSELF mentions (a boolean literal
1404
- // mentions none) must resolve to a class this package actually
1405
- // declares -- an unresolvable one (an external library type, a
1406
- // type alias, a generic parameter) refuses just this ONE
1407
- // candidate rather than guessing at it. The declaring subclass's
1408
- // OWN name is never needed here: the text names what the field
1409
- // holds, not who assigned it.
1410
- if (!foreignTypeNames.every((foreignName) => {
1411
- const info = index.classesByName.get(foreignName);
1412
- return info !== undefined && (resolve(info.filePath) === here || info.exportName !== null);
1413
- })) {
1414
- refusedDeclarer = true;
1415
- continue;
1416
- }
1417
- if (foreignTypeNames.some((foreignName) => boundHere.has(foreignName) && !importLines.has(foreignName))) {
1418
- refusedDeclarer = true;
1449
+ const typeParts = [];
1450
+ const neededImports = [];
1451
+ // ALL-OR-NONE.
1452
+ //
1453
+ // Every per-candidate refusal below used to `continue` and let the
1454
+ // REMAINING declarers form the union. That is not the smaller answer it
1455
+ // reads as -- it is a DIFFERENT one. The fact this module states is
1456
+ // "the member holds what SOME declarer put there, or `undefined`", and
1457
+ // it is sound only as an over-approximation; dropping a declarer makes
1458
+ // it a SUBSET, and the field it writes onto `Base` then shadows every
1459
+ // declarer's own precise declaration with a type that does not contain
1460
+ // what that declarer actually assigns.
1461
+ //
1462
+ // Measured: `Item.parent` is `@type {?Item}`, and that
1463
+ // candidate is refused by `modulesReachableFrom` (importing `Item`
1464
+ // into `Emitter.js` closes a cycle) -- while an unrelated
1465
+ // class's boolean `parent` survives. The overlay wrote `/** @type
1466
+ // {boolean | undefined} */ parent;` onto `Emitter`, and because
1467
+ // TypeScript treats a JS `this.x = ...` whose base declares `x` as an
1468
+ // ASSIGNMENT rather than a declaration, `Item`'s own
1469
+ // `@type {?Item}` stopped meaning anything: `this.parent` in
1470
+ // `Item.js` typed `boolean | undefined`. Not a widening -- a wrong
1471
+ // answer, and one no downstream census can see is wrong.
1472
+ //
1473
+ // The header already stated the intended rule for the whole-member case
1474
+ // ("if EVERY declarer refuses, the member is left exactly as `any`");
1475
+ // this is the same rule applied to a PARTIAL refusal, which is the only
1476
+ // reading under which the union is still the fact the header claims.
1477
+ let refusedDeclarer = false;
1478
+ for (const descendant of descendants) {
1479
+ const texts = descendant.ownMembers.get(name);
1480
+ if (!texts)
1419
1481
  continue;
1420
- }
1421
- // An import edge this candidate would need must not close a cycle:
1422
- // if the class the candidate names is a file that can ALREADY
1423
- // reach `here` (this base's own file) through the package's real
1424
- // runtime imports, adding the reverse edge closes a loop and the
1425
- // checker answers `any` for everything caught in it -- see
1426
- // `modulesReachableFrom`'s own comment. Refuses just this ONE
1427
- // candidate, the same granularity as the unresolvable-name check
1428
- // above: a different candidate for the same member that names an
1429
- // acyclic type is unaffected.
1430
- if (foreignTypeNames.some((foreignName) => {
1431
- const info = index.classesByName.get(foreignName);
1432
- if (!info)
1433
- return false;
1434
- const targetPath = resolve(info.filePath);
1435
- return targetPath !== here && modulesReachableFrom(targetPath, read).has(here);
1436
- })) {
1482
+ if (index.untrustedClassNames.has(descendant.name)) {
1437
1483
  refusedDeclarer = true;
1438
1484
  continue;
1439
1485
  }
1440
- typeParts.push(candidateText);
1441
- for (const className of foreignTypeNames) {
1442
- const info = index.classesByName.get(className);
1443
- if (info)
1444
- neededImports.push(info);
1486
+ for (const statedText of texts) {
1487
+ const candidateText = withConstantDomains(index, statedText);
1488
+ const foreignTypeNames = foreignNamesIn(candidateText);
1489
+ // Every foreign name the text ITSELF mentions (a boolean literal
1490
+ // mentions none) must resolve to a class this package actually
1491
+ // declares -- an unresolvable one (an external library type, a
1492
+ // type alias, a generic parameter) refuses just this ONE
1493
+ // candidate rather than guessing at it. The declaring subclass's
1494
+ // OWN name is never needed here: the text names what the field
1495
+ // holds, not who assigned it.
1496
+ if (!foreignTypeNames.every((foreignName) => {
1497
+ const info = index.classesByName.get(foreignName);
1498
+ return info !== undefined && (resolve(info.filePath) === here || info.exportName !== null);
1499
+ })) {
1500
+ refusedDeclarer = true;
1501
+ continue;
1502
+ }
1503
+ if (foreignTypeNames.some((foreignName) => boundHere.has(foreignName) && !importLines.has(foreignName))) {
1504
+ refusedDeclarer = true;
1505
+ continue;
1506
+ }
1507
+ // An import edge this candidate would need must not close a cycle:
1508
+ // if the class the candidate names is a file that can ALREADY
1509
+ // reach `here` (this base's own file) through the package's real
1510
+ // runtime imports, adding the reverse edge closes a loop and the
1511
+ // checker answers `any` for everything caught in it -- see
1512
+ // `modulesReachableFrom`'s own comment. Refuses just this ONE
1513
+ // candidate, the same granularity as the unresolvable-name check
1514
+ // above: a different candidate for the same member that names an
1515
+ // acyclic type is unaffected.
1516
+ if (foreignTypeNames.some((foreignName) => {
1517
+ const info = index.classesByName.get(foreignName);
1518
+ if (!info)
1519
+ return false;
1520
+ const targetPath = resolve(info.filePath);
1521
+ return targetPath !== here && modulesReachableFrom(targetPath, read).has(here);
1522
+ })) {
1523
+ refusedDeclarer = true;
1524
+ continue;
1525
+ }
1526
+ typeParts.push(candidateText);
1527
+ for (const className of foreignTypeNames) {
1528
+ const info = index.classesByName.get(className);
1529
+ if (info)
1530
+ neededImports.push(info);
1531
+ }
1445
1532
  }
1446
1533
  }
1447
- }
1448
- if (refusedDeclarer || typeParts.length === 0)
1449
- continue;
1450
- // A reference-typed candidate is sound to STATE (the union over-
1451
- // approximates, per this file's own header) but is only sound to
1452
- // ADD to Base without also corrupting what its OWN declaring
1453
- // subclasses read: TypeScript's checker gives an unannotated
1454
- // `this.x = ...` in a subclass the type Base now declares, not the
1455
- // narrower type that assignment's own shape implies. When every
1456
- // declarer of this member is drawn from the SAME inheritance lineage
1457
- // (`shareCommonAncestor`), a caller reaching the member through any
1458
- // union member still resolves the SAME inherited method -- no
1459
- // precision lost, no signature ambiguity. When two declarers are
1460
- // UNRELATED classes that merely reuse a member NAME
1461
- // (`Item.transform: Transform3` vs `Image.transform: Transform2` --
1462
- // both root classes, both direct descendants of a near-universal
1463
- // `Emitter`, sharing a name by coincidence, not a relationship),
1464
- // each contributes its own same-named method with a different
1465
- // signature; overlaying the union onto `Emitter` silently
1466
- // widens `Item`'s own `this.transform` from a precise `Transform3` to
1467
- // `Transform2 | Transform3 | undefined`, and calling a method
1468
- // through that union asks `derive.ts` for a carrier no nominal class
1469
- // reduction covers -- `unresolved-reaches-materialization` fires,
1470
- // correctly (measured before this check existed: new violations at every
1471
- // `.transform.copy`/`.transform.multiply` call site). This is
1472
- // a purely structural class-hierarchy test -- see
1473
- // `shareCommonAncestor`'s own comment -- never a name or library check.
1474
- if (!shareCommonAncestor(index, neededImports.map((entry) => entry.name)))
1475
- continue;
1476
- for (const info of neededImports) {
1477
- if (resolve(info.filePath) === here || importLines.has(info.name))
1534
+ if (refusedDeclarer || typeParts.length === 0)
1535
+ continue;
1536
+ // A reference-typed candidate is sound to STATE (the union over-
1537
+ // approximates, per this file's own header) but is only sound to
1538
+ // ADD to Base without also corrupting what its OWN declaring
1539
+ // subclasses read: TypeScript's checker gives an unannotated
1540
+ // `this.x = ...` in a subclass the type Base now declares, not the
1541
+ // narrower type that assignment's own shape implies. When every
1542
+ // declarer of this member is drawn from the SAME inheritance lineage
1543
+ // (`shareCommonAncestor`), a caller reaching the member through any
1544
+ // union member still resolves the SAME inherited method -- no
1545
+ // precision lost, no signature ambiguity. When two declarers are
1546
+ // UNRELATED classes that merely reuse a member NAME
1547
+ // (`Item.transform: Transform3` vs `Image.transform: Transform2` --
1548
+ // both root classes, both direct descendants of a near-universal
1549
+ // `Emitter`, sharing a name by coincidence, not a relationship),
1550
+ // each contributes its own same-named method with a different
1551
+ // signature; overlaying the union onto `Emitter` silently
1552
+ // widens `Item`'s own `this.transform` from a precise `Transform3` to
1553
+ // `Transform2 | Transform3 | undefined`, and calling a method
1554
+ // through that union asks `derive.ts` for a carrier no nominal class
1555
+ // reduction covers -- `unresolved-reaches-materialization` fires,
1556
+ // correctly (measured before this check existed: new violations at every
1557
+ // `.transform.copy`/`.transform.multiply` call site). This is
1558
+ // a purely structural class-hierarchy test -- see
1559
+ // `shareCommonAncestor`'s own comment -- never a name or library check.
1560
+ if (!shareCommonAncestor(index, neededImports.map((entry) => entry.name)))
1478
1561
  continue;
1479
- importLines.set(info.name, classImportLine(info, hereDir));
1562
+ for (const info of neededImports) {
1563
+ if (resolve(info.filePath) === here || importLines.has(info.name))
1564
+ continue;
1565
+ importLines.set(info.name, classImportLine(info, hereDir));
1566
+ }
1567
+ typeParts.push('undefined');
1568
+ fieldTexts.push(`\t/** @type {${typeParts.join(' | ')}}\n\t * @geaSubclassMemberOverlay */\n\t${name};\n`);
1480
1569
  }
1481
- typeParts.push('undefined');
1482
- fieldTexts.push(`\t/** @type {${typeParts.join(' | ')}}\n\t * @geaSubclassMemberOverlay */\n\t${name};\n`);
1570
+ if (fieldTexts.length === 0)
1571
+ continue;
1572
+ edits.push({ at: statement.members.pos, text: '\n' + fieldTexts.join('') });
1483
1573
  }
1484
- if (fieldTexts.length === 0)
1485
- continue;
1486
- edits.push({ at: statement.members.pos, text: '\n' + fieldTexts.join('') });
1487
- }
1488
- if (edits.length === 0)
1489
- return null;
1490
- if (importLines.size > 0) {
1491
- const block = `\n/**\n${[...importLines.values()]
1492
- .sort()
1493
- .map((line) => ` * ${line}`)
1494
- .join('\n')}\n */\n`;
1495
- edits.push({ at: leadingImportEnd, text: block });
1496
- }
1497
- edits.sort((a, b) => b.at - a.at);
1498
- let text = input.text;
1499
- for (const edit of edits)
1500
- text = text.slice(0, edit.at) + edit.text + text.slice(edit.at);
1501
- return text;
1574
+ if (edits.length === 0)
1575
+ return null;
1576
+ if (importLines.size > 0) {
1577
+ const block = `\n/**\n${[...importLines.values()]
1578
+ .sort()
1579
+ .map((line) => ` * ${line}`)
1580
+ .join('\n')}\n */\n`;
1581
+ edits.push({ at: leadingImportEnd, text: block });
1582
+ }
1583
+ edits.sort((a, b) => b.at - a.at);
1584
+ let text = input.text;
1585
+ for (const edit of edits)
1586
+ text = text.slice(0, edit.at) + edit.text + text.slice(edit.at);
1587
+ return text;
1588
+ };
1502
1589
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geastack/compiler",
3
- "version": "1.0.47",
3
+ "version": "1.0.49",
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": {