@tsplc/typegen 0.5.13 → 0.5.15

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.
@@ -1,87 +1,79 @@
1
- import { readdir, readFile } from "node:fs/promises";
2
- import { basename, join } from "node:path";
3
1
  import type { Publication } from "@tsplc/config";
4
- import { type ElementaryType, elementaryTypesByName } from "@tsplc/iec";
5
- import { identifierPattern } from "@tsplc/iec/st";
6
2
  import {
7
- constantResolver,
8
- integerExpression,
9
- isNumberInteger,
10
- } from "./constants";
3
+ elementaryType,
4
+ elementaryTypesByName,
5
+ fitsNumber,
6
+ isIntegerValued,
7
+ isWholeValue,
8
+ stringTypeText,
9
+ type WholeValueType,
10
+ } from "@tsplc/iec";
11
+ import { identifierPattern } from "@tsplc/iec/st";
12
+ import { stFiles } from "../files";
13
+ import { isIntegerConstant } from "./constants";
11
14
  import {
12
15
  type Declaration,
13
16
  type GlobalList,
14
- parseDeclarations,
15
- parseGlobals,
16
- type Source,
17
+ parseSources,
17
18
  type TypeReference,
18
19
  } from "./parser";
20
+ import { resolveDeclarations } from "./resolution";
21
+
22
+ export { stFiles } from "../files";
19
23
 
20
24
  export interface GenerateOptions {
21
25
  /** Directory searched recursively, or an explicit list of TYPE source files. */
22
26
  types: string | readonly string[];
23
27
  /** Directory or explicit GVL files; each list is named after its .st filename. */
24
- globals?: string | readonly string[];
25
- /** Inferred contracts select published globals and supported integer constants. */
26
- publishedGlobalsOnly?: boolean;
27
- publication?: Publication;
28
+ globals: string | readonly string[];
29
+ /**
30
+ * An inferred contract's publication: only the globals it names are emitted, with the
31
+ * integer constants a host can use. Without one every global and constant is emitted.
32
+ */
33
+ publication: Publication | null;
28
34
  /**
29
35
  * Also emit TypeScript declarations for the PLC's types, enums, constants and globals.
30
36
  * Turn off when host code imports them from the TypeScript program itself; the field and
31
37
  * symbol tables are still emitted, because TypeScript types don't exist at runtime.
32
38
  */
33
- declarations?: boolean;
39
+ declarations: boolean;
34
40
  }
35
41
 
36
- /** The TypeScript type a scalar is read as; the 64-bit date and time types have none. */
37
- const scalarType = (type: ElementaryType) => {
38
- switch (type.family) {
39
- case "bool":
40
- return "boolean";
41
- case "integer":
42
- case "bits":
43
- return type.bits === 64 ? "bigint" : "number";
44
- case "real":
45
- return "number";
46
- case "duration":
47
- case "date":
48
- case "timeOfDay":
49
- case "dateTime":
50
- return type.bits === 32 ? "number" : undefined;
51
- case "char":
52
- case "string":
53
- return undefined;
42
+ /** The TypeScript type a scalar is read as. */
43
+ const scalarType = (type: WholeValueType) => {
44
+ if (type.family === "bool") {
45
+ return "boolean";
54
46
  }
47
+ return isIntegerValued(type) && !fitsNumber(type) ? "bigint" : "number";
55
48
  };
56
49
 
57
50
  const scalars: Record<string, string> = Object.fromEntries(
58
- [...elementaryTypesByName].flatMap(([name, type]) => {
59
- const typescript = scalarType(type);
60
- return typescript ? [[name, typescript]] : [];
61
- }),
51
+ [...elementaryTypesByName].flatMap(([name, type]) =>
52
+ isWholeValue(type) ? [[name, scalarType(type)]] : [],
53
+ ),
62
54
  );
63
55
 
64
- /** Recursively lists .st files in name order. */
65
- export async function stFiles(directory: string): Promise<string[]> {
66
- const entries = await readdir(directory, { withFileTypes: true });
67
- const paths = await Promise.all(
68
- entries
69
- .sort((a, b) => {
70
- if (a.name === b.name) {
71
- return 0;
72
- }
73
- return a.name < b.name ? -1 : 1;
74
- })
75
- .map(async (entry) => {
76
- const file = join(directory, entry.name);
77
- if (entry.isDirectory()) {
78
- return stFiles(file);
79
- }
80
- return entry.isFile() && /\.st$/i.test(file) ? [file] : [];
81
- }),
56
+ const sourceFiles = async (setting: string | readonly string[]) =>
57
+ typeof setting === "string" ? stFiles(setting) : setting;
58
+
59
+ /** The names the contract exports besides the PLC's own declarations. */
60
+ const contractNames = {
61
+ field: "PlcField",
62
+ globals: "PlcGlobals",
63
+ typeFields: "typeFields",
64
+ globalVariableLists: "globalVariableLists",
65
+ symbols: "symbols",
66
+ publication: "publication",
67
+ } as const;
68
+
69
+ /** The module-private field list of the declaration at `index` in emission order. */
70
+ const fieldList = (index: number) => `_fields${index}`;
71
+ const isFieldList = (name: string) => /^_fields\d+$/.test(name);
72
+
73
+ const javascriptReserved =
74
+ "break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield let static implements interface package private protected public await arguments eval".split(
75
+ " ",
82
76
  );
83
- return paths.flat();
84
- }
85
77
 
86
78
  const quote = (value: string) => JSON.stringify(value);
87
79
  const documentation = (value: string) =>
@@ -89,40 +81,23 @@ const documentation = (value: string) =>
89
81
  ? `/** ${value.replace(/\*\//g, "* /").replace(/\r?\n/g, "\n * ")} */\n`
90
82
  : "";
91
83
 
92
- function unique<T extends { name: string; source: string }>(
93
- items: T[],
94
- ): Map<string, T> {
95
- const result = new Map<string, T>();
96
- for (const item of items) {
97
- const key = item.name.toUpperCase();
98
- if (result.has(key)) {
84
+ function assertUniqueNames(items: readonly { name: string; source: string }[]) {
85
+ const seen = new Map<string, string>();
86
+ for (const { name, source } of items) {
87
+ const key = name.toUpperCase();
88
+ const previous = seen.get(key);
89
+ if (previous !== undefined) {
99
90
  throw new Error(
100
- `${item.source}: duplicate declaration ${item.name} (also in ${result.get(key)?.source})`,
91
+ `${source}: duplicate declaration ${name} (also in ${previous})`,
101
92
  );
102
93
  }
103
- result.set(key, item);
94
+ seen.set(key, source);
104
95
  }
105
- return result;
106
96
  }
107
97
 
108
- /** Reads files concurrently, so they can be parsed in order and the first invalid one is reported. */
109
- const readSources = (files: readonly string[]): Promise<Source[]> =>
110
- Promise.all(
111
- files.map(async (name) => ({ name, text: await readFile(name, "utf8") })),
112
- );
113
-
114
98
  export async function generateTypes(options: GenerateOptions): Promise<string> {
115
- const typeFiles =
116
- typeof options.types === "string"
117
- ? await stFiles(options.types)
118
- : options.types;
119
- const declarations = (await readSources(typeFiles)).flatMap((source) =>
120
- parseDeclarations(source),
121
- );
122
- const globalFiles =
123
- typeof options.globals === "string"
124
- ? await stFiles(options.globals)
125
- : (options.globals ?? []);
99
+ const typeFiles = await sourceFiles(options.types);
100
+ const globalFiles = await sourceFiles(options.globals);
126
101
  // Program-only projects have a valid empty export selection. Directory
127
102
  // discovery still rejects empty input rather than hiding a bad setting.
128
103
  if (
@@ -134,28 +109,36 @@ export async function generateTypes(options: GenerateOptions): Promise<string> {
134
109
  `no .st declarations found in ${typeof options.types === "string" ? options.types : "the selected source files"}`,
135
110
  );
136
111
  }
137
- const globals = (await readSources(globalFiles)).map((source) =>
138
- parseGlobals(source, basename(source.name).replace(/\.st$/i, "")),
139
- );
140
- const publishedGlobalsOnly = options.publishedGlobalsOnly ?? false;
112
+ const { types: declarations, globals } = await parseSources({
113
+ types: typeFiles,
114
+ globals: globalFiles,
115
+ });
116
+ const { publication } = options;
141
117
  const contract = emit(
142
118
  declarations,
143
- publishedGlobalsOnly ? published(globals, options.publication) : globals,
144
- { publishedGlobalsOnly, emitDeclarations: options.declarations ?? true },
119
+ publication ? published(globals, publication) : globals,
120
+ {
121
+ publishedGlobalsOnly: publication !== null,
122
+ emitDeclarations: options.declarations,
123
+ },
145
124
  );
146
- return options.publication
147
- ? `${contract}\nexport const publication = ${JSON.stringify(options.publication, null, 2)} as const;\n`
125
+ return publication
126
+ ? `${contract}\nexport const ${contractNames.publication} = ${JSON.stringify(publication, null, 2)} as const;\n`
148
127
  : contract;
149
128
  }
150
129
 
151
130
  /**
152
131
  * Constant lists stay whole; a variable list keeps the members the publication names,
153
- * or without one those a symbol attribute publishes, and is dropped when none remain.
132
+ * and is dropped when none remain.
154
133
  */
155
134
  function published(
156
135
  globals: GlobalList[],
157
- publication: Publication | undefined,
136
+ publication: Publication,
158
137
  ): GlobalList[] {
138
+ const selected = new Set([
139
+ ...publication.production,
140
+ ...publication.development,
141
+ ]);
159
142
  return globals
160
143
  .map((list) =>
161
144
  list.constant
@@ -163,12 +146,7 @@ function published(
163
146
  : {
164
147
  ...list,
165
148
  members: list.members.filter((member) =>
166
- publication
167
- ? [
168
- ...publication.production,
169
- ...publication.development,
170
- ].includes(`${list.name}.${member.name}`)
171
- : member.symbol !== undefined,
149
+ selected.has(`${list.name}.${member.name}`),
172
150
  ),
173
151
  },
174
152
  )
@@ -183,57 +161,32 @@ function emit(
183
161
  emitDeclarations,
184
162
  }: { publishedGlobalsOnly: boolean; emitDeclarations: boolean },
185
163
  ): string {
186
- const types = unique(declarations);
187
- unique(globals);
164
+ assertUniqueNames(declarations);
165
+ assertUniqueNames(globals);
188
166
  const constants = globals.filter((list) => list.constant);
189
- // Keep integer constants useful to host clients, including declaration bounds.
190
167
  // Private block presets and labels cannot use this integer-only export format.
191
- // Their declarations still remain available to the lazy bound resolver below.
192
168
  const constantLists = publishedGlobalsOnly
193
169
  ? constants
194
170
  .map((list) => ({
195
171
  ...list,
196
- members: list.members.filter(
197
- (member) =>
198
- member.type.kind === "named" &&
199
- isNumberInteger(member.type.name.toUpperCase()),
200
- ),
172
+ members: list.members.filter(isIntegerConstant),
201
173
  }))
202
174
  .filter((list) => list.members.length)
203
175
  : constants;
204
176
  const variableLists = globals.filter((list) => !list.constant);
205
- const constant = constantResolver(constants);
177
+ const { constant, integer, declaration, aliasTarget, bounds, enumMembers } =
178
+ resolveDeclarations({ types: declarations, globals });
206
179
 
207
- function bound(expression: string): number {
208
- return integerExpression(expression, (name) => constant(name, null));
209
- }
210
- function dimensions(type: Extract<TypeReference, { kind: "array" }>) {
211
- return type.dimensions.map(({ lower, upper }) => {
212
- const start = bound(lower);
213
- const end = bound(upper);
214
- if (end < start || !Number.isSafeInteger(end - start + 1)) {
215
- throw new Error(`invalid array bounds ${lower}..${upper}`);
216
- }
217
- return { start, end };
218
- });
219
- }
220
- function declaration(name: string): Declaration {
221
- const found = types.get(name.toUpperCase());
222
- if (!found) {
223
- throw new Error(`unknown IEC type ${name}`);
224
- }
225
- return found;
226
- }
227
180
  function tsType(type: TypeReference): string {
228
181
  if (type.kind === "array") {
229
- dimensions(type);
182
+ bounds(type);
230
183
  return type.dimensions.reduce(
231
184
  (child) => `Array<${child}>`,
232
185
  tsType(type.element),
233
186
  );
234
187
  }
235
188
  if (type.kind === "string") {
236
- const length = bound(type.length);
189
+ const length = integer(type.length);
237
190
  if (length < 1) {
238
191
  throw new Error(`invalid ${type.name} length ${length}`);
239
192
  }
@@ -242,25 +195,25 @@ function emit(
242
195
  return scalars[type.name.toUpperCase()] ?? declaration(type.name).name;
243
196
  }
244
197
  function resolved(type: TypeReference): TypeReference {
245
- if (type.kind !== "named" || scalars[type.name.toUpperCase()]) {
246
- return type;
198
+ const target = aliasTarget(type);
199
+ if (target.kind !== "named" || scalars[target.name.toUpperCase()]) {
200
+ return target;
247
201
  }
248
- const definition = declaration(type.name);
249
- if (definition.kind === "alias") {
250
- return resolved(definition.type);
251
- }
252
- if (definition.kind === "enum") {
253
- return { kind: "named", name: definition.base };
254
- }
255
- return type;
202
+ const definition = declaration(target.name);
203
+ return definition.kind === "enum"
204
+ ? { kind: "named", name: definition.base }
205
+ : target;
256
206
  }
257
207
  function iecType(type: TypeReference): string {
258
208
  const actual = resolved(type);
259
209
  if (actual.kind === "string") {
260
- return `${actual.name}(${bound(actual.length)})`;
210
+ return stringTypeText({
211
+ wide: actual.name === "WSTRING",
212
+ capacity: integer(actual.length),
213
+ });
261
214
  }
262
215
  if (actual.kind === "array") {
263
- return `ARRAY[${dimensions(actual)
216
+ return `ARRAY[${bounds(actual)
264
217
  .map(({ start, end }) => `${start}..${end}`)
265
218
  .join(", ")}] OF ${iecType(actual.element)}`;
266
219
  }
@@ -306,11 +259,10 @@ function emit(
306
259
  }
307
260
  declarations.forEach(visit);
308
261
 
309
- const reserved = new Set(
310
- "break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield let static implements interface package private protected public await arguments eval PlcGlobals PlcField typeFields symbols globalVariableLists publication".split(
311
- " ",
312
- ),
313
- );
262
+ const reserved = new Set<string>([
263
+ ...javascriptReserved,
264
+ ...Object.values(contractNames),
265
+ ]);
314
266
  for (const name of [
315
267
  ...declarations.map((type) => type.name),
316
268
  ...constantLists.map((list) => list.name),
@@ -318,13 +270,12 @@ function emit(
318
270
  if (
319
271
  !identifierPattern.test(name) ||
320
272
  reserved.has(name) ||
321
- /^_fields\d+$/.test(name)
273
+ isFieldList(name)
322
274
  ) {
323
275
  throw new Error(`name cannot be exported to TypeScript: ${name}`);
324
276
  }
325
277
  reserved.add(name);
326
278
  }
327
- const indexes = new Map(ordered.map((type, index) => [type.name, index]));
328
279
  function complex(type: TypeReference): boolean {
329
280
  const actual = resolved(type);
330
281
  if (actual.kind === "array") {
@@ -351,14 +302,14 @@ function emit(
351
302
  ): string {
352
303
  const actual = resolved(type);
353
304
  if (actual.kind === "named" && complex(actual)) {
354
- const children = `_fields${indexes.get(declaration(actual.name).name)}`;
305
+ const children = fieldList(ordered.indexOf(declaration(actual.name)));
355
306
  if (path === '""') {
356
307
  return children;
357
308
  }
358
309
  return `${children}.map((member) => ({ ...member, field: ${path} + "." + member.field }))`;
359
310
  }
360
311
  if (actual.kind === "array" && (complex(actual.element) || keyed(type))) {
361
- const ranges = dimensions(actual);
312
+ const ranges = bounds(actual);
362
313
  const coordinates = ranges.map(
363
314
  (range, index) => `String(i${depth}_${index} + (${range.start}))`,
364
315
  );
@@ -375,9 +326,9 @@ function emit(
375
326
  const declare = (text: string) => (emitDeclarations ? [text] : []);
376
327
  const output = [
377
328
  "// Generated by @tsplc/typegen. Edit the PLC sources and regenerate.\n",
378
- "export interface PlcField { field: string; type: string; description: string; }\n",
329
+ `export interface ${contractNames.field} { field: string; type: string; description: string; }\n`,
379
330
  ];
380
- for (const type of ordered) {
331
+ for (const [index, type] of ordered.entries()) {
381
332
  try {
382
333
  const doc = documentation(type.description);
383
334
  if (type.kind === "struct") {
@@ -387,7 +338,7 @@ function emit(
387
338
  ),
388
339
  );
389
340
  output.push(
390
- `const _fields${indexes.get(type.name)}: PlcField[] = [\n${type.members.map((member) => `...${fields(member.type, quote(member.name), member.description)},`).join("\n")}\n];\n`,
341
+ `const ${fieldList(index)}: ${contractNames.field}[] = [\n${type.members.map((member) => `...${fields(member.type, quote(member.name), member.description)},`).join("\n")}\n];\n`,
391
342
  );
392
343
  } else if (type.kind === "alias") {
393
344
  output.push(
@@ -396,32 +347,20 @@ function emit(
396
347
  ),
397
348
  );
398
349
  output.push(
399
- `const _fields${indexes.get(type.name)}: PlcField[] = ${fields({ kind: "named", name: type.name }, '""', type.description)};\n`,
350
+ `const ${fieldList(index)}: ${contractNames.field}[] = ${fields({ kind: "named", name: type.name }, '""', type.description)};\n`,
400
351
  );
401
352
  } else {
402
- if (!isNumberInteger(type.base)) {
353
+ if (!fitsNumber(elementaryType(type.base))) {
403
354
  throw new Error(`unsupported enum base ${type.base}`);
404
355
  }
405
- const entries = new Map<string, number>();
406
- for (const member of type.members) {
407
- const previous = [...entries.values()].at(-1) ?? -1;
408
- const value =
409
- member.value === undefined
410
- ? previous + 1
411
- : integerExpression(
412
- member.value,
413
- (name) =>
414
- entries.get(name.toUpperCase()) ?? constant(name, null),
415
- );
416
- entries.set(member.name.toUpperCase(), value);
417
- }
356
+ const members = enumMembers(type);
418
357
  output.push(
419
358
  ...declare(
420
- `${doc}export const ${type.name} = { ${type.members.map((member) => `${quote(member.name)}: ${entries.get(member.name.toUpperCase())}`).join(", ")} } as const;\nexport type ${type.name} = (typeof ${type.name})[keyof typeof ${type.name}];\n`,
359
+ `${doc}export const ${type.name} = { ${members.map(({ name, value }) => `${quote(name)}: ${value}`).join(", ")} } as const;\nexport type ${type.name} = (typeof ${type.name})[keyof typeof ${type.name}];\n`,
421
360
  ),
422
361
  );
423
362
  output.push(
424
- `const _fields${indexes.get(type.name)}: PlcField[] = ${fields({ kind: "named", name: type.base }, '""', type.description)};\n`,
363
+ `const ${fieldList(index)}: ${contractNames.field}[] = ${fields({ kind: "named", name: type.base }, '""', type.description)};\n`,
425
364
  );
426
365
  }
427
366
  } catch (error) {
@@ -446,9 +385,9 @@ function emit(
446
385
  ]),
447
386
  );
448
387
  output.push(
449
- `export const typeFields = {\n${[
388
+ `export const ${contractNames.typeFields} = {\n${[
450
389
  ...ordered.map(
451
- (type) => `${quote(type.name)}: _fields${indexes.get(type.name)},`,
390
+ (type, index) => `${quote(type.name)}: ${fieldList(index)},`,
452
391
  ),
453
392
  ...[...inlineArrays].map(
454
393
  ([type, members]) => `${quote(type)}: ${members},`,
@@ -462,14 +401,14 @@ function emit(
462
401
  }
463
402
  output.push(
464
403
  ...declare(
465
- `export interface PlcGlobals {\n${variableLists.map((list) => `${documentation(list.description)}${quote(list.name)}: {\n${list.members.map((member) => `${documentation(member.description)}${quote(member.name)}: ${tsType(member.type)};`).join("\n")}\n};`).join("\n")}\n}\n`,
404
+ `export interface ${contractNames.globals} {\n${variableLists.map((list) => `${documentation(list.description)}${quote(list.name)}: {\n${list.members.map((member) => `${documentation(member.description)}${quote(member.name)}: ${tsType(member.type)};`).join("\n")}\n};`).join("\n")}\n}\n`,
466
405
  ),
467
406
  );
468
407
  output.push(
469
- `export const globalVariableLists = ${JSON.stringify(Object.fromEntries(variableLists.map((list) => [list.name, list.description])), null, "\t")} as const;\n`,
408
+ `export const ${contractNames.globalVariableLists} = ${JSON.stringify(Object.fromEntries(variableLists.map((list) => [list.name, list.description])), null, "\t")} as const;\n`,
470
409
  );
471
410
  output.push(
472
- `export const symbols = ${JSON.stringify(
411
+ `export const ${contractNames.symbols} = ${JSON.stringify(
473
412
  variableLists.flatMap((list) =>
474
413
  list.members.map((member) => ({
475
414
  name: member.name,