@tsplc/typegen 0.2.17 → 0.2.19

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,418 +1,466 @@
1
1
  import { readdir, readFile } from "node:fs/promises";
2
2
  import { basename, join } from "node:path";
3
- import { integerExpression } from "./constants";
3
+ import {
4
+ constantResolver,
5
+ integerExpression,
6
+ isNumberInteger,
7
+ } from "./constants";
4
8
  import type { Publication } from "@tsplc/config";
9
+ import { type ElementaryType, elementaryTypesByName } from "@tsplc/iec";
10
+ import { identifierPattern } from "@tsplc/iec/st";
5
11
  import {
6
- type Declaration,
7
- type GlobalList,
8
- type TypeReference,
9
- parseDeclarations,
10
- parseGlobals,
12
+ type Declaration,
13
+ type GlobalList,
14
+ type Source,
15
+ type TypeReference,
16
+ parseDeclarations,
17
+ parseGlobals,
11
18
  } from "./parser";
12
19
 
13
20
  export interface GenerateOptions {
14
- /** Directory searched recursively, or an explicit list of TYPE source files. */
15
- types: string | readonly string[];
16
- /** Directory or explicit GVL files; each list is named after its .st filename. */
17
- globals?: string | readonly string[];
18
- /** Inferred contracts select published globals and supported integer constants. */
19
- publishedGlobalsOnly?: boolean;
20
- publication?: Publication;
21
- /**
22
- * Also emit TypeScript declarations for the PLC's types, enums, constants and globals.
23
- * Turn off when host code imports them from the TypeScript program itself; the field and
24
- * symbol tables are still emitted, because TypeScript types don't exist at runtime.
25
- */
26
- declarations?: boolean;
21
+ /** Directory searched recursively, or an explicit list of TYPE source files. */
22
+ types: string | readonly string[];
23
+ /** 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
+ /**
29
+ * Also emit TypeScript declarations for the PLC's types, enums, constants and globals.
30
+ * Turn off when host code imports them from the TypeScript program itself; the field and
31
+ * symbol tables are still emitted, because TypeScript types don't exist at runtime.
32
+ */
33
+ declarations?: boolean;
27
34
  }
28
35
 
29
- const integerTypePattern = /^(?:U?S?INT|U?DINT|BYTE|WORD|DWORD)$/;
30
-
31
- const scalars: Record<string, string> = {
32
- BOOL: "boolean",
33
- BYTE: "number",
34
- WORD: "number",
35
- DWORD: "number",
36
- LWORD: "bigint",
37
- SINT: "number",
38
- INT: "number",
39
- DINT: "number",
40
- LINT: "bigint",
41
- USINT: "number",
42
- UINT: "number",
43
- UDINT: "number",
44
- ULINT: "bigint",
45
- REAL: "number",
46
- LREAL: "number",
47
- TIME: "number",
48
- TOD: "number",
49
- TIME_OF_DAY: "number",
50
- DATE: "number",
51
- DT: "number",
52
- DATE_AND_TIME: "number",
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;
54
+ }
53
55
  };
54
56
 
57
+ const scalars: Record<string, string> = Object.fromEntries(
58
+ [...elementaryTypesByName].flatMap(([name, type]) => {
59
+ const typescript = scalarType(type);
60
+ return typescript ? [[name, typescript]] : [];
61
+ }),
62
+ );
63
+
55
64
  /** Recursively lists .st files in name order. */
56
65
  export async function stFiles(directory: string): Promise<string[]> {
57
- const entries = await readdir(directory, { withFileTypes: true });
58
- const paths = await Promise.all(
59
- entries
60
- .sort((a, b) => {
61
- if (a.name === b.name) return 0;
62
- return a.name < b.name ? -1 : 1;
63
- })
64
- .map(async (entry) => {
65
- const file = join(directory, entry.name);
66
- if (entry.isDirectory()) return stFiles(file);
67
- return entry.isFile() && /\.st$/i.test(file) ? [file] : [];
68
- }),
69
- );
70
- return paths.flat();
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
+ }),
82
+ );
83
+ return paths.flat();
71
84
  }
72
85
 
73
86
  const quote = (value: string) => JSON.stringify(value);
74
87
  const documentation = (value: string) =>
75
- value ? `/** ${value.replace(/\*\//g, "* /").replace(/\r?\n/g, "\n * ")} */\n` : "";
88
+ value
89
+ ? `/** ${value.replace(/\*\//g, "* /").replace(/\r?\n/g, "\n * ")} */\n`
90
+ : "";
76
91
 
77
- function unique<T extends { name: string; source: string }>(items: T[]): Map<string, T> {
78
- const result = new Map<string, T>();
79
- for (const item of items) {
80
- const key = item.name.toUpperCase();
81
- if (result.has(key))
82
- throw new Error(
83
- `${item.source}: duplicate declaration ${item.name} (also in ${result.get(key)?.source})`,
84
- );
85
- result.set(key, item);
86
- }
87
- return result;
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)) {
99
+ throw new Error(
100
+ `${item.source}: duplicate declaration ${item.name} (also in ${result.get(key)?.source})`,
101
+ );
102
+ }
103
+ result.set(key, item);
104
+ }
105
+ return result;
88
106
  }
89
107
 
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
+
90
114
  export async function generateTypes(options: GenerateOptions): Promise<string> {
91
- const typeFiles =
92
- typeof options.types === "string" ? await stFiles(options.types) : options.types;
93
- const declarations = (
94
- await Promise.all(
95
- typeFiles.map(async (name) =>
96
- parseDeclarations({ name, text: await readFile(name, "utf8") }),
97
- ),
98
- )
99
- ).flat();
100
- const globalFiles =
101
- typeof options.globals === "string" ? await stFiles(options.globals) : (options.globals ?? []);
102
- // Program-only projects have a valid empty export selection. Directory
103
- // discovery still rejects empty input rather than hiding a bad setting.
104
- if (
105
- !typeFiles.length &&
106
- !globalFiles.length &&
107
- (typeof options.types === "string" || typeof options.globals === "string")
108
- )
109
- throw new Error(
110
- `no .st declarations found in ${typeof options.types === "string" ? options.types : "the selected source files"}`,
111
- );
112
- let globals = await Promise.all(
113
- globalFiles.map(async (name) =>
114
- parseGlobals(
115
- { name, text: await readFile(name, "utf8") },
116
- basename(name).replace(/\.st$/i, ""),
117
- ),
118
- ),
119
- );
120
- if (options.publishedGlobalsOnly)
121
- globals = globals
122
- .map((list) =>
123
- list.constant
124
- ? list
125
- : {
126
- ...list,
127
- members: list.members.filter((member) =>
128
- options.publication
129
- ? [
130
- ...options.publication.production,
131
- ...options.publication.development,
132
- ].includes(`${list.name}.${member.name}`)
133
- : member.published,
134
- ),
135
- },
136
- )
137
- .filter((list) => list.constant || list.members.length);
138
- const contract = emit(
139
- declarations,
140
- globals,
141
- options.publishedGlobalsOnly ?? false,
142
- options.declarations ?? true,
143
- );
144
- return options.publication
145
- ? `${contract}\nexport const publication = ${JSON.stringify(options.publication, null, 2)} as const;\n`
146
- : contract;
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 ?? []);
126
+ // Program-only projects have a valid empty export selection. Directory
127
+ // discovery still rejects empty input rather than hiding a bad setting.
128
+ if (
129
+ !typeFiles.length &&
130
+ !globalFiles.length &&
131
+ (typeof options.types === "string" || typeof options.globals === "string")
132
+ ) {
133
+ throw new Error(
134
+ `no .st declarations found in ${typeof options.types === "string" ? options.types : "the selected source files"}`,
135
+ );
136
+ }
137
+ const globals = (await readSources(globalFiles)).map((source) =>
138
+ parseGlobals(source, basename(source.name).replace(/\.st$/i, "")),
139
+ );
140
+ const publishedGlobalsOnly = options.publishedGlobalsOnly ?? false;
141
+ const contract = emit(
142
+ declarations,
143
+ publishedGlobalsOnly ? published(globals, options.publication) : globals,
144
+ { publishedGlobalsOnly, emitDeclarations: options.declarations ?? true },
145
+ );
146
+ return options.publication
147
+ ? `${contract}\nexport const publication = ${JSON.stringify(options.publication, null, 2)} as const;\n`
148
+ : contract;
149
+ }
150
+
151
+ /**
152
+ * 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.
154
+ */
155
+ function published(
156
+ globals: GlobalList[],
157
+ publication: Publication | undefined,
158
+ ): GlobalList[] {
159
+ return globals
160
+ .map((list) =>
161
+ list.constant
162
+ ? list
163
+ : {
164
+ ...list,
165
+ members: list.members.filter((member) =>
166
+ publication
167
+ ? [
168
+ ...publication.production,
169
+ ...publication.development,
170
+ ].includes(`${list.name}.${member.name}`)
171
+ : member.published,
172
+ ),
173
+ },
174
+ )
175
+ .filter((list) => list.constant || list.members.length);
147
176
  }
148
177
 
149
178
  function emit(
150
- declarations: Declaration[],
151
- globals: GlobalList[],
152
- publishedGlobalsOnly: boolean,
153
- emitDeclarations: boolean,
179
+ declarations: Declaration[],
180
+ globals: GlobalList[],
181
+ {
182
+ publishedGlobalsOnly,
183
+ emitDeclarations,
184
+ }: { publishedGlobalsOnly: boolean; emitDeclarations: boolean },
154
185
  ): string {
155
- const types = unique(declarations);
156
- unique(globals);
157
- const constants = globals.filter((list) => list.constant);
158
- // Keep integer constants useful to host clients, including declaration bounds.
159
- // Private block presets and labels cannot use this integer-only export format.
160
- // Their declarations still remain available to the lazy bound resolver below.
161
- const constantLists = publishedGlobalsOnly
162
- ? constants
163
- .map((list) => ({
164
- ...list,
165
- members: list.members.filter(
166
- (member) =>
167
- member.type.kind === "named" &&
168
- integerTypePattern.test(member.type.name.toUpperCase()),
169
- ),
170
- }))
171
- .filter((list) => list.members.length)
172
- : constants;
173
- const variableLists = globals.filter((list) => !list.constant);
174
- const constantValues = new Map<string, number>();
175
- const resolvingConstants = new Set<string>();
176
- const constantDefinitions = constants.flatMap((list) =>
177
- list.members.map((member) => ({
178
- list,
179
- member,
180
- key: `${list.name}.${member.name}`.toUpperCase(),
181
- })),
182
- );
183
- function constant(name: string, scope?: string): number {
184
- const key = name.toUpperCase();
185
- const scoped = constantDefinitions.find(
186
- (item) => item.key === `${scope}.${name}`.toUpperCase(),
187
- );
188
- const candidates = scoped
189
- ? [scoped]
190
- : constantDefinitions.filter(
191
- (item) =>
192
- item.key === key || (!name.includes(".") && item.member.name.toUpperCase() === key),
193
- );
194
- if (candidates.length !== 1) throw new Error(`unknown or ambiguous constant ${name}`);
195
- const definition = candidates[0]!;
196
- const cached = constantValues.get(definition.key);
197
- if (cached !== undefined) return cached;
198
- if (resolvingConstants.has(definition.key)) throw new Error(`cyclic constant ${name}`);
199
- const { member, list } = definition;
200
- if (
201
- member.initial === undefined ||
202
- member.type.kind !== "named" ||
203
- !integerTypePattern.test(member.type.name.toUpperCase())
204
- )
205
- throw new Error(
206
- `${list.source}: constant ${member.name} must have an integer type and initializer`,
207
- );
208
- resolvingConstants.add(definition.key);
209
- const value = integerExpression(member.initial, (reference) => constant(reference, list.name));
210
- resolvingConstants.delete(definition.key);
211
- constantValues.set(definition.key, value);
212
- return value;
213
- }
186
+ const types = unique(declarations);
187
+ unique(globals);
188
+ const constants = globals.filter((list) => list.constant);
189
+ // Keep integer constants useful to host clients, including declaration bounds.
190
+ // 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
+ const constantLists = publishedGlobalsOnly
193
+ ? constants
194
+ .map((list) => ({
195
+ ...list,
196
+ members: list.members.filter(
197
+ (member) =>
198
+ member.type.kind === "named" &&
199
+ isNumberInteger(member.type.name.toUpperCase()),
200
+ ),
201
+ }))
202
+ .filter((list) => list.members.length)
203
+ : constants;
204
+ const variableLists = globals.filter((list) => !list.constant);
205
+ const constant = constantResolver(constants);
214
206
 
215
- function bound(expression: string): number {
216
- return integerExpression(expression, (name) => constant(name));
217
- }
218
- function dimensions(type: Extract<TypeReference, { kind: "array" }>) {
219
- return type.dimensions.map(({ lower, upper }) => {
220
- const start = bound(lower);
221
- const end = bound(upper);
222
- if (end < start || !Number.isSafeInteger(end - start + 1))
223
- throw new Error(`invalid array bounds ${lower}..${upper}`);
224
- return { start, end };
225
- });
226
- }
227
- function declaration(name: string): Declaration {
228
- const found = types.get(name.toUpperCase());
229
- if (!found) throw new Error(`unknown IEC type ${name}`);
230
- return found;
231
- }
232
- function tsType(type: TypeReference): string {
233
- if (type.kind === "array") {
234
- dimensions(type);
235
- return type.dimensions.reduce((child) => `Array<${child}>`, tsType(type.element));
236
- }
237
- if (type.kind === "string") {
238
- const length = bound(type.length);
239
- if (length < 1) throw new Error(`invalid ${type.name} length ${length}`);
240
- return "string";
241
- }
242
- return scalars[type.name.toUpperCase()] ?? declaration(type.name).name;
243
- }
244
- function resolved(type: TypeReference): TypeReference {
245
- if (type.kind !== "named" || scalars[type.name.toUpperCase()]) return type;
246
- const definition = declaration(type.name);
247
- if (definition.kind === "alias") return resolved(definition.type);
248
- if (definition.kind === "enum") return { kind: "named", name: definition.base };
249
- return type;
250
- }
251
- function iecType(type: TypeReference): string {
252
- const actual = resolved(type);
253
- if (actual.kind === "string") return `${actual.name}(${bound(actual.length)})`;
254
- if (actual.kind === "array")
255
- return `ARRAY[${dimensions(actual)
256
- .map(({ start, end }) => `${start}..${end}`)
257
- .join(", ")}] OF ${iecType(actual.element)}`;
258
- return scalars[actual.name.toUpperCase()]
259
- ? actual.name.toUpperCase()
260
- : declaration(actual.name).name;
261
- }
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
+ function tsType(type: TypeReference): string {
228
+ if (type.kind === "array") {
229
+ dimensions(type);
230
+ return type.dimensions.reduce(
231
+ (child) => `Array<${child}>`,
232
+ tsType(type.element),
233
+ );
234
+ }
235
+ if (type.kind === "string") {
236
+ const length = bound(type.length);
237
+ if (length < 1) {
238
+ throw new Error(`invalid ${type.name} length ${length}`);
239
+ }
240
+ return "string";
241
+ }
242
+ return scalars[type.name.toUpperCase()] ?? declaration(type.name).name;
243
+ }
244
+ function resolved(type: TypeReference): TypeReference {
245
+ if (type.kind !== "named" || scalars[type.name.toUpperCase()]) {
246
+ return type;
247
+ }
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;
256
+ }
257
+ function iecType(type: TypeReference): string {
258
+ const actual = resolved(type);
259
+ if (actual.kind === "string") {
260
+ return `${actual.name}(${bound(actual.length)})`;
261
+ }
262
+ if (actual.kind === "array") {
263
+ return `ARRAY[${dimensions(actual)
264
+ .map(({ start, end }) => `${start}..${end}`)
265
+ .join(", ")}] OF ${iecType(actual.element)}`;
266
+ }
267
+ return scalars[actual.name.toUpperCase()]
268
+ ? actual.name.toUpperCase()
269
+ : declaration(actual.name).name;
270
+ }
262
271
 
263
- // Topological order makes generated field lists reusable without duplicating child fields.
264
- const ordered: Declaration[] = [];
265
- const visiting = new Set<string>();
266
- const visited = new Set<string>();
267
- function visitReference(type: TypeReference): void {
268
- if (type.kind === "array") return visitReference(type.element);
269
- if (type.kind === "named" && !scalars[type.name.toUpperCase()]) visit(declaration(type.name));
270
- }
271
- function visit(type: Declaration): void {
272
- if (visited.has(type.name)) return;
273
- if (visiting.has(type.name))
274
- throw new Error(`${type.source}: cyclic type reference involving ${type.name}`);
275
- visiting.add(type.name);
276
- if (type.kind === "struct") type.members.forEach((member) => visitReference(member.type));
277
- if (type.kind === "alias") visitReference(type.type);
278
- visiting.delete(type.name);
279
- visited.add(type.name);
280
- ordered.push(type);
281
- }
282
- declarations.forEach(visit);
272
+ // Topological order makes generated field lists reusable without duplicating child fields.
273
+ const ordered: Declaration[] = [];
274
+ const visiting = new Set<string>();
275
+ const visited = new Set<string>();
276
+ function visitReference(type: TypeReference): void {
277
+ if (type.kind === "array") {
278
+ return visitReference(type.element);
279
+ }
280
+ if (type.kind === "named" && !scalars[type.name.toUpperCase()]) {
281
+ visit(declaration(type.name));
282
+ }
283
+ }
284
+ function visit(type: Declaration): void {
285
+ if (visited.has(type.name)) {
286
+ return;
287
+ }
288
+ if (visiting.has(type.name)) {
289
+ throw new Error(
290
+ `${type.source}: cyclic type reference involving ${type.name}`,
291
+ );
292
+ }
293
+ visiting.add(type.name);
294
+ if (type.kind === "struct") {
295
+ type.members.forEach((member) => visitReference(member.type));
296
+ }
297
+ if (type.kind === "alias") {
298
+ visitReference(type.type);
299
+ }
300
+ visiting.delete(type.name);
301
+ visited.add(type.name);
302
+ ordered.push(type);
303
+ }
304
+ declarations.forEach(visit);
283
305
 
284
- const reserved = new Set(
285
- "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(
286
- " ",
287
- ),
288
- );
289
- for (const name of [
290
- ...declarations.map((type) => type.name),
291
- ...constantLists.map((list) => list.name),
292
- ]) {
293
- if (!/^[A-Za-z_]\w*$/.test(name) || reserved.has(name) || /^_fields\d+$/.test(name))
294
- throw new Error(`name cannot be exported to TypeScript: ${name}`);
295
- reserved.add(name);
296
- }
297
- const indexes = new Map(ordered.map((type, index) => [type.name, index]));
298
- function complex(type: TypeReference): boolean {
299
- const actual = resolved(type);
300
- if (actual.kind === "array") return complex(actual.element);
301
- return actual.kind === "named" && !scalars[actual.name.toUpperCase()];
302
- }
303
- /** An enum-keyed array: like a record's fields, each key is its own contract variable. */
304
- function keyed(type: TypeReference): boolean {
305
- if (type.kind !== "named" || scalars[type.name.toUpperCase()]) return false;
306
- const definition = declaration(type.name);
307
- return definition.kind === "alias" && (!!definition.keyed || keyed(definition.type));
308
- }
309
- function fields(type: TypeReference, path: string, description: string, depth = 0): string {
310
- const actual = resolved(type);
311
- if (actual.kind === "named" && complex(actual)) {
312
- const children = `_fields${indexes.get(declaration(actual.name).name)}`;
313
- if (path === '""') return children;
314
- return `${children}.map((member) => ({ ...member, field: ${path} + "." + member.field }))`;
315
- }
316
- if (actual.kind === "array" && (complex(actual.element) || keyed(type))) {
317
- const ranges = dimensions(actual);
318
- const coordinates = ranges.map(
319
- (range, index) => `String(i${depth}_${index} + (${range.start}))`,
320
- );
321
- const arrayPath = `${path} + "[" + ${coordinates.join(' + "," + ')} + "]"`;
322
- return ranges.reduceRight(
323
- (child, range, index) =>
324
- `Array.from({ length: ${range.end - range.start + 1} }, (_, i${depth}_${index}) => ${child}).flat()`,
325
- fields(actual.element, `(${arrayPath})`, description, depth + 1),
326
- );
327
- }
328
- return `[{ field: ${path}, type: ${quote(iecType(actual))}, description: ${quote(description)} }]`;
329
- }
306
+ const reserved = new Set(
307
+ "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(
308
+ " ",
309
+ ),
310
+ );
311
+ for (const name of [
312
+ ...declarations.map((type) => type.name),
313
+ ...constantLists.map((list) => list.name),
314
+ ]) {
315
+ if (
316
+ !identifierPattern.test(name) ||
317
+ reserved.has(name) ||
318
+ /^_fields\d+$/.test(name)
319
+ ) {
320
+ throw new Error(`name cannot be exported to TypeScript: ${name}`);
321
+ }
322
+ reserved.add(name);
323
+ }
324
+ const indexes = new Map(ordered.map((type, index) => [type.name, index]));
325
+ function complex(type: TypeReference): boolean {
326
+ const actual = resolved(type);
327
+ if (actual.kind === "array") {
328
+ return complex(actual.element);
329
+ }
330
+ return actual.kind === "named" && !scalars[actual.name.toUpperCase()];
331
+ }
332
+ /** An enum-keyed array: like a record's fields, each key is its own contract variable. */
333
+ function keyed(type: TypeReference): boolean {
334
+ if (type.kind !== "named" || scalars[type.name.toUpperCase()]) {
335
+ return false;
336
+ }
337
+ const definition = declaration(type.name);
338
+ return (
339
+ definition.kind === "alias" &&
340
+ (!!definition.keyed || keyed(definition.type))
341
+ );
342
+ }
343
+ function fields(
344
+ type: TypeReference,
345
+ path: string,
346
+ description: string,
347
+ depth = 0,
348
+ ): string {
349
+ const actual = resolved(type);
350
+ if (actual.kind === "named" && complex(actual)) {
351
+ const children = `_fields${indexes.get(declaration(actual.name).name)}`;
352
+ if (path === '""') {
353
+ return children;
354
+ }
355
+ return `${children}.map((member) => ({ ...member, field: ${path} + "." + member.field }))`;
356
+ }
357
+ if (actual.kind === "array" && (complex(actual.element) || keyed(type))) {
358
+ const ranges = dimensions(actual);
359
+ const coordinates = ranges.map(
360
+ (range, index) => `String(i${depth}_${index} + (${range.start}))`,
361
+ );
362
+ const arrayPath = `${path} + "[" + ${coordinates.join(' + "," + ')} + "]"`;
363
+ return ranges.reduceRight(
364
+ (child, range, index) =>
365
+ `Array.from({ length: ${range.end - range.start + 1} }, (_, i${depth}_${index}) => ${child}).flat()`,
366
+ fields(actual.element, `(${arrayPath})`, description, depth + 1),
367
+ );
368
+ }
369
+ return `[{ field: ${path}, type: ${quote(iecType(actual))}, description: ${quote(description)} }]`;
370
+ }
330
371
 
331
- const declare = (text: string) => (emitDeclarations ? [text] : []);
332
- const output = [
333
- "// Generated by @tsplc/typegen. Edit the PLC sources and regenerate.\n",
334
- "export interface PlcField { field: string; type: string; description: string; }\n",
335
- ];
336
- for (const type of ordered) {
337
- try {
338
- const doc = documentation(type.description);
339
- if (type.kind === "struct") {
340
- output.push(
341
- ...declare(
342
- `${doc}export interface ${type.name} {\n${type.members.map((member) => `${documentation(member.description)}${quote(member.name)}: ${tsType(member.type)};`).join("\n")}\n}\n`,
343
- ),
344
- );
345
- output.push(
346
- `const _fields${indexes.get(type.name)}: PlcField[] = [\n${type.members.map((member) => `...${fields(member.type, quote(member.name), member.description)},`).join("\n")}\n];\n`,
347
- );
348
- } else if (type.kind === "alias") {
349
- output.push(...declare(`${doc}export type ${type.name} = ${tsType(type.type)};\n`));
350
- output.push(
351
- `const _fields${indexes.get(type.name)}: PlcField[] = ${fields({ kind: "named", name: type.name }, '""', type.description)};\n`,
352
- );
353
- } else {
354
- if (!integerTypePattern.test(type.base))
355
- throw new Error(`unsupported enum base ${type.base}`);
356
- const entries = new Map<string, number>();
357
- for (const member of type.members) {
358
- const previous = [...entries.values()].at(-1) ?? -1;
359
- const value =
360
- member.value === undefined
361
- ? previous + 1
362
- : integerExpression(
363
- member.value,
364
- (name) => entries.get(name.toUpperCase()) ?? constant(name),
365
- );
366
- entries.set(member.name.toUpperCase(), value);
367
- }
368
- output.push(
369
- ...declare(
370
- `${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`,
371
- ),
372
- );
373
- output.push(
374
- `const _fields${indexes.get(type.name)}: PlcField[] = ${fields({ kind: "named", name: type.base }, '""', type.description)};\n`,
375
- );
376
- }
377
- } catch (error) {
378
- throw new Error(
379
- `${type.source} (${type.name}): ${error instanceof Error ? error.message : String(error)}`,
380
- { cause: error },
381
- );
382
- }
383
- }
384
- output.push(
385
- `export const typeFields = {\n${ordered.map((type) => `${quote(type.name)}: _fields${indexes.get(type.name)},`).join("\n")}\n};\n`,
386
- );
387
- for (const list of emitDeclarations ? constantLists : []) {
388
- output.push(
389
- `${documentation(list.description)}export const ${list.name} = {\n${list.members.map((member) => `${documentation(member.description)}${quote(member.name)}: ${constant(`${list.name}.${member.name}`)},`).join("\n")}\n} as const;\n`,
390
- );
391
- }
392
- output.push(
393
- ...declare(
394
- `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`,
395
- ),
396
- );
397
- output.push(
398
- `export const globalVariableLists = ${JSON.stringify(Object.fromEntries(variableLists.map((list) => [list.name, list.description])), null, "\t")} as const;\n`,
399
- );
400
- output.push(
401
- `export const symbols = ${JSON.stringify(
402
- variableLists.flatMap((list) =>
403
- list.members.map((member) => ({
404
- name: member.name,
405
- gvl: list.name,
406
- type:
407
- member.type.kind === "named" && !scalars[member.type.name.toUpperCase()]
408
- ? declaration(member.type.name).name
409
- : iecType(member.type),
410
- description: member.description,
411
- })),
412
- ),
413
- null,
414
- "\t",
415
- )} as const;\n`,
416
- );
417
- return output.join("\n");
372
+ const declare = (text: string) => (emitDeclarations ? [text] : []);
373
+ const output = [
374
+ "// Generated by @tsplc/typegen. Edit the PLC sources and regenerate.\n",
375
+ "export interface PlcField { field: string; type: string; description: string; }\n",
376
+ ];
377
+ for (const type of ordered) {
378
+ try {
379
+ const doc = documentation(type.description);
380
+ if (type.kind === "struct") {
381
+ output.push(
382
+ ...declare(
383
+ `${doc}export interface ${type.name} {\n${type.members.map((member) => `${documentation(member.description)}${quote(member.name)}: ${tsType(member.type)};`).join("\n")}\n}\n`,
384
+ ),
385
+ );
386
+ output.push(
387
+ `const _fields${indexes.get(type.name)}: PlcField[] = [\n${type.members.map((member) => `...${fields(member.type, quote(member.name), member.description)},`).join("\n")}\n];\n`,
388
+ );
389
+ } else if (type.kind === "alias") {
390
+ output.push(
391
+ ...declare(
392
+ `${doc}export type ${type.name} = ${tsType(type.type)};\n`,
393
+ ),
394
+ );
395
+ output.push(
396
+ `const _fields${indexes.get(type.name)}: PlcField[] = ${fields({ kind: "named", name: type.name }, '""', type.description)};\n`,
397
+ );
398
+ } else {
399
+ if (!isNumberInteger(type.base)) {
400
+ throw new Error(`unsupported enum base ${type.base}`);
401
+ }
402
+ const entries = new Map<string, number>();
403
+ for (const member of type.members) {
404
+ const previous = [...entries.values()].at(-1) ?? -1;
405
+ const value =
406
+ member.value === undefined
407
+ ? previous + 1
408
+ : integerExpression(
409
+ member.value,
410
+ (name) =>
411
+ entries.get(name.toUpperCase()) ?? constant(name, null),
412
+ );
413
+ entries.set(member.name.toUpperCase(), value);
414
+ }
415
+ output.push(
416
+ ...declare(
417
+ `${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`,
418
+ ),
419
+ );
420
+ output.push(
421
+ `const _fields${indexes.get(type.name)}: PlcField[] = ${fields({ kind: "named", name: type.base }, '""', type.description)};\n`,
422
+ );
423
+ }
424
+ } catch (error) {
425
+ throw new Error(
426
+ `${type.source} (${type.name}): ${error instanceof Error ? error.message : String(error)}`,
427
+ { cause: error },
428
+ );
429
+ }
430
+ }
431
+ output.push(
432
+ `export const typeFields = {\n${ordered.map((type) => `${quote(type.name)}: _fields${indexes.get(type.name)},`).join("\n")}\n};\n`,
433
+ );
434
+ for (const list of emitDeclarations ? constantLists : []) {
435
+ output.push(
436
+ `${documentation(list.description)}export const ${list.name} = {\n${list.members.map((member) => `${documentation(member.description)}${quote(member.name)}: ${constant(`${list.name}.${member.name}`, null)},`).join("\n")}\n} as const;\n`,
437
+ );
438
+ }
439
+ output.push(
440
+ ...declare(
441
+ `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`,
442
+ ),
443
+ );
444
+ output.push(
445
+ `export const globalVariableLists = ${JSON.stringify(Object.fromEntries(variableLists.map((list) => [list.name, list.description])), null, "\t")} as const;\n`,
446
+ );
447
+ output.push(
448
+ `export const symbols = ${JSON.stringify(
449
+ variableLists.flatMap((list) =>
450
+ list.members.map((member) => ({
451
+ name: member.name,
452
+ gvl: list.name,
453
+ type:
454
+ member.type.kind === "named" &&
455
+ !scalars[member.type.name.toUpperCase()]
456
+ ? declaration(member.type.name).name
457
+ : iecType(member.type),
458
+ description: member.description,
459
+ })),
460
+ ),
461
+ null,
462
+ "\t",
463
+ )} as const;\n`,
464
+ );
465
+ return output.join("\n");
418
466
  }