@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.
- package/README.md +29 -3
- package/dist/cli.js +609 -433
- package/dist/cli.js.map +21 -16
- package/dist/codegen.js +242 -192
- package/dist/codegen.js.map +8 -6
- package/dist/declarations.js +277 -138
- package/dist/declarations.js.map +8 -7
- package/dist/hardware.js +383 -114
- package/dist/hardware.js.map +13 -10
- package/dist/index.js +652 -468
- package/dist/index.js.map +21 -17
- package/dist/project-snapshot.js +17 -19
- package/dist/project-snapshot.js.map +5 -4
- package/package.json +3 -3
- package/src/cli.ts +25 -33
- package/src/codegen/constants.ts +19 -25
- package/src/codegen/declarations.ts +12 -39
- package/src/codegen/generate.ts +118 -179
- package/src/codegen/parser.ts +121 -63
- package/src/codegen/resolution.ts +68 -0
- package/src/device-tree.ts +14 -97
- package/src/files.ts +40 -0
- package/src/hardware/catalog.ts +49 -0
- package/src/hardware/channels.ts +12 -5
- package/src/hardware/eds.ts +229 -45
- package/src/hardware/mapping-types.ts +58 -21
- package/src/hardware/modbus.ts +42 -28
- package/src/hardware/process-image.ts +57 -24
- package/src/hardware/selection.ts +25 -9
- package/src/hardware.ts +56 -77
- package/src/index.ts +4 -7
- package/src/outputs.ts +50 -0
- package/src/project-snapshot.ts +13 -25
- package/src/project.ts +108 -136
package/dist/codegen.js
CHANGED
|
@@ -1,22 +1,44 @@
|
|
|
1
1
|
// packages/typegen/src/codegen/generate.ts
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
|
|
2
|
+
import {
|
|
3
|
+
elementaryType as elementaryType3,
|
|
4
|
+
elementaryTypesByName,
|
|
5
|
+
fitsNumber as fitsNumber2,
|
|
6
|
+
isIntegerValued as isIntegerValued2,
|
|
7
|
+
isWholeValue,
|
|
8
|
+
stringTypeText
|
|
9
|
+
} from "@tsplc/iec";
|
|
5
10
|
import { identifierPattern as identifierPattern2 } from "@tsplc/iec/st";
|
|
6
11
|
|
|
12
|
+
// packages/typegen/src/files.ts
|
|
13
|
+
import { readdir, readFile } from "node:fs/promises";
|
|
14
|
+
import { join } from "node:path";
|
|
15
|
+
async function filesUnder(directory, extension, order) {
|
|
16
|
+
const pattern = new RegExp(`\\.${extension}$`, "i");
|
|
17
|
+
const entries = await readdir(directory, { withFileTypes: true });
|
|
18
|
+
const paths = await Promise.all(entries.sort((a, b) => order(a.name, b.name)).map(async (entry) => {
|
|
19
|
+
const path = join(directory, entry.name);
|
|
20
|
+
if (entry.isDirectory()) {
|
|
21
|
+
return filesUnder(path, extension, order);
|
|
22
|
+
}
|
|
23
|
+
return entry.isFile() && pattern.test(entry.name) ? [path] : [];
|
|
24
|
+
}));
|
|
25
|
+
return paths.flat();
|
|
26
|
+
}
|
|
27
|
+
var stFiles = (directory) => filesUnder(directory, "st", (a, b) => a < b ? -1 : 1);
|
|
28
|
+
|
|
7
29
|
// packages/typegen/src/codegen/constants.ts
|
|
8
30
|
import {
|
|
9
31
|
elementaryType,
|
|
10
32
|
elementaryTypes,
|
|
33
|
+
fitsNumber,
|
|
11
34
|
integerRange,
|
|
12
35
|
isIntegerValued
|
|
13
36
|
} from "@tsplc/iec";
|
|
14
|
-
|
|
15
|
-
const type = elementaryType(name);
|
|
16
|
-
return isIntegerValued(type) && type.bits <= 32;
|
|
17
|
-
};
|
|
37
|
+
import { identifierPart, identifierStart, integerLiteral } from "@tsplc/iec/st";
|
|
18
38
|
var integerRanges = new Map(elementaryTypes.filter(isIntegerValued).map((type) => [type.name, integerRange(type)]));
|
|
19
|
-
var
|
|
39
|
+
var identifier = `${identifierStart}${identifierPart}*`;
|
|
40
|
+
var startsWithIdentifier = new RegExp(`^${identifierStart}`);
|
|
41
|
+
var integerToken = new RegExp(String.raw`(?:${[...integerRanges.keys()].join("|")})\s*#\s*[+-]?(?:(?:2|8|16)#[\da-fA-F_]+|\d[\d_]*)|(?:2|8|16)#[\da-fA-F_]+|\d[\d_]*|${identifier}(?:\s*\.\s*${identifier})?|[()+\-*/]`, "g");
|
|
20
42
|
function integerExpression(text, lookup) {
|
|
21
43
|
const compact = text.replace(/\s+/g, "");
|
|
22
44
|
const tokens = (text.match(integerToken) ?? []).map((token) => token.replace(/\s+/g, ""));
|
|
@@ -55,13 +77,13 @@ function integerExpression(text, lookup) {
|
|
|
55
77
|
return value;
|
|
56
78
|
}
|
|
57
79
|
if (token && /^\d/.test(token)) {
|
|
58
|
-
const
|
|
59
|
-
if (
|
|
60
|
-
throw new Error(`invalid
|
|
80
|
+
const literal = integerLiteral(token);
|
|
81
|
+
if (literal === undefined) {
|
|
82
|
+
throw new Error(`invalid integer literal: ${token}`);
|
|
61
83
|
}
|
|
62
|
-
return safe(
|
|
84
|
+
return safe(Number(literal));
|
|
63
85
|
}
|
|
64
|
-
if (token &&
|
|
86
|
+
if (token && startsWithIdentifier.test(token)) {
|
|
65
87
|
return lookup(token);
|
|
66
88
|
}
|
|
67
89
|
throw new Error(`invalid integer expression: ${text}`);
|
|
@@ -88,11 +110,12 @@ function integerExpression(text, lookup) {
|
|
|
88
110
|
return value;
|
|
89
111
|
}
|
|
90
112
|
const value = sum();
|
|
91
|
-
if (position !== tokens.length
|
|
92
|
-
throw new Error(`invalid
|
|
113
|
+
if (position !== tokens.length) {
|
|
114
|
+
throw new Error(`invalid integer expression: ${text}`);
|
|
93
115
|
}
|
|
94
116
|
return value;
|
|
95
117
|
}
|
|
118
|
+
var isIntegerConstant = (member) => member.type.kind === "named" && fitsNumber(elementaryType(member.type.name.toUpperCase()));
|
|
96
119
|
function constantResolver(lists) {
|
|
97
120
|
const values = new Map;
|
|
98
121
|
const resolving = new Set;
|
|
@@ -116,7 +139,7 @@ function constantResolver(lists) {
|
|
|
116
139
|
throw new Error(`cyclic constant ${name}`);
|
|
117
140
|
}
|
|
118
141
|
const { member, list } = definition;
|
|
119
|
-
if (member.initial === undefined ||
|
|
142
|
+
if (member.initial === undefined || !isIntegerConstant(member)) {
|
|
120
143
|
throw new Error(`${list.source}: constant ${member.name} must have an integer type and initializer`);
|
|
121
144
|
}
|
|
122
145
|
resolving.add(definition.key);
|
|
@@ -129,73 +152,84 @@ function constantResolver(lists) {
|
|
|
129
152
|
}
|
|
130
153
|
|
|
131
154
|
// packages/typegen/src/codegen/parser.ts
|
|
155
|
+
import { readFile as readFile2 } from "node:fs/promises";
|
|
156
|
+
import { basename } from "node:path";
|
|
157
|
+
import { defaultStringLength } from "@tsplc/iec";
|
|
132
158
|
import {
|
|
133
159
|
blockCommentEnd,
|
|
134
160
|
directAddressEnd,
|
|
161
|
+
identifierPart as identifierPart2,
|
|
135
162
|
identifierPattern,
|
|
163
|
+
identifierStart as identifierStart2,
|
|
136
164
|
lineCommentEnd,
|
|
137
|
-
qualifiers
|
|
165
|
+
qualifiers,
|
|
166
|
+
stringEnd
|
|
138
167
|
} from "@tsplc/iec/st";
|
|
168
|
+
var pragmaEnd = (text, offset) => {
|
|
169
|
+
const next = text.slice(offset).search(/[}'"]/);
|
|
170
|
+
if (next < 0) {
|
|
171
|
+
return null;
|
|
172
|
+
}
|
|
173
|
+
const at = offset + next;
|
|
174
|
+
if (text[at] === "}") {
|
|
175
|
+
return at + 1;
|
|
176
|
+
}
|
|
177
|
+
const end = stringEnd(text, at);
|
|
178
|
+
return end === null ? null : pragmaEnd(text, end);
|
|
179
|
+
};
|
|
180
|
+
var codeToken = new RegExp(String.raw`^(?:\d[\d_]*#[\da-fA-F_]+|\d[\d_]*(?:\.(?!\.)[\d_]+)?(?:[eE][+-]?\d+)?|${identifierStart2}${identifierPart2}*|:=|\.\.|[[\]():;,.+\-*/#])`, "i");
|
|
181
|
+
function tokenAt(source, start) {
|
|
182
|
+
const { text } = source;
|
|
183
|
+
const offset = start + text.slice(start).search(/\S|$/);
|
|
184
|
+
if (offset === text.length) {
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
const rest = text.slice(offset);
|
|
188
|
+
if (rest.startsWith("(*")) {
|
|
189
|
+
const end = blockCommentEnd(text, offset);
|
|
190
|
+
if (end === null) {
|
|
191
|
+
throw new Error(`${source.name}: unterminated comment`);
|
|
192
|
+
}
|
|
193
|
+
const comment = text.slice(offset + 2, end - 2).trim();
|
|
194
|
+
return { text: comment, offset, end, kind: "comment" };
|
|
195
|
+
}
|
|
196
|
+
if (rest.startsWith("//")) {
|
|
197
|
+
const end = lineCommentEnd(text, offset);
|
|
198
|
+
const comment = text.slice(offset + 2, end).trim();
|
|
199
|
+
return { text: comment, offset, end, kind: "comment" };
|
|
200
|
+
}
|
|
201
|
+
const code = (kind, end) => ({
|
|
202
|
+
text: text.slice(offset, end),
|
|
203
|
+
offset,
|
|
204
|
+
end,
|
|
205
|
+
kind
|
|
206
|
+
});
|
|
207
|
+
const attributeEnd = rest.startsWith("{") ? pragmaEnd(text, offset + 1) : null;
|
|
208
|
+
if (attributeEnd !== null) {
|
|
209
|
+
return code("attribute", attributeEnd);
|
|
210
|
+
}
|
|
211
|
+
const addressEnd = directAddressEnd(text, offset);
|
|
212
|
+
if (addressEnd !== null) {
|
|
213
|
+
return code("code", addressEnd);
|
|
214
|
+
}
|
|
215
|
+
const literalEnd = rest.startsWith("'") || rest.startsWith('"') ? stringEnd(text, offset) : null;
|
|
216
|
+
if (literalEnd !== null) {
|
|
217
|
+
return code("code", literalEnd);
|
|
218
|
+
}
|
|
219
|
+
const word = codeToken.exec(rest);
|
|
220
|
+
if (!word) {
|
|
221
|
+
throw new Error(`${source.name}:${text.slice(0, offset).split(`
|
|
222
|
+
`).length}: unsupported token ${JSON.stringify(rest.slice(0, 24))}`);
|
|
223
|
+
}
|
|
224
|
+
return code("code", offset + word[0].length);
|
|
225
|
+
}
|
|
139
226
|
function tokenize(source) {
|
|
140
227
|
const tokens = [];
|
|
141
|
-
let
|
|
142
|
-
|
|
143
|
-
const rest = source.text.slice(offset);
|
|
144
|
-
const whitespace = /^\s+/.exec(rest);
|
|
145
|
-
if (whitespace) {
|
|
146
|
-
offset += whitespace[0].length;
|
|
147
|
-
continue;
|
|
148
|
-
}
|
|
149
|
-
if (rest.startsWith("(*")) {
|
|
150
|
-
const end = blockCommentEnd(source.text, offset);
|
|
151
|
-
if (end === null) {
|
|
152
|
-
throw new Error(`${source.name}: unterminated comment`);
|
|
153
|
-
}
|
|
154
|
-
tokens.push({
|
|
155
|
-
text: source.text.slice(offset + 2, end - 2).trim(),
|
|
156
|
-
offset,
|
|
157
|
-
kind: "comment"
|
|
158
|
-
});
|
|
159
|
-
offset = end;
|
|
160
|
-
continue;
|
|
161
|
-
}
|
|
162
|
-
if (rest.startsWith("//")) {
|
|
163
|
-
const end = lineCommentEnd(source.text, offset);
|
|
164
|
-
tokens.push({
|
|
165
|
-
text: source.text.slice(offset + 2, end).trim(),
|
|
166
|
-
offset,
|
|
167
|
-
kind: "comment"
|
|
168
|
-
});
|
|
169
|
-
offset = end;
|
|
170
|
-
continue;
|
|
171
|
-
}
|
|
172
|
-
const attribute = /^\{(?:[^}'"]|'(?:\$[\s\S]|''|[^'])*'|"(?:\$[\s\S]|""|[^"])*")*\}/.exec(rest);
|
|
173
|
-
if (attribute) {
|
|
174
|
-
tokens.push({ text: attribute[0], offset, kind: "attribute" });
|
|
175
|
-
offset += attribute[0].length;
|
|
176
|
-
continue;
|
|
177
|
-
}
|
|
178
|
-
const addressEnd = directAddressEnd(source.text, offset);
|
|
179
|
-
if (addressEnd !== null) {
|
|
180
|
-
tokens.push({
|
|
181
|
-
text: source.text.slice(offset, addressEnd),
|
|
182
|
-
offset,
|
|
183
|
-
kind: "code"
|
|
184
|
-
});
|
|
185
|
-
offset = addressEnd;
|
|
186
|
-
continue;
|
|
187
|
-
}
|
|
188
|
-
const code = /^(?:'(?:\$[\s\S]|''|[^'])*'|"(?:\$[\s\S]|""|[^"])*"|\d[\d_]*#[\da-fA-F_]+|\d[\d_]*(?:\.(?!\.)[\d_]+)?(?:[eE][+-]?\d+)?|[A-Za-z_]\w*|:=|\.\.|[[\]():;,.+\-*/#])/i.exec(rest);
|
|
189
|
-
if (!code) {
|
|
190
|
-
throw new Error(`${source.name}:${source.text.slice(0, offset).split(`
|
|
191
|
-
`).length}: unsupported token ${JSON.stringify(rest.slice(0, 24))}`);
|
|
192
|
-
}
|
|
193
|
-
tokens.push({ text: code[0], offset, kind: "code" });
|
|
194
|
-
offset += code[0].length;
|
|
228
|
+
for (let token = tokenAt(source, 0);token; token = tokenAt(source, token.end)) {
|
|
229
|
+
tokens.push(token);
|
|
195
230
|
}
|
|
196
231
|
return tokens;
|
|
197
232
|
}
|
|
198
|
-
|
|
199
233
|
class Parser {
|
|
200
234
|
source;
|
|
201
235
|
position = 0;
|
|
@@ -296,7 +330,11 @@ class Parser {
|
|
|
296
330
|
if (upper === "STRING" || upper === "WSTRING") {
|
|
297
331
|
const opening = this.peek();
|
|
298
332
|
if (opening !== "(" && opening !== "[") {
|
|
299
|
-
return {
|
|
333
|
+
return {
|
|
334
|
+
kind: "string",
|
|
335
|
+
name: upper,
|
|
336
|
+
length: String(defaultStringLength)
|
|
337
|
+
};
|
|
300
338
|
}
|
|
301
339
|
this.take();
|
|
302
340
|
const closing = opening === "(" ? ")" : "]";
|
|
@@ -435,126 +473,143 @@ function parseDeclarations(source) {
|
|
|
435
473
|
function parseGlobals(source, name) {
|
|
436
474
|
return new Parser(source).globals(name);
|
|
437
475
|
}
|
|
476
|
+
var readSource = async (name) => ({
|
|
477
|
+
name,
|
|
478
|
+
text: await readFile2(name, "utf8")
|
|
479
|
+
});
|
|
480
|
+
async function parseSources(files) {
|
|
481
|
+
return {
|
|
482
|
+
types: (await Promise.all(files.types.map(readSource))).flatMap(parseDeclarations),
|
|
483
|
+
globals: (await Promise.all(files.globals.map(readSource))).map((source) => parseGlobals(source, basename(source.name).replace(/\.st$/i, "")))
|
|
484
|
+
};
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
// packages/typegen/src/codegen/resolution.ts
|
|
488
|
+
import { elementaryType as elementaryType2 } from "@tsplc/iec";
|
|
489
|
+
function resolveDeclarations({
|
|
490
|
+
types,
|
|
491
|
+
globals
|
|
492
|
+
}) {
|
|
493
|
+
const declarations = new Map(types.map((declaration) => [declaration.name.toUpperCase(), declaration]));
|
|
494
|
+
const constant = constantResolver(globals.filter((list) => list.constant));
|
|
495
|
+
const integer = (expression) => integerExpression(expression, (name) => constant(name, null));
|
|
496
|
+
const declaration = (name) => {
|
|
497
|
+
const found = declarations.get(name.toUpperCase());
|
|
498
|
+
if (!found) {
|
|
499
|
+
throw new Error(`unknown IEC type ${name}`);
|
|
500
|
+
}
|
|
501
|
+
return found;
|
|
502
|
+
};
|
|
503
|
+
const aliasTarget = (reference) => {
|
|
504
|
+
if (reference.kind !== "named" || elementaryType2(reference.name.toUpperCase())) {
|
|
505
|
+
return reference;
|
|
506
|
+
}
|
|
507
|
+
const named = declaration(reference.name);
|
|
508
|
+
return named.kind === "alias" ? aliasTarget(named.type) : reference;
|
|
509
|
+
};
|
|
510
|
+
const bounds = (array) => array.dimensions.map(({ lower, upper }) => {
|
|
511
|
+
const start = integer(lower);
|
|
512
|
+
const end = integer(upper);
|
|
513
|
+
if (end < start || !Number.isSafeInteger(end - start + 1)) {
|
|
514
|
+
throw new Error(`invalid array bounds ${lower}..${upper}`);
|
|
515
|
+
}
|
|
516
|
+
return { start, end };
|
|
517
|
+
});
|
|
518
|
+
const enumMembers = (enumeration) => {
|
|
519
|
+
const members = [];
|
|
520
|
+
for (const member of enumeration.members) {
|
|
521
|
+
const value = member.value === undefined ? (members.at(-1)?.value ?? -1) + 1 : integerExpression(member.value, (name) => members.find((item) => item.name.toUpperCase() === name.toUpperCase())?.value ?? constant(name, null));
|
|
522
|
+
members.push({ name: member.name, value });
|
|
523
|
+
}
|
|
524
|
+
return members;
|
|
525
|
+
};
|
|
526
|
+
return { constant, integer, declaration, aliasTarget, bounds, enumMembers };
|
|
527
|
+
}
|
|
438
528
|
|
|
439
529
|
// packages/typegen/src/codegen/generate.ts
|
|
440
530
|
var scalarType = (type) => {
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
return "boolean";
|
|
444
|
-
case "integer":
|
|
445
|
-
case "bits":
|
|
446
|
-
return type.bits === 64 ? "bigint" : "number";
|
|
447
|
-
case "real":
|
|
448
|
-
return "number";
|
|
449
|
-
case "duration":
|
|
450
|
-
case "date":
|
|
451
|
-
case "timeOfDay":
|
|
452
|
-
case "dateTime":
|
|
453
|
-
return type.bits === 32 ? "number" : undefined;
|
|
454
|
-
case "char":
|
|
455
|
-
case "string":
|
|
456
|
-
return;
|
|
531
|
+
if (type.family === "bool") {
|
|
532
|
+
return "boolean";
|
|
457
533
|
}
|
|
534
|
+
return isIntegerValued2(type) && !fitsNumber2(type) ? "bigint" : "number";
|
|
458
535
|
};
|
|
459
|
-
var scalars = Object.fromEntries([...elementaryTypesByName].flatMap(([name, type]) =>
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
if (entry.isDirectory()) {
|
|
473
|
-
return stFiles(file);
|
|
474
|
-
}
|
|
475
|
-
return entry.isFile() && /\.st$/i.test(file) ? [file] : [];
|
|
476
|
-
}));
|
|
477
|
-
return paths.flat();
|
|
478
|
-
}
|
|
536
|
+
var scalars = Object.fromEntries([...elementaryTypesByName].flatMap(([name, type]) => isWholeValue(type) ? [[name, scalarType(type)]] : []));
|
|
537
|
+
var sourceFiles = async (setting) => typeof setting === "string" ? stFiles(setting) : setting;
|
|
538
|
+
var contractNames = {
|
|
539
|
+
field: "PlcField",
|
|
540
|
+
globals: "PlcGlobals",
|
|
541
|
+
typeFields: "typeFields",
|
|
542
|
+
globalVariableLists: "globalVariableLists",
|
|
543
|
+
symbols: "symbols",
|
|
544
|
+
publication: "publication"
|
|
545
|
+
};
|
|
546
|
+
var fieldList = (index) => `_fields${index}`;
|
|
547
|
+
var isFieldList = (name) => /^_fields\d+$/.test(name);
|
|
548
|
+
var javascriptReserved = "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(" ");
|
|
479
549
|
var quote = (value) => JSON.stringify(value);
|
|
480
550
|
var documentation = (value) => value ? `/** ${value.replace(/\*\//g, "* /").replace(/\r?\n/g, `
|
|
481
551
|
* `)} */
|
|
482
552
|
` : "";
|
|
483
|
-
function
|
|
484
|
-
const
|
|
485
|
-
for (const
|
|
486
|
-
const key =
|
|
487
|
-
|
|
488
|
-
|
|
553
|
+
function assertUniqueNames(items) {
|
|
554
|
+
const seen = new Map;
|
|
555
|
+
for (const { name, source } of items) {
|
|
556
|
+
const key = name.toUpperCase();
|
|
557
|
+
const previous = seen.get(key);
|
|
558
|
+
if (previous !== undefined) {
|
|
559
|
+
throw new Error(`${source}: duplicate declaration ${name} (also in ${previous})`);
|
|
489
560
|
}
|
|
490
|
-
|
|
561
|
+
seen.set(key, source);
|
|
491
562
|
}
|
|
492
|
-
return result;
|
|
493
563
|
}
|
|
494
|
-
var readSources = (files) => Promise.all(files.map(async (name) => ({ name, text: await readFile(name, "utf8") })));
|
|
495
564
|
async function generateTypes(options) {
|
|
496
|
-
const typeFiles =
|
|
497
|
-
const
|
|
498
|
-
const globalFiles = typeof options.globals === "string" ? await stFiles(options.globals) : options.globals ?? [];
|
|
565
|
+
const typeFiles = await sourceFiles(options.types);
|
|
566
|
+
const globalFiles = await sourceFiles(options.globals);
|
|
499
567
|
if (!typeFiles.length && !globalFiles.length && (typeof options.types === "string" || typeof options.globals === "string")) {
|
|
500
568
|
throw new Error(`no .st declarations found in ${typeof options.types === "string" ? options.types : "the selected source files"}`);
|
|
501
569
|
}
|
|
502
|
-
const globals =
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
570
|
+
const { types: declarations, globals } = await parseSources({
|
|
571
|
+
types: typeFiles,
|
|
572
|
+
globals: globalFiles
|
|
573
|
+
});
|
|
574
|
+
const { publication } = options;
|
|
575
|
+
const contract = emit(declarations, publication ? published(globals, publication) : globals, {
|
|
576
|
+
publishedGlobalsOnly: publication !== null,
|
|
577
|
+
emitDeclarations: options.declarations
|
|
578
|
+
});
|
|
579
|
+
return publication ? `${contract}
|
|
580
|
+
export const ${contractNames.publication} = ${JSON.stringify(publication, null, 2)} as const;
|
|
507
581
|
` : contract;
|
|
508
582
|
}
|
|
509
583
|
function published(globals, publication) {
|
|
584
|
+
const selected = new Set([
|
|
585
|
+
...publication.production,
|
|
586
|
+
...publication.development
|
|
587
|
+
]);
|
|
510
588
|
return globals.map((list) => list.constant ? list : {
|
|
511
589
|
...list,
|
|
512
|
-
members: list.members.filter((member) =>
|
|
513
|
-
...publication.production,
|
|
514
|
-
...publication.development
|
|
515
|
-
].includes(`${list.name}.${member.name}`) : member.symbol !== undefined)
|
|
590
|
+
members: list.members.filter((member) => selected.has(`${list.name}.${member.name}`))
|
|
516
591
|
}).filter((list) => list.constant || list.members.length);
|
|
517
592
|
}
|
|
518
593
|
function emit(declarations, globals, {
|
|
519
594
|
publishedGlobalsOnly,
|
|
520
595
|
emitDeclarations
|
|
521
596
|
}) {
|
|
522
|
-
|
|
523
|
-
|
|
597
|
+
assertUniqueNames(declarations);
|
|
598
|
+
assertUniqueNames(globals);
|
|
524
599
|
const constants = globals.filter((list) => list.constant);
|
|
525
600
|
const constantLists = publishedGlobalsOnly ? constants.map((list) => ({
|
|
526
601
|
...list,
|
|
527
|
-
members: list.members.filter(
|
|
602
|
+
members: list.members.filter(isIntegerConstant)
|
|
528
603
|
})).filter((list) => list.members.length) : constants;
|
|
529
604
|
const variableLists = globals.filter((list) => !list.constant);
|
|
530
|
-
const constant =
|
|
531
|
-
function bound(expression) {
|
|
532
|
-
return integerExpression(expression, (name) => constant(name, null));
|
|
533
|
-
}
|
|
534
|
-
function dimensions(type) {
|
|
535
|
-
return type.dimensions.map(({ lower, upper }) => {
|
|
536
|
-
const start = bound(lower);
|
|
537
|
-
const end = bound(upper);
|
|
538
|
-
if (end < start || !Number.isSafeInteger(end - start + 1)) {
|
|
539
|
-
throw new Error(`invalid array bounds ${lower}..${upper}`);
|
|
540
|
-
}
|
|
541
|
-
return { start, end };
|
|
542
|
-
});
|
|
543
|
-
}
|
|
544
|
-
function declaration(name) {
|
|
545
|
-
const found = types.get(name.toUpperCase());
|
|
546
|
-
if (!found) {
|
|
547
|
-
throw new Error(`unknown IEC type ${name}`);
|
|
548
|
-
}
|
|
549
|
-
return found;
|
|
550
|
-
}
|
|
605
|
+
const { constant, integer, declaration, aliasTarget, bounds, enumMembers } = resolveDeclarations({ types: declarations, globals });
|
|
551
606
|
function tsType(type) {
|
|
552
607
|
if (type.kind === "array") {
|
|
553
|
-
|
|
608
|
+
bounds(type);
|
|
554
609
|
return type.dimensions.reduce((child) => `Array<${child}>`, tsType(type.element));
|
|
555
610
|
}
|
|
556
611
|
if (type.kind === "string") {
|
|
557
|
-
const length =
|
|
612
|
+
const length = integer(type.length);
|
|
558
613
|
if (length < 1) {
|
|
559
614
|
throw new Error(`invalid ${type.name} length ${length}`);
|
|
560
615
|
}
|
|
@@ -563,25 +618,23 @@ function emit(declarations, globals, {
|
|
|
563
618
|
return scalars[type.name.toUpperCase()] ?? declaration(type.name).name;
|
|
564
619
|
}
|
|
565
620
|
function resolved(type) {
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
const definition = declaration(type.name);
|
|
570
|
-
if (definition.kind === "alias") {
|
|
571
|
-
return resolved(definition.type);
|
|
572
|
-
}
|
|
573
|
-
if (definition.kind === "enum") {
|
|
574
|
-
return { kind: "named", name: definition.base };
|
|
621
|
+
const target = aliasTarget(type);
|
|
622
|
+
if (target.kind !== "named" || scalars[target.name.toUpperCase()]) {
|
|
623
|
+
return target;
|
|
575
624
|
}
|
|
576
|
-
|
|
625
|
+
const definition = declaration(target.name);
|
|
626
|
+
return definition.kind === "enum" ? { kind: "named", name: definition.base } : target;
|
|
577
627
|
}
|
|
578
628
|
function iecType(type) {
|
|
579
629
|
const actual = resolved(type);
|
|
580
630
|
if (actual.kind === "string") {
|
|
581
|
-
return
|
|
631
|
+
return stringTypeText({
|
|
632
|
+
wide: actual.name === "WSTRING",
|
|
633
|
+
capacity: integer(actual.length)
|
|
634
|
+
});
|
|
582
635
|
}
|
|
583
636
|
if (actual.kind === "array") {
|
|
584
|
-
return `ARRAY[${
|
|
637
|
+
return `ARRAY[${bounds(actual).map(({ start, end }) => `${start}..${end}`).join(", ")}] OF ${iecType(actual.element)}`;
|
|
585
638
|
}
|
|
586
639
|
return scalars[actual.name.toUpperCase()] ? actual.name.toUpperCase() : declaration(actual.name).name;
|
|
587
640
|
}
|
|
@@ -618,17 +671,19 @@ function emit(declarations, globals, {
|
|
|
618
671
|
ordered.push(type);
|
|
619
672
|
}
|
|
620
673
|
declarations.forEach(visit);
|
|
621
|
-
const reserved = new Set(
|
|
674
|
+
const reserved = new Set([
|
|
675
|
+
...javascriptReserved,
|
|
676
|
+
...Object.values(contractNames)
|
|
677
|
+
]);
|
|
622
678
|
for (const name of [
|
|
623
679
|
...declarations.map((type) => type.name),
|
|
624
680
|
...constantLists.map((list) => list.name)
|
|
625
681
|
]) {
|
|
626
|
-
if (!identifierPattern2.test(name) || reserved.has(name) ||
|
|
682
|
+
if (!identifierPattern2.test(name) || reserved.has(name) || isFieldList(name)) {
|
|
627
683
|
throw new Error(`name cannot be exported to TypeScript: ${name}`);
|
|
628
684
|
}
|
|
629
685
|
reserved.add(name);
|
|
630
686
|
}
|
|
631
|
-
const indexes = new Map(ordered.map((type, index) => [type.name, index]));
|
|
632
687
|
function complex(type) {
|
|
633
688
|
const actual = resolved(type);
|
|
634
689
|
if (actual.kind === "array") {
|
|
@@ -646,14 +701,14 @@ function emit(declarations, globals, {
|
|
|
646
701
|
function fields(type, path, description, depth = 0) {
|
|
647
702
|
const actual = resolved(type);
|
|
648
703
|
if (actual.kind === "named" && complex(actual)) {
|
|
649
|
-
const children =
|
|
704
|
+
const children = fieldList(ordered.indexOf(declaration(actual.name)));
|
|
650
705
|
if (path === '""') {
|
|
651
706
|
return children;
|
|
652
707
|
}
|
|
653
708
|
return `${children}.map((member) => ({ ...member, field: ${path} + "." + member.field }))`;
|
|
654
709
|
}
|
|
655
710
|
if (actual.kind === "array" && (complex(actual.element) || keyed(type))) {
|
|
656
|
-
const ranges =
|
|
711
|
+
const ranges = bounds(actual);
|
|
657
712
|
const coordinates = ranges.map((range, index) => `String(i${depth}_${index} + (${range.start}))`);
|
|
658
713
|
const arrayPath = `${path} + "[" + ${coordinates.join(' + "," + ')} + "]"`;
|
|
659
714
|
return ranges.reduceRight((child, range, index) => `Array.from({ length: ${range.end - range.start + 1} }, (_, i${depth}_${index}) => ${child}).flat()`, fields(actual.element, `(${arrayPath})`, description, depth + 1));
|
|
@@ -664,10 +719,10 @@ function emit(declarations, globals, {
|
|
|
664
719
|
const output = [
|
|
665
720
|
`// Generated by @tsplc/typegen. Edit the PLC sources and regenerate.
|
|
666
721
|
`,
|
|
667
|
-
`export interface
|
|
722
|
+
`export interface ${contractNames.field} { field: string; type: string; description: string; }
|
|
668
723
|
`
|
|
669
724
|
];
|
|
670
|
-
for (const type of ordered) {
|
|
725
|
+
for (const [index, type] of ordered.entries()) {
|
|
671
726
|
try {
|
|
672
727
|
const doc = documentation(type.description);
|
|
673
728
|
if (type.kind === "struct") {
|
|
@@ -676,7 +731,7 @@ ${type.members.map((member) => `${documentation(member.description)}${quote(memb
|
|
|
676
731
|
`)}
|
|
677
732
|
}
|
|
678
733
|
`));
|
|
679
|
-
output.push(`const
|
|
734
|
+
output.push(`const ${fieldList(index)}: ${contractNames.field}[] = [
|
|
680
735
|
${type.members.map((member) => `...${fields(member.type, quote(member.name), member.description)},`).join(`
|
|
681
736
|
`)}
|
|
682
737
|
];
|
|
@@ -684,22 +739,17 @@ ${type.members.map((member) => `...${fields(member.type, quote(member.name), mem
|
|
|
684
739
|
} else if (type.kind === "alias") {
|
|
685
740
|
output.push(...declare(`${doc}export type ${type.name} = ${tsType(type.type)};
|
|
686
741
|
`));
|
|
687
|
-
output.push(`const
|
|
742
|
+
output.push(`const ${fieldList(index)}: ${contractNames.field}[] = ${fields({ kind: "named", name: type.name }, '""', type.description)};
|
|
688
743
|
`);
|
|
689
744
|
} else {
|
|
690
|
-
if (!
|
|
745
|
+
if (!fitsNumber2(elementaryType3(type.base))) {
|
|
691
746
|
throw new Error(`unsupported enum base ${type.base}`);
|
|
692
747
|
}
|
|
693
|
-
const
|
|
694
|
-
|
|
695
|
-
const previous = [...entries.values()].at(-1) ?? -1;
|
|
696
|
-
const value = member.value === undefined ? previous + 1 : integerExpression(member.value, (name) => entries.get(name.toUpperCase()) ?? constant(name, null));
|
|
697
|
-
entries.set(member.name.toUpperCase(), value);
|
|
698
|
-
}
|
|
699
|
-
output.push(...declare(`${doc}export const ${type.name} = { ${type.members.map((member) => `${quote(member.name)}: ${entries.get(member.name.toUpperCase())}`).join(", ")} } as const;
|
|
748
|
+
const members = enumMembers(type);
|
|
749
|
+
output.push(...declare(`${doc}export const ${type.name} = { ${members.map(({ name, value }) => `${quote(name)}: ${value}`).join(", ")} } as const;
|
|
700
750
|
export type ${type.name} = (typeof ${type.name})[keyof typeof ${type.name}];
|
|
701
751
|
`));
|
|
702
|
-
output.push(`const
|
|
752
|
+
output.push(`const ${fieldList(index)}: ${contractNames.field}[] = ${fields({ kind: "named", name: type.base }, '""', type.description)};
|
|
703
753
|
`);
|
|
704
754
|
}
|
|
705
755
|
} catch (error) {
|
|
@@ -710,9 +760,9 @@ export type ${type.name} = (typeof ${type.name})[keyof typeof ${type.name}];
|
|
|
710
760
|
iecType(member.type),
|
|
711
761
|
fields(member.type, '""', member.description)
|
|
712
762
|
]));
|
|
713
|
-
output.push(`export const typeFields = {
|
|
763
|
+
output.push(`export const ${contractNames.typeFields} = {
|
|
714
764
|
${[
|
|
715
|
-
...ordered.map((type) => `${quote(type.name)}:
|
|
765
|
+
...ordered.map((type, index) => `${quote(type.name)}: ${fieldList(index)},`),
|
|
716
766
|
...[...inlineArrays].map(([type, members]) => `${quote(type)}: ${members},`)
|
|
717
767
|
].join(`
|
|
718
768
|
`)}
|
|
@@ -725,7 +775,7 @@ ${list.members.map((member) => `${documentation(member.description)}${quote(memb
|
|
|
725
775
|
} as const;
|
|
726
776
|
`);
|
|
727
777
|
}
|
|
728
|
-
output.push(...declare(`export interface
|
|
778
|
+
output.push(...declare(`export interface ${contractNames.globals} {
|
|
729
779
|
${variableLists.map((list) => `${documentation(list.description)}${quote(list.name)}: {
|
|
730
780
|
${list.members.map((member) => `${documentation(member.description)}${quote(member.name)}: ${tsType(member.type)};`).join(`
|
|
731
781
|
`)}
|
|
@@ -733,9 +783,9 @@ ${list.members.map((member) => `${documentation(member.description)}${quote(memb
|
|
|
733
783
|
`)}
|
|
734
784
|
}
|
|
735
785
|
`));
|
|
736
|
-
output.push(`export const globalVariableLists = ${JSON.stringify(Object.fromEntries(variableLists.map((list) => [list.name, list.description])), null, "\t")} as const;
|
|
786
|
+
output.push(`export const ${contractNames.globalVariableLists} = ${JSON.stringify(Object.fromEntries(variableLists.map((list) => [list.name, list.description])), null, "\t")} as const;
|
|
737
787
|
`);
|
|
738
|
-
output.push(`export const symbols = ${JSON.stringify(variableLists.flatMap((list) => list.members.map((member) => ({
|
|
788
|
+
output.push(`export const ${contractNames.symbols} = ${JSON.stringify(variableLists.flatMap((list) => list.members.map((member) => ({
|
|
739
789
|
name: member.name,
|
|
740
790
|
gvl: list.name,
|
|
741
791
|
type: member.type.kind === "named" && !scalars[member.type.name.toUpperCase()] ? declaration(member.type.name).name : iecType(member.type),
|
|
@@ -750,5 +800,5 @@ export {
|
|
|
750
800
|
stFiles
|
|
751
801
|
};
|
|
752
802
|
|
|
753
|
-
//# debugId=
|
|
803
|
+
//# debugId=40D88E7A4A266C3664756E2164756E21
|
|
754
804
|
//# sourceMappingURL=codegen.js.map
|