@tsplc/compiler 0.6.0 → 0.6.1

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.
package/package.json CHANGED
@@ -17,7 +17,7 @@
17
17
  "url": "git+https://github.com/rip-technologies/tsplc.git",
18
18
  "directory": "packages/compiler"
19
19
  },
20
- "version": "0.6.0",
20
+ "version": "0.6.1",
21
21
  "type": "module",
22
22
  "exports": {
23
23
  ".": {
@@ -93,17 +93,17 @@
93
93
  "bun": ">=1.4.3"
94
94
  },
95
95
  "dependencies": {
96
- "@tsplc/agent": "0.6.0",
97
- "@tsplc/build": "0.6.0",
98
- "@tsplc/config": "0.6.0",
99
- "@tsplc/debug": "0.6.0",
100
- "@tsplc/opcua": "0.6.0",
101
- "@tsplc/typegen": "0.6.0",
96
+ "@tsplc/agent": "0.6.1",
97
+ "@tsplc/build": "0.6.1",
98
+ "@tsplc/config": "0.6.1",
99
+ "@tsplc/debug": "0.6.1",
100
+ "@tsplc/opcua": "0.6.1",
101
+ "@tsplc/typegen": "0.6.1",
102
102
  "typescript": "6.0.3",
103
103
  "zod": "4.3.6",
104
104
  "@types/bun": "1.4.2",
105
- "@tsplc/server": "0.6.0",
106
- "@tsplc/iec": "0.6.0"
105
+ "@tsplc/server": "0.6.1",
106
+ "@tsplc/iec": "0.6.1"
107
107
  },
108
108
  "bin": {
109
109
  "tsplc": "./dist/cli.js"
@@ -99,6 +99,8 @@ export class Analyzer {
99
99
  private readonly diagnostics: Diagnostic[],
100
100
  private readonly positions: Positions,
101
101
  serviceRecord: ServiceRecord | null,
102
+ /** Modules elaboration cut down to their declarations: nothing in them is compiled. */
103
+ reduced: ReadonlySet<string>,
102
104
  ) {
103
105
  this.checker = program.getTypeChecker();
104
106
  this.resolver = new TypeResolver(
@@ -142,6 +144,7 @@ export class Analyzer {
142
144
  this.sources = runtimeSources(program).filter(
143
145
  (source) =>
144
146
  source.fileName !== sdk &&
147
+ !reduced.has(source.fileName) &&
145
148
  !inSdk(sdk, source.fileName) &&
146
149
  !program.isSourceFileDefaultLibrary(source) &&
147
150
  (!source.isDeclarationFile || roots.has(source.fileName)),
@@ -31,6 +31,7 @@ import { Model, type Root } from "./model";
31
31
  import { Retention, retentionDeclarations } from "./retention";
32
32
  import { closingBrace, Specializer } from "./specialize";
33
33
  import { SpecializeError } from "./values";
34
+ import { within } from "./writes";
34
35
 
35
36
  /**
36
37
  * A module the compiled program keeps as written: only types, enums, constants, tasks and the
@@ -347,12 +348,15 @@ export const lowerElaboration = (
347
348
  references: NonNullable<PlcModule["references"]>;
348
349
  /** The string each member of a literal union's enum stands for, by `<types file>:<enum>`. */
349
350
  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>;
350
353
  } => {
351
354
  const sources = new Map<string, Mapped>();
352
355
  const diagnostics: Diagnostic[] = [];
353
356
  const origins = new Map<string, { name: string; instance?: string }>();
354
357
  const folded: Folded[] = [];
355
358
  const literals = new Map<string, Record<string, string>>();
359
+ const reduced = new Set<string>();
356
360
  const references: { id: number; path: string }[] = [];
357
361
  const referenceFields: string[] = [];
358
362
  const result = {
@@ -361,6 +365,7 @@ export const lowerElaboration = (
361
365
  origins,
362
366
  folded,
363
367
  literals,
368
+ reduced,
364
369
  references: { objects: references, fields: referenceFields },
365
370
  };
366
371
  const runtime = plcSources(program).filter(
@@ -549,10 +554,30 @@ export const lowerElaboration = (
549
554
  });
550
555
  }
551
556
  }
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
+ };
552
576
  // The plain modules now live in the generated code; keep only their types for type importers.
553
577
  for (const source of runtime) {
554
578
  if (source.fileName !== entryFile && !isKept(source.fileName)) {
555
- sources.set(source.fileName, typesOnly(source, checker, sdk));
579
+ sources.set(source.fileName, typesOnly(source, checker, sdk, survives));
580
+ reduced.add(source.fileName);
556
581
  }
557
582
  }
558
583
  } catch (cause) {
@@ -672,34 +697,205 @@ const storageGlobals = (
672
697
  };
673
698
 
674
699
  /**
675
- * A plain module reduced to the types other modules may import from it, and the service client it
676
- * creates, which scan code calls through this module as it does through a module of constants.
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.
677
704
  */
678
705
  const typesOnly = (
679
706
  source: ts.SourceFile,
680
707
  checker: ts.TypeChecker,
681
708
  sdk: string,
709
+ survives: (symbol: ts.Symbol) => boolean,
682
710
  ): Mapped => {
683
711
  const clients = serviceClients(source, checker, sdk);
684
712
  return joined(
685
713
  [
686
- ...source.statements
687
- .filter(
688
- (statement) =>
689
- ts.isInterfaceDeclaration(statement) ||
690
- ts.isTypeAliasDeclaration(statement) ||
691
- (ts.isImportDeclaration(statement) &&
692
- (statement.importClause?.isTypeOnly ||
693
- (clients.length > 0 && importsSdk(statement)))) ||
694
- clients.includes(statement),
695
- )
696
- .map(copied),
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),
697
734
  "export {};",
698
735
  ],
699
736
  "\n",
700
737
  );
701
738
  };
702
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
+
703
899
  /** A module's statements that create the service client. */
704
900
  const serviceClients = (
705
901
  source: ts.SourceFile,
@@ -223,6 +223,8 @@ function compileFrontend(
223
223
  return { diagnostics: [...diagnostics, ...uses] };
224
224
  }
225
225
  }
226
+ // Only shown when compiling fails, which one of them may explain.
227
+ const lost: Diagnostic[] = [];
226
228
  const lowerings = new LoweringPipeline(program, (program, lowering) => {
227
229
  diagnostics.push(...lowering.diagnostics);
228
230
  for (const source of runtimeSources(program)) {
@@ -256,7 +258,20 @@ function compileFrontend(
256
258
  host,
257
259
  oldProgram: program,
258
260
  });
259
- diagnostics.push(...sourceDiagnostics(lowered, plcFiles(lowered)));
261
+ const plc = plcFiles(lowered);
262
+ diagnostics.push(...sourceDiagnostics(lowered, plc));
263
+ lost.push(
264
+ ...lostImports({
265
+ before: program,
266
+ after: lowered,
267
+ rewritten: lowering.sources,
268
+ plc: new Set(
269
+ [...plc, ...plcFiles(program)].map(({ fileName }) => fileName),
270
+ ),
271
+ root,
272
+ positions,
273
+ }),
274
+ );
260
275
  return lowered;
261
276
  });
262
277
  // A plain program's setup reads the configuration this resolves. The pass runs again below for
@@ -290,7 +305,7 @@ function compileFrontend(
290
305
  );
291
306
  const lowered = lowerings.program;
292
307
  if (!lowered || !elaboration || !services || !promises || !lowering) {
293
- return { diagnostics };
308
+ return { diagnostics: [...diagnostics, ...lost] };
294
309
  }
295
310
  const analyzer = new Analyzer(
296
311
  lowered,
@@ -300,10 +315,13 @@ function compileFrontend(
300
315
  diagnostics,
301
316
  positions,
302
317
  serviceRecords(lowered, services),
318
+ elaboration.reduced,
303
319
  );
304
320
  const module = analyzer.run({ ...options.programs, ...lowering.programs });
305
321
  attachLowerings(module, root, { elaboration, promises, lowering });
306
- return hasErrors(diagnostics) ? { diagnostics } : { module, diagnostics };
322
+ return hasErrors(diagnostics)
323
+ ? { diagnostics: [...diagnostics, ...lost] }
324
+ : { module, diagnostics };
307
325
  }
308
326
 
309
327
  /**
@@ -341,6 +359,102 @@ function storesGeneratedGlobal(
341
359
  return Boolean(source && ts.isSourceFile(source) && generated(source));
342
360
  }
343
361
 
362
+ /** TypeScript's errors for an import that names something its module doesn't export. */
363
+ const missingExportCodes: ReadonlySet<number> = new Set([
364
+ 2305, 2459, 2460, 2614, 2724,
365
+ ]);
366
+
367
+ /** The file an import or re-export's module specifier resolves to, if it resolves to a source file. */
368
+ function importedFile(
369
+ checker: ts.TypeChecker,
370
+ statement: ts.Statement,
371
+ ): string | undefined {
372
+ if (
373
+ !(ts.isImportDeclaration(statement) || ts.isExportDeclaration(statement)) ||
374
+ !statement.moduleSpecifier
375
+ ) {
376
+ return undefined;
377
+ }
378
+ const module = checker.getSymbolAtLocation(
379
+ statement.moduleSpecifier,
380
+ )?.valueDeclaration;
381
+ return module && ts.isSourceFile(module) ? module.fileName : undefined;
382
+ }
383
+
384
+ /**
385
+ * Imports a lowering pass broke in files tsPLC doesn't compile, such as a server's router: the
386
+ * pass rewrote a module and dropped a name the file still imports. Only PLC files' TypeScript
387
+ * errors are reported, so without this a server schema reads the lost name as nothing, and the
388
+ * error surfaces far from its cause. The server itself runs the module as written, so a lost name
389
+ * matters only where tsPLC reads that file's types: these are warnings, shown beside the errors
390
+ * they may explain.
391
+ */
392
+ function lostImports({
393
+ before,
394
+ after,
395
+ rewritten,
396
+ plc,
397
+ root,
398
+ positions,
399
+ }: {
400
+ before: ts.Program;
401
+ after: ts.Program;
402
+ rewritten: ReadonlyMap<string, Mapped>;
403
+ /** The PLC program's files before the pass and after it, whose errors are reported anyway. */
404
+ plc: ReadonlySet<string>;
405
+ root: string;
406
+ positions: Positions;
407
+ }): Diagnostic[] {
408
+ const checker = after.getTypeChecker();
409
+ return after.getSourceFiles().flatMap((file) => {
410
+ const imports = file.statements.flatMap((statement) => {
411
+ const imported = importedFile(checker, statement);
412
+ return imported && rewritten.has(imported)
413
+ ? [{ statement, imported }]
414
+ : [];
415
+ });
416
+ const original = before.getSourceFile(file.fileName);
417
+ if (
418
+ !imports.length ||
419
+ !original ||
420
+ file.isDeclarationFile ||
421
+ plc.has(file.fileName) ||
422
+ rewritten.has(file.fileName)
423
+ ) {
424
+ return [];
425
+ }
426
+ const missing = (program: ts.Program, source: ts.SourceFile) =>
427
+ program
428
+ .getSemanticDiagnostics(source)
429
+ .filter(
430
+ (diagnostic) =>
431
+ missingExportCodes.has(diagnostic.code) &&
432
+ diagnostic.start !== undefined,
433
+ );
434
+ const known = new Set(
435
+ missing(before, original).map(({ start, code }) => `${start}:${code}`),
436
+ );
437
+ return missing(after, file).flatMap(({ start = 0, length = 1, code }) => {
438
+ const broken = imports.find(
439
+ ({ statement }) => statement.pos <= start && start < statement.end,
440
+ );
441
+ if (!broken || known.has(`${start}:${code}`)) {
442
+ return [];
443
+ }
444
+ const name = file.text.slice(start, start + length);
445
+ return [
446
+ {
447
+ origin: "plc" as const,
448
+ code: "PLC1016",
449
+ severity: "warning" as const,
450
+ message: `tsPLC dropped ${name} from ${relative(root, broken.imported)} while compiling the PLC program, but ${relative(root, file.fileName)} imports it, so tsPLC reads that file's types without it. If an error here is in what that file declares, this is its cause, and a tsPLC bug.`,
451
+ span: positions.span(file, start, start + length),
452
+ },
453
+ ];
454
+ });
455
+ });
456
+ }
457
+
344
458
  /** TS2540: "Cannot assign to '…' because it is a read-only property." */
345
459
  const readOnlyAssignment = 2540;
346
460