@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.
@@ -10,6 +10,7 @@ import {
10
10
  import type { CapturedValue } from "./capture-protocol";
11
11
  import { ModuleImports } from "./imports";
12
12
  import { isExported, type Model, type ModelNode, unionMembers } from "./model";
13
+ import { type Names, rootFieldNames } from "./names";
13
14
  import { SpecializeError } from "./values";
14
15
 
15
16
  /** IEC names a program can write as types; they keep their width rather than becoming DINT. */
@@ -95,10 +96,10 @@ export class Layouts {
95
96
  * may import beside the generated ones, and the namespaces storage modules are imported as.
96
97
  */
97
98
  private readonly takenNames: Set<string>;
98
- /** Enums the declarations need from kept modules. */
99
- readonly imports = new ModuleImports();
99
+ /** Enums the declarations need from the program's modules. */
100
+ readonly imports: ModuleImports;
100
101
  /** Types the declarations need from kept modules. */
101
- readonly typeImports = new ModuleImports();
102
+ readonly typeImports: ModuleImports;
102
103
  private readonly enums = new Map<string, LiteralEnum>();
103
104
  private readonly records = new Map<string, string>();
104
105
  private readonly names = new Map<string, number>();
@@ -120,7 +121,16 @@ export class Layouts {
120
121
  keptSources: readonly ts.SourceFile[],
121
122
  /** The stored layout of a class instance or an array of them, which storage, built on these layouts, gives. */
122
123
  private readonly instanceState: (node: ModelNode) => string | undefined,
124
+ private readonly moduleNames: Names,
125
+ /** Why the generated modules can't import an enum from the module that declares it; undefined when they can. */
126
+ private readonly enumRefusal: (
127
+ declaration: ts.EnumDeclaration,
128
+ ) => string | undefined,
123
129
  ) {
130
+ // Each is imported into every root's storage module, beside that root's fields.
131
+ const fields = rootFieldNames(model);
132
+ this.imports = new ModuleImports(moduleNames, fields);
133
+ this.typeImports = new ModuleImports(moduleNames, fields);
124
134
  // Storage imports a root's module under its capitalized name, unless the program names a type so.
125
135
  const typeNames = new Set(
126
136
  model.program
@@ -174,9 +184,15 @@ export class Layouts {
174
184
  const count = this.names.get(base) ?? 0;
175
185
  this.names.set(base, count + 1);
176
186
  const name = count ? `${base}_${count + 1}` : base;
177
- return this.declarations.has(name) || this.takenNames.has(name)
178
- ? this.unique(base)
179
- : name;
187
+ if (
188
+ this.declarations.has(name) ||
189
+ this.takenNames.has(name) ||
190
+ this.moduleNames.importedAs(name)
191
+ ) {
192
+ return this.unique(base);
193
+ }
194
+ this.moduleNames.declare(name);
195
+ return name;
180
196
  }
181
197
 
182
198
  /**
@@ -627,14 +643,19 @@ export class Layouts {
627
643
  return this.typeImports.add(file, symbol.name);
628
644
  }
629
645
 
646
+ /**
647
+ * The name generated code reads a TypeScript enum by: its own, imported from the module that
648
+ * declares it, so the PLC, the server and the program's own modules share one enum.
649
+ */
630
650
  private enumName(declaration: ts.EnumDeclaration): string {
631
- const file = declaration.getSourceFile().fileName;
632
- if (!this.kept(file)) {
633
- throw new Error(
634
- `${declaration.name.text}: declare PLC enums in a module of enums and constants, so the server and PLC share them.`,
635
- );
651
+ const refusal = this.enumRefusal(declaration);
652
+ if (refusal) {
653
+ throw new SpecializeError(declaration.name, refusal);
636
654
  }
637
- return this.imports.add(file, declaration.name.text);
655
+ return this.imports.add(
656
+ declaration.getSourceFile().fileName,
657
+ declaration.name.text,
658
+ );
638
659
  }
639
660
 
640
661
  /** `Record<Enum, T>`: an object type whose properties are exactly an enum's members. */
@@ -793,10 +814,12 @@ export class Layouts {
793
814
  ): string {
794
815
  return this.checker
795
816
  .getPropertiesOfType(type)
796
- .map(
797
- (property) =>
798
- `${property.name}: ${this.declaredText(property.valueDeclaration, this.checker.getTypeOfSymbol(property), captured(property.name) ?? this.fieldSample(property), pascalCase(property.name))};`,
799
- )
817
+ .map((property) => {
818
+ if (!plainName(property.name)) {
819
+ throw quotedField(property.valueDeclaration, property.name);
820
+ }
821
+ return `${property.name}: ${this.declaredText(property.valueDeclaration, this.checker.getTypeOfSymbol(property), captured(property.name) ?? this.fieldSample(property), pascalCase(property.name))};`;
822
+ })
800
823
  .join(" ");
801
824
  }
802
825
  }
@@ -958,20 +981,24 @@ const isReadonlyArray = (type: ts.Type): boolean =>
958
981
  const enumKey = (members: readonly string[]): string =>
959
982
  [...members].sort().join("|");
960
983
 
961
- /** `base`, or else the first of `base_2`, `base_3`… that `taken` does not hold. */
962
- export const unusedName = (
963
- base: string,
964
- taken: (name: string) => boolean,
965
- ): string => {
966
- if (!taken(base)) {
967
- return base;
968
- }
969
- for (let index = 2; ; index++) {
970
- const name = `${base}_${index}`;
971
- if (!taken(name)) {
972
- return name;
973
- }
974
- }
984
+ /** Whether a field's name is one a PLC variable or record field can have: a plain name, or a table's number. */
985
+ export const plainName = (name: string): boolean =>
986
+ /^(\d+|[\p{ID_Start}_$][\p{ID_Continue}$]*)$/u.test(name);
987
+
988
+ /** The refusal of a field whose name had to be quoted, at the field. */
989
+ export const quotedField = (
990
+ declaration: ts.Node | undefined,
991
+ name: string,
992
+ ): Error => {
993
+ const plain = name
994
+ .replace(/[^A-Za-z0-9_$]+(.)?/g, (_, next: string | undefined) =>
995
+ next ? next.toUpperCase() : "",
996
+ )
997
+ .replace(/^\d/, "_$&");
998
+ const message = `"${name}" can't name a field the PLC stores, which needs a plain name such as ${plain || "field"}. Rename the field.`;
999
+ return declaration
1000
+ ? new SpecializeError(declaration, message)
1001
+ : new Error(message);
975
1002
  };
976
1003
 
977
1004
  /** A string literal as an enum member name. */
@@ -49,6 +49,22 @@ export const unionMembers = (type: ts.Type): readonly ts.Type[] =>
49
49
  export const isExported = (declaration: ts.Declaration): boolean =>
50
50
  Boolean(ts.getCombinedModifierFlags(declaration) & ts.ModifierFlags.Export);
51
51
 
52
+ /** Whether a module's export list names its binding `name`: `export { name }`. */
53
+ const listedExport = (source: ts.SourceFile, name: string): boolean =>
54
+ source.statements.some(
55
+ (statement) =>
56
+ ts.isExportDeclaration(statement) &&
57
+ !statement.moduleSpecifier &&
58
+ !statement.isTypeOnly &&
59
+ statement.exportClause !== undefined &&
60
+ ts.isNamedExports(statement.exportClause) &&
61
+ statement.exportClause.elements.some(
62
+ (element) =>
63
+ !element.isTypeOnly &&
64
+ (element.propertyName ?? element.name).text === name,
65
+ ),
66
+ );
67
+
52
68
  /** Each step from a captured object to what it holds, with the value there. */
53
69
  export const children = (captured: CapturedNode): [Step, CapturedValue][] => {
54
70
  if (captured.kind === "array") {
@@ -153,7 +169,10 @@ export class Model {
153
169
  file: binding.file,
154
170
  name: binding.name,
155
171
  declaration,
156
- exported: isExported(declaration) || bound.has(binding.name),
172
+ exported:
173
+ isExported(declaration) ||
174
+ listedExport(this.sourceFile(binding.file), binding.name) ||
175
+ bound.has(binding.name),
157
176
  bound: bound.has(binding.name),
158
177
  value: binding.value,
159
178
  };
@@ -0,0 +1,134 @@
1
+ import ts from "typescript";
2
+ import type { Model } from "./model";
3
+
4
+ /** `base`, or else the first of `base_2`, `base_3`… that `taken` does not hold. */
5
+ export const unusedName = (
6
+ base: string,
7
+ taken: (name: string) => boolean,
8
+ ): string => {
9
+ if (!taken(base)) {
10
+ return base;
11
+ }
12
+ for (let index = 2; ; index++) {
13
+ const name = `${base}_${index}`;
14
+ if (!taken(name)) {
15
+ return name;
16
+ }
17
+ }
18
+ };
19
+
20
+ /**
21
+ * The names the generated modules use at module level: what they declare, and what they import
22
+ * the program's constants, enums, tasks and storage as. Every part of elaboration that makes one up
23
+ * asks here, so two things of one name never meet, whichever modules the program wrote them in.
24
+ *
25
+ * What a generated module declares keeps the name it always had, since a routine's or a type's
26
+ * name reaches the PLC. An import is local to the generated TypeScript, so it is the one renamed.
27
+ */
28
+ export class Names {
29
+ private readonly declared = new Set<string>();
30
+ /** The name each import is read by, by what it imports. */
31
+ private readonly imports = new Map<string, string>();
32
+ private readonly imported = new Set<string>();
33
+
34
+ constructor(
35
+ /** Names the entry module is sure to declare, which no import takes however early it is made. */
36
+ private readonly reserved: ReadonlySet<string>,
37
+ ) {}
38
+
39
+ /** Notes that a generated module declares `name`, which imports made from now on avoid. */
40
+ declare(name: string): void {
41
+ this.declared.add(name);
42
+ }
43
+
44
+ /** Whether an import is read by `name`, which a declaration made after it must then avoid. */
45
+ importedAs(name: string): boolean {
46
+ return this.imported.has(name);
47
+ }
48
+
49
+ /**
50
+ * The name generated code reads an import by: its own, unless that is taken, reserved, or one
51
+ * of `avoided`. `key` says what is imported, so the same thing is read by the same name everywhere.
52
+ */
53
+ import(
54
+ key: string,
55
+ name: string,
56
+ avoided: ReadonlySet<string> = new Set(),
57
+ ): string {
58
+ const known = this.imports.get(key);
59
+ if (known) {
60
+ return known;
61
+ }
62
+ const local = unusedName(
63
+ name,
64
+ (candidate) =>
65
+ this.imported.has(candidate) ||
66
+ this.declared.has(candidate) ||
67
+ this.reserved.has(candidate) ||
68
+ avoided.has(candidate),
69
+ );
70
+ this.imports.set(key, local);
71
+ this.imported.add(local);
72
+ return local;
73
+ }
74
+ }
75
+
76
+ /**
77
+ * The names the entry module is sure to declare under the program's own name for the thing: a
78
+ * module's function that takes no parameters is one routine, named as the function is. A function
79
+ * with parameters may become several routines, each named with a digest, so it reserves nothing.
80
+ */
81
+ export const routineNames = (
82
+ sources: readonly ts.SourceFile[],
83
+ ): Set<string> => {
84
+ const names = new Set<string>();
85
+ for (const source of sources) {
86
+ for (const statement of source.statements) {
87
+ if (
88
+ ts.isFunctionDeclaration(statement) &&
89
+ statement.name &&
90
+ !statement.parameters.length
91
+ ) {
92
+ names.add(statement.name.text);
93
+ }
94
+ if (!ts.isVariableStatement(statement)) {
95
+ continue;
96
+ }
97
+ for (const declaration of statement.declarationList.declarations) {
98
+ const initializer = declaration.initializer;
99
+ if (
100
+ ts.isIdentifier(declaration.name) &&
101
+ initializer &&
102
+ (ts.isArrowFunction(initializer) ||
103
+ ts.isFunctionExpression(initializer)) &&
104
+ !initializer.parameters.length
105
+ ) {
106
+ names.add(declaration.name.text);
107
+ }
108
+ }
109
+ }
110
+ }
111
+ return names;
112
+ };
113
+
114
+ /**
115
+ * The names a root's storage module may declare: one variable for each field of a root record or
116
+ * instance. A storage module imports every enum and type the generated types use, so those give way.
117
+ */
118
+ export const rootFieldNames = (model: Model): Set<string> => {
119
+ const names = new Set<string>();
120
+ for (const root of model.roots) {
121
+ const node = model.node(root.value);
122
+ if (node?.captured.kind === "object") {
123
+ for (const field of Object.keys(node.captured.fields)) {
124
+ names.add(field);
125
+ }
126
+ }
127
+ if (node?.captured.kind === "instance") {
128
+ for (const member of model.fields(model.classOf(node))) {
129
+ names.add(member.name.getText());
130
+ }
131
+ }
132
+ }
133
+ return names;
134
+ };