@tsplc/compiler 0.6.1 → 0.6.2

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.
@@ -12,13 +12,7 @@ import { generatedDirectory } from "@tsplc/config/project-files";
12
12
  import ts from "typescript";
13
13
  import { modulePath } from "../lowering-key";
14
14
  import { plcSources } from "../module-graph";
15
- import {
16
- copied,
17
- from,
18
- joined,
19
- type Mapped,
20
- type Positions,
21
- } from "../positions";
15
+ import { from, joined, type Mapped, type Positions } from "../positions";
22
16
  import { inSdk, namesSdk, sdkModules, unaliased } from "../sdk";
23
17
  import { defaultNumericTypes } from "../types";
24
18
  import type { BoundPath, CompileDebug } from "../typescript";
@@ -26,12 +20,25 @@ import type { CapturedValue } from "./capture-protocol";
26
20
  import { GenericTypes } from "./generics";
27
21
  import { captureGraph } from "./graph";
28
22
  import { importPath } from "./imports";
29
- import { stringEnums, type TypeDeclarations } from "./layouts";
23
+ import {
24
+ plainName,
25
+ quotedField,
26
+ stringEnums,
27
+ type TypeDeclarations,
28
+ } from "./layouts";
30
29
  import { Model, type Root } from "./model";
30
+ import { unusedName } from "./names";
31
+ import {
32
+ constantInitializer,
33
+ definesTask,
34
+ Reduction,
35
+ serviceClients,
36
+ type Uncompiled,
37
+ } from "./reduce";
31
38
  import { Retention, retentionDeclarations } from "./retention";
32
39
  import { closingBrace, Specializer } from "./specialize";
40
+ import type { RootField } from "./storage";
33
41
  import { SpecializeError } from "./values";
34
- import { within } from "./writes";
35
42
 
36
43
  /**
37
44
  * A module the compiled program keeps as written: only types, enums, constants, tasks and the
@@ -186,70 +193,6 @@ const taskWork = (
186
193
  return work;
187
194
  };
188
195
 
189
- const constantInitializer = (
190
- node: ts.Expression,
191
- checker: ts.TypeChecker,
192
- sdk: string,
193
- ): boolean => {
194
- if (
195
- ts.isNumericLiteral(node) ||
196
- ts.isStringLiteral(node) ||
197
- ts.isNoSubstitutionTemplateLiteral(node) ||
198
- ts.isBigIntLiteral(node) ||
199
- node.kind === ts.SyntaxKind.TrueKeyword ||
200
- node.kind === ts.SyntaxKind.FalseKeyword
201
- ) {
202
- return true;
203
- }
204
- if (ts.isPrefixUnaryExpression(node)) {
205
- return constantInitializer(node.operand, checker, sdk);
206
- }
207
- if (
208
- ts.isAsExpression(node) ||
209
- ts.isSatisfiesExpression(node) ||
210
- ts.isParenthesizedExpression(node)
211
- ) {
212
- return constantInitializer(node.expression, checker, sdk);
213
- }
214
- if (ts.isPropertyAccessExpression(node)) {
215
- return ts.isIdentifier(node.expression);
216
- }
217
- if (ts.isIdentifier(node)) {
218
- return true;
219
- }
220
- if (ts.isObjectLiteralExpression(node)) {
221
- return node.properties.every(
222
- (property) =>
223
- (ts.isPropertyAssignment(property) &&
224
- constantInitializer(property.initializer, checker, sdk)) ||
225
- ts.isShorthandPropertyAssignment(property),
226
- );
227
- }
228
- if (ts.isArrayLiteralExpression(node)) {
229
- return node.elements.every((element) =>
230
- constantInitializer(element, checker, sdk),
231
- );
232
- }
233
- if (ts.isCallExpression(node)) {
234
- return (
235
- namesSdk(checker, sdk, node.expression, "createServiceClient") ||
236
- definesTask(node, checker, sdk)
237
- );
238
- }
239
- return false;
240
- };
241
-
242
- /** Whether `call` is `tasks.define(...)` or `backgroundTasks.define(...)`, which the async lowering compiles as written. */
243
- const definesTask = (
244
- call: ts.CallExpression,
245
- checker: ts.TypeChecker,
246
- sdk: string,
247
- ): boolean =>
248
- ts.isPropertyAccessExpression(call.expression) &&
249
- call.expression.name.text === "define" &&
250
- (namesSdk(checker, sdk, call.expression.expression, "tasks") ||
251
- namesSdk(checker, sdk, call.expression.expression, "backgroundTasks"));
252
-
253
196
  /**
254
197
  * Whether the program is plain TypeScript: it declares a class that is not a function block, one
255
198
  * extending the SDK's `FunctionBlock` however the module names it.
@@ -348,15 +291,15 @@ export const lowerElaboration = (
348
291
  references: NonNullable<PlcModule["references"]>;
349
292
  /** The string each member of a literal union's enum stands for, by `<types file>:<enum>`. */
350
293
  literals: Map<string, Record<string, string>>;
351
- /** The plain modules cut down to their declarations, which hold nothing the PLC compiles. */
352
- reduced: Set<string>;
294
+ /** What of each module rewritten here the PLC compiles, where that is not all of it. */
295
+ reduced: Map<string, Uncompiled>;
353
296
  } => {
354
297
  const sources = new Map<string, Mapped>();
355
298
  const diagnostics: Diagnostic[] = [];
356
299
  const origins = new Map<string, { name: string; instance?: string }>();
357
300
  const folded: Folded[] = [];
358
301
  const literals = new Map<string, Record<string, string>>();
359
- const reduced = new Set<string>();
302
+ const reduced = new Map<string, Uncompiled>();
360
303
  const references: { id: number; path: string }[] = [];
361
304
  const referenceFields: string[] = [];
362
305
  const result = {
@@ -422,7 +365,7 @@ export const lowerElaboration = (
422
365
  if (refused.length) {
423
366
  throw new AggregateError(refused);
424
367
  }
425
- const declarations = retentionDeclarations(runtime, checker, sdk);
368
+ const retained = retentionDeclarations(runtime, checker, sdk);
426
369
  const graph = captureGraph(entryFile, runtime, checker, configuration);
427
370
  // Generic classes specialize per instance, through a checker that knows each one's type arguments.
428
371
  const generics = new GenericTypes(checker);
@@ -430,18 +373,35 @@ export const lowerElaboration = (
430
373
  bound,
431
374
  inputs,
432
375
  });
433
- const rootModule = rootModules(model.roots, { directory, root, bound });
376
+ const generated = generatedModules(model.roots, { directory, root, bound });
377
+ const rootModule = generated.root;
434
378
  // A module that also holds state keeps its client and types, which a reply's type may need: the
435
379
  // router's types have no layout of their own.
436
380
  const named = (source: ts.SourceFile) =>
437
381
  isKept(source.fileName) ||
438
382
  serviceClients(source, checker, sdk).length > 0;
383
+ const reduction = new Reduction(checker, sdk, {
384
+ runtime,
385
+ kept: isKept,
386
+ entry: entrySource,
387
+ written,
388
+ bound,
389
+ });
390
+ // What the entry module declares for other modules to import, beside its code.
391
+ const declarations = reduction.entry();
439
392
  const specializer = new Specializer(
440
393
  model,
441
394
  generics,
442
395
  sdk,
443
396
  runtime,
444
- { kept: isKept, named },
397
+ {
398
+ kept: isKept,
399
+ named,
400
+ enumRefusal: (declaration) =>
401
+ reduction.sharesEnum(declaration)
402
+ ? undefined
403
+ : reduction.enumRefusal(declaration),
404
+ },
445
405
  rootModule,
446
406
  );
447
407
  const scans = scanFunctions.map((name) => {
@@ -478,20 +438,34 @@ export const lowerElaboration = (
478
438
  for (const name of specializer.initializers.takeSdkCalls()) {
479
439
  specializer.imports.addSdk(sdkModules.types, name);
480
440
  }
481
- const retention = new Retention(model, specializer.storage, declarations);
482
- const globals = new Map(
483
- [...specializer.storage.roots].map((item) => [
484
- item,
485
- storageGlobals(specializer, retention, item),
486
- ]),
487
- );
441
+ const retention = new Retention(model, specializer.storage, retained);
442
+ const stored = [...specializer.storage.roots].map((item) => ({
443
+ item,
444
+ ...storageGlobals(specializer, retention, item),
445
+ }));
488
446
  const unretained = retention.unclaimed();
489
447
  if (unretained) {
490
448
  throw unretained;
491
449
  }
492
450
  // Writing the globals declared the types they use.
493
451
  const types = specializer.layouts.snapshot();
494
- const typesFile = `${directory}/types.ts`;
452
+ // A storage module imports the generated types, so none of its variables can have a type's name.
453
+ const misnamed = stored.flatMap(({ item, fields }) =>
454
+ fields.flatMap(({ name, declaration }) =>
455
+ types.declarations.has(name)
456
+ ? [
457
+ new SpecializeError(
458
+ declaration ?? item.declaration,
459
+ `${item.name}.${name}: each field of ${item.name} becomes a PLC variable of the field's name, and the generated code already names a type ${name}. Rename the field.`,
460
+ ),
461
+ ]
462
+ : [],
463
+ ),
464
+ );
465
+ if (misnamed.length) {
466
+ throw new AggregateError(misnamed);
467
+ }
468
+ const typesFile = generated.types;
495
469
  const typeImports = (file: string) => [
496
470
  ...specializer.layouts.imports.lines(file, "import"),
497
471
  ...specializer.layouts.typeImports.lines(file, "import type"),
@@ -502,7 +476,7 @@ export const lowerElaboration = (
502
476
  typesFile,
503
477
  joined([...typeImports(typesFile), ...types.declarations.values()], "\n"),
504
478
  );
505
- for (const [item, lines] of globals) {
479
+ for (const { item, lines } of stored) {
506
480
  const file = rootModule(item);
507
481
  const imports = [...typeImports(file), ...importTypes(file)];
508
482
  sources.set(
@@ -519,11 +493,35 @@ export const lowerElaboration = (
519
493
  ...importTypes(entryFile),
520
494
  ...specializer.imports.lines(entryFile),
521
495
  ];
496
+ // An enum the generated code stores is declared before the code that reads it. What the entry
497
+ // declares for other modules only comes last, where it moves nothing the program compiled to,
498
+ // and is left out where the generated code already has the name for something of its own.
499
+ const storesEnum = (name: string) =>
500
+ specializer.layouts.imports.has(entryFile, name);
501
+ const free = ({ name }: { name: string }) =>
502
+ !storesEnum(name) &&
503
+ !specializer.named(name) &&
504
+ !types.declarations.has(name);
505
+ const declared = [
506
+ ...declarations.enums.filter(free),
507
+ ...declarations.constants.filter(free),
508
+ ];
509
+ reduction.declaredByEntry(
510
+ new Set(
511
+ [
512
+ ...declarations.enums.filter(({ name }) => storesEnum(name)),
513
+ ...declared,
514
+ ].map(({ name }) => name),
515
+ ),
516
+ );
522
517
  sources.set(
523
518
  entryFile,
524
519
  joined(
525
520
  [
526
521
  ...header.map((line) => from(main, line)),
522
+ ...declarations.enums
523
+ .filter(({ name }) => storesEnum(name))
524
+ .map(({ line }) => line),
527
525
  ...specializer.expressions.tableDeclarations,
528
526
  ...specializer.routines,
529
527
  ...scans.flatMap(({ name, declaration, body }) => [
@@ -531,6 +529,7 @@ export const lowerElaboration = (
531
529
  ...body,
532
530
  from(closingBrace(declaration), "}"),
533
531
  ]),
532
+ ...declared.map(({ line }) => line),
534
533
  ],
535
534
  "\n",
536
535
  ),
@@ -554,32 +553,17 @@ export const lowerElaboration = (
554
553
  });
555
554
  }
556
555
  }
557
- // What a cut-down module still exports: types and its literal constants; a kept module, everything.
558
- const survives = (symbol: ts.Symbol): boolean => {
559
- const declaration = symbol.valueDeclaration;
560
- if (!(symbol.flags & ts.SymbolFlags.Value) || !declaration) {
561
- return true;
562
- }
563
- const file = declaration.getSourceFile().fileName;
564
- if (file === entryFile) {
565
- return false;
566
- }
567
- return (
568
- isKept(file) ||
569
- !runtime.some((source) => source.fileName === file) ||
570
- literalConstant(checker, symbol) !== undefined ||
571
- serviceClients(declaration.getSourceFile(), checker, sdk).some(
572
- (statement) => within(declaration, statement),
573
- )
574
- );
575
- };
576
- // The plain modules now live in the generated code; keep only their types for type importers.
577
- for (const source of runtime) {
578
- if (source.fileName !== entryFile && !isKept(source.fileName)) {
579
- sources.set(source.fileName, typesOnly(source, checker, sdk, survives));
580
- reduced.add(source.fileName);
581
- }
556
+ for (const source of reduction.modules) {
557
+ sources.set(source.fileName, reduction.module(source));
558
+ reduced.set(source.fileName, { compiled: reduction.compiled(source) });
582
559
  }
560
+ reduced.set(entryFile, {
561
+ declared: new Set(
562
+ [...declarations.enums, ...declarations.constants].map(
563
+ ({ name }) => name,
564
+ ),
565
+ ),
566
+ });
583
567
  } catch (cause) {
584
568
  const causes = cause instanceof AggregateError ? cause.errors : [cause];
585
569
  diagnostics.push(
@@ -625,12 +609,13 @@ const typesModuleImports = (
625
609
  /**
626
610
  * The globals of a root's storage module: one per stored field of a record or instance, or the
627
611
  * root itself. The entry module assigns them through its namespace import of this module.
612
+ * `fields` are the fields that became globals, each of which must be able to name a variable.
628
613
  */
629
614
  const storageGlobals = (
630
615
  specializer: Specializer,
631
616
  retention: Retention,
632
617
  item: Root,
633
- ): Mapped[] => {
618
+ ): { lines: Mapped[]; fields: RootField[] } => {
634
619
  const { model, checker, layouts, storage, initializers } = specializer;
635
620
  const lines: Mapped[] = [];
636
621
  /** The SDK calls the globals' initializers are wrapped in, `retain` or `persist`. */
@@ -675,7 +660,7 @@ const storageGlobals = (
675
660
  initial: initializers.valueText(item.value, declared, layout),
676
661
  declaration: item.declaration,
677
662
  });
678
- return [...sdkImports(), ...lines];
663
+ return { lines: [...sdkImports(), ...lines], fields: [] };
679
664
  }
680
665
  const fieldInitializer = (name: string, layout: string): string => {
681
666
  if (node.captured.kind === "instance") {
@@ -687,245 +672,80 @@ const storageGlobals = (
687
672
  }
688
673
  return initializers.valueText(model.field(node, name), declared, layout);
689
674
  };
690
- for (const field of storage.rootFields(item)) {
675
+ const fields = storage.rootFields(item);
676
+ for (const field of fields) {
677
+ const origin = field.declaration ?? item.declaration;
678
+ if (!plainName(field.name)) {
679
+ throw quotedField(origin, field.name);
680
+ }
681
+ if (reservedWords.has(field.name)) {
682
+ throw new SpecializeError(
683
+ origin,
684
+ `${item.name}.${field.name}: each field of ${item.name} becomes a PLC variable of the field's name, and "${field.name}" is a word TypeScript reserves, so no variable can have it. Rename the field.`,
685
+ );
686
+ }
691
687
  global({
692
688
  ...field,
693
689
  initial: fieldInitializer(field.name, field.layout),
694
690
  });
695
691
  }
696
- return [...sdkImports(), ...lines];
692
+ return { lines: [...sdkImports(), ...lines], fields };
697
693
  };
698
694
 
699
695
  /**
700
- * A plain module reduced to what other modules may still import from it once its code and state have
701
- * moved to the generated modules: its types, the names it re-exports, its literal
702
- * constants, and the service client it creates. Its imports become type imports, which is all the
703
- * declarations left can use.
696
+ * The words no variable of a module can be named, exactly: every other word TypeScript knows,
697
+ * such as `out`, `type` and `of`, names a variable as any name does.
704
698
  */
705
- const typesOnly = (
706
- source: ts.SourceFile,
707
- checker: ts.TypeChecker,
708
- sdk: string,
709
- survives: (symbol: ts.Symbol) => boolean,
710
- ): Mapped => {
711
- const clients = serviceClients(source, checker, sdk);
712
- return joined(
713
- [
714
- ...source.statements.flatMap((statement): Mapped[] => {
715
- if (
716
- ts.isInterfaceDeclaration(statement) ||
717
- ts.isTypeAliasDeclaration(statement) ||
718
- clients.includes(statement)
719
- ) {
720
- return [copied(statement)];
721
- }
722
- if (ts.isImportDeclaration(statement)) {
723
- return statement.importClause?.isTypeOnly ||
724
- (clients.length > 0 && importsSdk(statement))
725
- ? [copied(statement)]
726
- : typeImports(statement, checker, survives);
727
- }
728
- if (ts.isExportDeclaration(statement) && statement.moduleSpecifier) {
729
- return reExports(statement, checker, survives);
730
- }
731
- return [];
732
- }),
733
- ...literalConstants(source, checker),
734
- "export {};",
735
- ],
736
- "\n",
737
- );
738
- };
739
-
740
- /** An import's names that the module they come from still exports, imported as types. */
741
- const typeImports = (
742
- statement: ts.ImportDeclaration,
743
- checker: ts.TypeChecker,
744
- survives: (symbol: ts.Symbol) => boolean,
745
- ): Mapped[] => {
746
- const clause = statement.importClause;
747
- const surviving = (name: ts.Identifier): boolean => {
748
- const symbol = checker.getSymbolAtLocation(name);
749
- return symbol !== undefined && survives(unaliased(checker, symbol));
750
- };
751
- const specifier = statement.moduleSpecifier.getText();
752
- if (!clause) {
753
- return [];
754
- }
755
- const bindings = clause.namedBindings;
756
- const named =
757
- bindings && ts.isNamedImports(bindings)
758
- ? bindings.elements
759
- .filter((element) => surviving(element.name))
760
- .map((element) =>
761
- element.propertyName
762
- ? `${element.propertyName.getText()} as ${element.name.text}`
763
- : element.name.text,
764
- )
765
- : [];
766
- return [
767
- ...(clause.name && surviving(clause.name)
768
- ? [`import type ${clause.name.text} from ${specifier};`]
769
- : []),
770
- ...(bindings && ts.isNamespaceImport(bindings)
771
- ? [`import type * as ${bindings.name.text} from ${specifier};`]
772
- : []),
773
- ...(named.length
774
- ? [`import type { ${named.join(", ")} } from ${specifier};`]
775
- : []),
776
- ].map((line) => from(statement, line));
777
- };
778
-
779
- /** A re-export, without the names the module it names no longer exports. */
780
- const reExports = (
781
- statement: ts.ExportDeclaration,
782
- checker: ts.TypeChecker,
783
- survives: (symbol: ts.Symbol) => boolean,
784
- ): Mapped[] => {
785
- const clause = statement.exportClause;
786
- if (statement.isTypeOnly || !clause || !ts.isNamedExports(clause)) {
787
- return [copied(statement)];
788
- }
789
- const kept = clause.elements.filter((element) => {
790
- const symbol = checker.getSymbolAtLocation(element.name);
791
- return (
792
- element.isTypeOnly ||
793
- (symbol !== undefined && survives(unaliased(checker, symbol)))
794
- );
795
- });
796
- return kept.length
797
- ? [
798
- from(
799
- statement,
800
- `export { ${kept.map((element) => element.getText()).join(", ")} } from ${statement.moduleSpecifier?.getText()};`,
801
- ),
802
- ]
803
- : [];
804
- };
805
-
806
- /** Whether a type is one literal value, or a readonly table of them, as `as const` gives. */
807
- const literalType = (checker: ts.TypeChecker, type: ts.Type): boolean => {
808
- if (type.isLiteral() || type.flags & ts.TypeFlags.BooleanLiteral) {
809
- return true;
810
- }
811
- if (
812
- !(type.flags & ts.TypeFlags.Object) ||
813
- type.getCallSignatures().length ||
814
- type.getConstructSignatures().length
815
- ) {
816
- return false;
817
- }
818
- if (checker.isTupleType(type)) {
819
- return checker
820
- .getTypeArguments(type as ts.TypeReference)
821
- .every((item) => literalType(checker, item));
822
- }
823
- const properties = type.getProperties();
824
- return (
825
- properties.length > 0 &&
826
- !type.getStringIndexType() &&
827
- !type.getNumberIndexType() &&
828
- properties.every((property) => {
829
- const declaration = property.valueDeclaration;
830
- return (
831
- declaration !== undefined &&
832
- ts.isPropertyAssignment(declaration) &&
833
- literalType(checker, checker.getTypeOfSymbol(property))
834
- );
835
- })
836
- );
837
- };
838
-
839
- /** A module-level const of this module whose type is a literal value: what a cut-down module still exports of its values. */
840
- const literalConstant = (
841
- checker: ts.TypeChecker,
842
- symbol: ts.Symbol,
843
- ): ts.VariableDeclaration | undefined => {
844
- const declaration = symbol.valueDeclaration;
845
- return declaration &&
846
- ts.isVariableDeclaration(declaration) &&
847
- ts.isIdentifier(declaration.name) &&
848
- ts.isVariableStatement(declaration.parent.parent) &&
849
- ts.isSourceFile(declaration.parent.parent.parent) &&
850
- declaration.parent.flags & ts.NodeFlags.Const &&
851
- literalType(checker, checker.getTypeAtLocation(declaration.name))
852
- ? declaration
853
- : undefined;
854
- };
855
-
856
- /**
857
- * A module's exported constants of one literal value, declared without a value: a server's schema
858
- * can size a wire field by one, and reads that size from its type.
859
- */
860
- const literalConstants = (
861
- source: ts.SourceFile,
862
- checker: ts.TypeChecker,
863
- ): Mapped[] => {
864
- const module = checker.getSymbolAtLocation(source);
865
- if (!module) {
866
- return [];
867
- }
868
- return checker.getExportsOfModule(module).flatMap((exported) => {
869
- // A name re-exported from another module is that module's to declare.
870
- const local = exported.declarations?.some(
871
- (declaration) =>
872
- declaration.getSourceFile() === source &&
873
- !(
874
- ts.isExportSpecifier(declaration) &&
875
- declaration.parent.parent.moduleSpecifier
876
- ),
877
- );
878
- const declaration =
879
- local && literalConstant(checker, unaliased(checker, exported));
880
- if (!declaration || declaration.getSourceFile() !== source) {
881
- return [];
882
- }
883
- const type = checker.typeToString(
884
- checker.getTypeAtLocation(declaration.name),
885
- undefined,
886
- ts.TypeFormatFlags.NoTruncation,
887
- );
888
- return [
889
- from(
890
- declaration,
891
- exported.name === "default"
892
- ? `declare const tsplcDefault: ${type};\nexport default tsplcDefault;`
893
- : `export declare const ${exported.name}: ${type};`,
894
- ),
895
- ];
896
- });
897
- };
898
-
899
- /** A module's statements that create the service client. */
900
- const serviceClients = (
901
- source: ts.SourceFile,
902
- checker: ts.TypeChecker,
903
- sdk: string,
904
- ): ts.Statement[] =>
905
- source.statements.filter(
906
- (statement) =>
907
- ts.isVariableStatement(statement) &&
908
- statement.declarationList.declarations.every(
909
- (declaration) =>
910
- declaration.initializer &&
911
- ts.isCallExpression(declaration.initializer) &&
912
- namesSdk(
913
- checker,
914
- sdk,
915
- declaration.initializer.expression,
916
- "createServiceClient",
917
- ),
918
- ),
919
- );
920
-
921
- /** Whether an import names one of the SDK's modules, which every module can import. */
922
- const importsSdk = (statement: ts.ImportDeclaration): boolean => {
923
- const specifier = statement.moduleSpecifier;
924
- return (
925
- ts.isStringLiteral(specifier) &&
926
- Object.values(sdkModules).some((module) => module === specifier.text)
927
- );
928
- };
699
+ const reservedWords: ReadonlySet<string> = new Set([
700
+ "arguments",
701
+ "await",
702
+ "break",
703
+ "case",
704
+ "catch",
705
+ "class",
706
+ "const",
707
+ "continue",
708
+ "debugger",
709
+ "default",
710
+ "delete",
711
+ "do",
712
+ "else",
713
+ "enum",
714
+ "eval",
715
+ "export",
716
+ "extends",
717
+ "false",
718
+ "finally",
719
+ "for",
720
+ "function",
721
+ "if",
722
+ "implements",
723
+ "import",
724
+ "in",
725
+ "instanceof",
726
+ "interface",
727
+ "let",
728
+ "new",
729
+ "null",
730
+ "package",
731
+ "private",
732
+ "protected",
733
+ "public",
734
+ "return",
735
+ "static",
736
+ "super",
737
+ "switch",
738
+ "this",
739
+ "throw",
740
+ "true",
741
+ "try",
742
+ "typeof",
743
+ "var",
744
+ "void",
745
+ "while",
746
+ "with",
747
+ "yield",
748
+ ]);
929
749
 
930
750
  /** An elaboration failure as a diagnostic, at the node specialization stopped at when it knows one. */
931
751
  const failure = (
@@ -974,23 +794,22 @@ const findEntry = (
974
794
  };
975
795
 
976
796
  /**
977
- * Each root's storage module. Roots in different modules can share a name, up to case, and would
978
- * then share one module and its list; each of them is qualified by its own module instead. The
979
- * config's `io` names a root by its binding name, which then names none of them, so that is refused.
797
+ * The generated modules: each root's storage module, and the module of generated types. A root's
798
+ * module has the root's name, which io and the HMI reach its storage by, so the types module is
799
+ * the one that gives way to a root named like it.
800
+ *
801
+ * Roots in different modules can share a name, up to case, and would then share one module and its
802
+ * list; each of them is qualified by its own module instead. The config's `io` names a root by its
803
+ * binding name, which then names none of them, so that is refused.
980
804
  */
981
- const rootModules = (
805
+ const generatedModules = (
982
806
  roots: readonly Root[],
983
807
  {
984
808
  directory,
985
809
  root: projectRoot,
986
810
  bound,
987
811
  }: { directory: string; root: string; bound: ReadonlySet<string> },
988
- ): ((item: Root) => string) => {
989
- const counts = new Map<string, number>();
990
- for (const item of roots) {
991
- const key = item.name.toLowerCase();
992
- counts.set(key, (counts.get(key) ?? 0) + 1);
993
- }
812
+ ): { root: (item: Root) => string; types: string } => {
994
813
  const shareName = (item: Root) =>
995
814
  roots.filter(
996
815
  (other) => other.name.toLowerCase() === item.name.toLowerCase(),
@@ -1011,11 +830,22 @@ const rootModules = (
1011
830
  }),
1012
831
  );
1013
832
  }
1014
- return (item) => {
1015
- const shared = (counts.get(item.name.toLowerCase()) ?? 0) > 1;
1016
- const name = shared
1017
- ? `${item.name}_${identityDigest(modulePath(projectRoot, item.file))}`
1018
- : item.name;
1019
- return `${directory}/${name}.ts`;
833
+ const qualified = (item: Root): string => {
834
+ const module = modulePath(projectRoot, item.file);
835
+ const sharing = shareName(item);
836
+ if (sharing.length === 1) {
837
+ return item.name;
838
+ }
839
+ // Two roots of one module differ only in their capitals, which a file's name can't tell apart.
840
+ // The last of them keeps the name the module alone gives, as it always had; the others add their own.
841
+ const twins = sharing.filter((other) => other.file === item.file);
842
+ return twins.at(-1) === item
843
+ ? `${item.name}_${identityDigest(module)}`
844
+ : `${item.name}_${identityDigest(`${module}\0${item.name}`)}`;
845
+ };
846
+ const taken = new Set(roots.map((item) => qualified(item).toLowerCase()));
847
+ return {
848
+ root: (item) => `${directory}/${qualified(item)}.ts`,
849
+ types: `${directory}/${unusedName("types", (name) => taken.has(name))}.ts`,
1020
850
  };
1021
851
  };