@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/cli.js
CHANGED
|
@@ -1,29 +1,59 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
|
|
3
3
|
// packages/typegen/src/cli.ts
|
|
4
|
-
import {
|
|
5
|
-
import { dirname as dirname2, resolve as resolve3 } from "node:path";
|
|
4
|
+
import { resolve as resolve3 } from "node:path";
|
|
6
5
|
import { parseArgs } from "node:util";
|
|
6
|
+
import { loadTsplcConfig } from "@tsplc/config";
|
|
7
|
+
import { configFileName } from "@tsplc/config/project-files";
|
|
7
8
|
|
|
8
9
|
// packages/typegen/src/codegen/generate.ts
|
|
9
|
-
import {
|
|
10
|
-
|
|
11
|
-
|
|
10
|
+
import {
|
|
11
|
+
elementaryType as elementaryType3,
|
|
12
|
+
elementaryTypesByName,
|
|
13
|
+
fitsNumber as fitsNumber2,
|
|
14
|
+
isIntegerValued as isIntegerValued2,
|
|
15
|
+
isWholeValue,
|
|
16
|
+
stringTypeText
|
|
17
|
+
} from "@tsplc/iec";
|
|
12
18
|
import { identifierPattern as identifierPattern2 } from "@tsplc/iec/st";
|
|
13
19
|
|
|
20
|
+
// packages/typegen/src/files.ts
|
|
21
|
+
import { readdir, readFile } from "node:fs/promises";
|
|
22
|
+
import { join } from "node:path";
|
|
23
|
+
var isMissingFile = (error) => error instanceof Error && ("code" in error) && error.code === "ENOENT";
|
|
24
|
+
var readIfPresent = (path) => readFile(path, "utf8").catch((error) => {
|
|
25
|
+
if (isMissingFile(error)) {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
throw error;
|
|
29
|
+
});
|
|
30
|
+
async function filesUnder(directory, extension, order) {
|
|
31
|
+
const pattern = new RegExp(`\\.${extension}$`, "i");
|
|
32
|
+
const entries = await readdir(directory, { withFileTypes: true });
|
|
33
|
+
const paths = await Promise.all(entries.sort((a, b) => order(a.name, b.name)).map(async (entry) => {
|
|
34
|
+
const path = join(directory, entry.name);
|
|
35
|
+
if (entry.isDirectory()) {
|
|
36
|
+
return filesUnder(path, extension, order);
|
|
37
|
+
}
|
|
38
|
+
return entry.isFile() && pattern.test(entry.name) ? [path] : [];
|
|
39
|
+
}));
|
|
40
|
+
return paths.flat();
|
|
41
|
+
}
|
|
42
|
+
var stFiles = (directory) => filesUnder(directory, "st", (a, b) => a < b ? -1 : 1);
|
|
43
|
+
|
|
14
44
|
// packages/typegen/src/codegen/constants.ts
|
|
15
45
|
import {
|
|
16
46
|
elementaryType,
|
|
17
47
|
elementaryTypes,
|
|
48
|
+
fitsNumber,
|
|
18
49
|
integerRange,
|
|
19
50
|
isIntegerValued
|
|
20
51
|
} from "@tsplc/iec";
|
|
21
|
-
|
|
22
|
-
const type = elementaryType(name);
|
|
23
|
-
return isIntegerValued(type) && type.bits <= 32;
|
|
24
|
-
};
|
|
52
|
+
import { identifierPart, identifierStart, integerLiteral } from "@tsplc/iec/st";
|
|
25
53
|
var integerRanges = new Map(elementaryTypes.filter(isIntegerValued).map((type) => [type.name, integerRange(type)]));
|
|
26
|
-
var
|
|
54
|
+
var identifier = `${identifierStart}${identifierPart}*`;
|
|
55
|
+
var startsWithIdentifier = new RegExp(`^${identifierStart}`);
|
|
56
|
+
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");
|
|
27
57
|
function integerExpression(text, lookup) {
|
|
28
58
|
const compact = text.replace(/\s+/g, "");
|
|
29
59
|
const tokens = (text.match(integerToken) ?? []).map((token) => token.replace(/\s+/g, ""));
|
|
@@ -62,13 +92,13 @@ function integerExpression(text, lookup) {
|
|
|
62
92
|
return value;
|
|
63
93
|
}
|
|
64
94
|
if (token && /^\d/.test(token)) {
|
|
65
|
-
const
|
|
66
|
-
if (
|
|
67
|
-
throw new Error(`invalid
|
|
95
|
+
const literal = integerLiteral(token);
|
|
96
|
+
if (literal === undefined) {
|
|
97
|
+
throw new Error(`invalid integer literal: ${token}`);
|
|
68
98
|
}
|
|
69
|
-
return safe(
|
|
99
|
+
return safe(Number(literal));
|
|
70
100
|
}
|
|
71
|
-
if (token &&
|
|
101
|
+
if (token && startsWithIdentifier.test(token)) {
|
|
72
102
|
return lookup(token);
|
|
73
103
|
}
|
|
74
104
|
throw new Error(`invalid integer expression: ${text}`);
|
|
@@ -95,11 +125,12 @@ function integerExpression(text, lookup) {
|
|
|
95
125
|
return value;
|
|
96
126
|
}
|
|
97
127
|
const value = sum();
|
|
98
|
-
if (position !== tokens.length
|
|
99
|
-
throw new Error(`invalid
|
|
128
|
+
if (position !== tokens.length) {
|
|
129
|
+
throw new Error(`invalid integer expression: ${text}`);
|
|
100
130
|
}
|
|
101
131
|
return value;
|
|
102
132
|
}
|
|
133
|
+
var isIntegerConstant = (member) => member.type.kind === "named" && fitsNumber(elementaryType(member.type.name.toUpperCase()));
|
|
103
134
|
function constantResolver(lists) {
|
|
104
135
|
const values = new Map;
|
|
105
136
|
const resolving = new Set;
|
|
@@ -123,7 +154,7 @@ function constantResolver(lists) {
|
|
|
123
154
|
throw new Error(`cyclic constant ${name}`);
|
|
124
155
|
}
|
|
125
156
|
const { member, list } = definition;
|
|
126
|
-
if (member.initial === undefined ||
|
|
157
|
+
if (member.initial === undefined || !isIntegerConstant(member)) {
|
|
127
158
|
throw new Error(`${list.source}: constant ${member.name} must have an integer type and initializer`);
|
|
128
159
|
}
|
|
129
160
|
resolving.add(definition.key);
|
|
@@ -136,72 +167,89 @@ function constantResolver(lists) {
|
|
|
136
167
|
}
|
|
137
168
|
|
|
138
169
|
// packages/typegen/src/codegen/parser.ts
|
|
170
|
+
import { readFile as readFile2 } from "node:fs/promises";
|
|
171
|
+
import { basename } from "node:path";
|
|
172
|
+
import { defaultStringLength } from "@tsplc/iec";
|
|
139
173
|
import {
|
|
140
174
|
blockCommentEnd,
|
|
141
175
|
directAddressEnd,
|
|
176
|
+
identifierPart as identifierPart2,
|
|
142
177
|
identifierPattern,
|
|
178
|
+
identifierStart as identifierStart2,
|
|
143
179
|
lineCommentEnd,
|
|
144
|
-
qualifiers
|
|
180
|
+
qualifiers,
|
|
181
|
+
stringEnd
|
|
145
182
|
} from "@tsplc/iec/st";
|
|
183
|
+
var pragmaEnd = (text, offset) => {
|
|
184
|
+
const next = text.slice(offset).search(/[}'"]/);
|
|
185
|
+
if (next < 0) {
|
|
186
|
+
return null;
|
|
187
|
+
}
|
|
188
|
+
const at = offset + next;
|
|
189
|
+
if (text[at] === "}") {
|
|
190
|
+
return at + 1;
|
|
191
|
+
}
|
|
192
|
+
const end = stringEnd(text, at);
|
|
193
|
+
return end === null ? null : pragmaEnd(text, end);
|
|
194
|
+
};
|
|
195
|
+
var codeToken = new RegExp(String.raw`^(?:\d[\d_]*#[\da-fA-F_]+|\d[\d_]*(?:\.(?!\.)[\d_]+)?(?:[eE][+-]?\d+)?|${identifierStart2}${identifierPart2}*|:=|\.\.|[[\]():;,.+\-*/#])`, "i");
|
|
196
|
+
function tokenAt(source, start) {
|
|
197
|
+
const { text } = source;
|
|
198
|
+
const offset = start + text.slice(start).search(/\S|$/);
|
|
199
|
+
if (offset === text.length) {
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
const rest = text.slice(offset);
|
|
203
|
+
if (rest.startsWith("(*")) {
|
|
204
|
+
const end = blockCommentEnd(text, offset);
|
|
205
|
+
if (end === null) {
|
|
206
|
+
throw new Error(`${source.name}: unterminated comment`);
|
|
207
|
+
}
|
|
208
|
+
const comment = text.slice(offset + 2, end - 2).trim();
|
|
209
|
+
return { text: comment, offset, end, kind: "comment" };
|
|
210
|
+
}
|
|
211
|
+
if (rest.startsWith("//")) {
|
|
212
|
+
const end = lineCommentEnd(text, offset);
|
|
213
|
+
const comment = text.slice(offset + 2, end).trim();
|
|
214
|
+
return { text: comment, offset, end, kind: "comment" };
|
|
215
|
+
}
|
|
216
|
+
const code = (kind, end) => ({
|
|
217
|
+
text: text.slice(offset, end),
|
|
218
|
+
offset,
|
|
219
|
+
end,
|
|
220
|
+
kind
|
|
221
|
+
});
|
|
222
|
+
const attributeEnd = rest.startsWith("{") ? pragmaEnd(text, offset + 1) : null;
|
|
223
|
+
if (attributeEnd !== null) {
|
|
224
|
+
return code("attribute", attributeEnd);
|
|
225
|
+
}
|
|
226
|
+
const addressEnd = directAddressEnd(text, offset);
|
|
227
|
+
if (addressEnd !== null) {
|
|
228
|
+
return code("code", addressEnd);
|
|
229
|
+
}
|
|
230
|
+
const literalEnd = rest.startsWith("'") || rest.startsWith('"') ? stringEnd(text, offset) : null;
|
|
231
|
+
if (literalEnd !== null) {
|
|
232
|
+
return code("code", literalEnd);
|
|
233
|
+
}
|
|
234
|
+
const word = codeToken.exec(rest);
|
|
235
|
+
if (!word) {
|
|
236
|
+
throw new Error(`${source.name}:${text.slice(0, offset).split(`
|
|
237
|
+
`).length}: unsupported token ${JSON.stringify(rest.slice(0, 24))}`);
|
|
238
|
+
}
|
|
239
|
+
return code("code", offset + word[0].length);
|
|
240
|
+
}
|
|
146
241
|
function tokenize(source) {
|
|
147
242
|
const tokens = [];
|
|
148
|
-
let
|
|
149
|
-
|
|
150
|
-
const rest = source.text.slice(offset);
|
|
151
|
-
const whitespace = /^\s+/.exec(rest);
|
|
152
|
-
if (whitespace) {
|
|
153
|
-
offset += whitespace[0].length;
|
|
154
|
-
continue;
|
|
155
|
-
}
|
|
156
|
-
if (rest.startsWith("(*")) {
|
|
157
|
-
const end = blockCommentEnd(source.text, offset);
|
|
158
|
-
if (end === null) {
|
|
159
|
-
throw new Error(`${source.name}: unterminated comment`);
|
|
160
|
-
}
|
|
161
|
-
tokens.push({
|
|
162
|
-
text: source.text.slice(offset + 2, end - 2).trim(),
|
|
163
|
-
offset,
|
|
164
|
-
kind: "comment"
|
|
165
|
-
});
|
|
166
|
-
offset = end;
|
|
167
|
-
continue;
|
|
168
|
-
}
|
|
169
|
-
if (rest.startsWith("//")) {
|
|
170
|
-
const end = lineCommentEnd(source.text, offset);
|
|
171
|
-
tokens.push({
|
|
172
|
-
text: source.text.slice(offset + 2, end).trim(),
|
|
173
|
-
offset,
|
|
174
|
-
kind: "comment"
|
|
175
|
-
});
|
|
176
|
-
offset = end;
|
|
177
|
-
continue;
|
|
178
|
-
}
|
|
179
|
-
const attribute = /^\{(?:[^}'"]|'(?:\$[\s\S]|''|[^'])*'|"(?:\$[\s\S]|""|[^"])*")*\}/.exec(rest);
|
|
180
|
-
if (attribute) {
|
|
181
|
-
tokens.push({ text: attribute[0], offset, kind: "attribute" });
|
|
182
|
-
offset += attribute[0].length;
|
|
183
|
-
continue;
|
|
184
|
-
}
|
|
185
|
-
const addressEnd = directAddressEnd(source.text, offset);
|
|
186
|
-
if (addressEnd !== null) {
|
|
187
|
-
tokens.push({
|
|
188
|
-
text: source.text.slice(offset, addressEnd),
|
|
189
|
-
offset,
|
|
190
|
-
kind: "code"
|
|
191
|
-
});
|
|
192
|
-
offset = addressEnd;
|
|
193
|
-
continue;
|
|
194
|
-
}
|
|
195
|
-
const code = /^(?:'(?:\$[\s\S]|''|[^'])*'|"(?:\$[\s\S]|""|[^"])*"|\d[\d_]*#[\da-fA-F_]+|\d[\d_]*(?:\.(?!\.)[\d_]+)?(?:[eE][+-]?\d+)?|[A-Za-z_]\w*|:=|\.\.|[[\]():;,.+\-*/#])/i.exec(rest);
|
|
196
|
-
if (!code) {
|
|
197
|
-
throw new Error(`${source.name}:${source.text.slice(0, offset).split(`
|
|
198
|
-
`).length}: unsupported token ${JSON.stringify(rest.slice(0, 24))}`);
|
|
199
|
-
}
|
|
200
|
-
tokens.push({ text: code[0], offset, kind: "code" });
|
|
201
|
-
offset += code[0].length;
|
|
243
|
+
for (let token = tokenAt(source, 0);token; token = tokenAt(source, token.end)) {
|
|
244
|
+
tokens.push(token);
|
|
202
245
|
}
|
|
203
246
|
return tokens;
|
|
204
247
|
}
|
|
248
|
+
var codeTokenAt = (source, offset) => {
|
|
249
|
+
const token = tokenAt(source, offset);
|
|
250
|
+
return token && token.kind !== "code" ? codeTokenAt(source, token.end) : token;
|
|
251
|
+
};
|
|
252
|
+
var firstCodeToken = (source) => codeTokenAt(source, 0)?.text;
|
|
205
253
|
|
|
206
254
|
class Parser {
|
|
207
255
|
source;
|
|
@@ -303,7 +351,11 @@ class Parser {
|
|
|
303
351
|
if (upper === "STRING" || upper === "WSTRING") {
|
|
304
352
|
const opening = this.peek();
|
|
305
353
|
if (opening !== "(" && opening !== "[") {
|
|
306
|
-
return {
|
|
354
|
+
return {
|
|
355
|
+
kind: "string",
|
|
356
|
+
name: upper,
|
|
357
|
+
length: String(defaultStringLength)
|
|
358
|
+
};
|
|
307
359
|
}
|
|
308
360
|
this.take();
|
|
309
361
|
const closing = opening === "(" ? ")" : "]";
|
|
@@ -442,126 +494,143 @@ function parseDeclarations(source) {
|
|
|
442
494
|
function parseGlobals(source, name) {
|
|
443
495
|
return new Parser(source).globals(name);
|
|
444
496
|
}
|
|
497
|
+
var readSource = async (name) => ({
|
|
498
|
+
name,
|
|
499
|
+
text: await readFile2(name, "utf8")
|
|
500
|
+
});
|
|
501
|
+
async function parseSources(files) {
|
|
502
|
+
return {
|
|
503
|
+
types: (await Promise.all(files.types.map(readSource))).flatMap(parseDeclarations),
|
|
504
|
+
globals: (await Promise.all(files.globals.map(readSource))).map((source) => parseGlobals(source, basename(source.name).replace(/\.st$/i, "")))
|
|
505
|
+
};
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
// packages/typegen/src/codegen/resolution.ts
|
|
509
|
+
import { elementaryType as elementaryType2 } from "@tsplc/iec";
|
|
510
|
+
function resolveDeclarations({
|
|
511
|
+
types,
|
|
512
|
+
globals
|
|
513
|
+
}) {
|
|
514
|
+
const declarations = new Map(types.map((declaration) => [declaration.name.toUpperCase(), declaration]));
|
|
515
|
+
const constant = constantResolver(globals.filter((list) => list.constant));
|
|
516
|
+
const integer = (expression) => integerExpression(expression, (name) => constant(name, null));
|
|
517
|
+
const declaration = (name) => {
|
|
518
|
+
const found = declarations.get(name.toUpperCase());
|
|
519
|
+
if (!found) {
|
|
520
|
+
throw new Error(`unknown IEC type ${name}`);
|
|
521
|
+
}
|
|
522
|
+
return found;
|
|
523
|
+
};
|
|
524
|
+
const aliasTarget = (reference) => {
|
|
525
|
+
if (reference.kind !== "named" || elementaryType2(reference.name.toUpperCase())) {
|
|
526
|
+
return reference;
|
|
527
|
+
}
|
|
528
|
+
const named = declaration(reference.name);
|
|
529
|
+
return named.kind === "alias" ? aliasTarget(named.type) : reference;
|
|
530
|
+
};
|
|
531
|
+
const bounds = (array) => array.dimensions.map(({ lower, upper }) => {
|
|
532
|
+
const start = integer(lower);
|
|
533
|
+
const end = integer(upper);
|
|
534
|
+
if (end < start || !Number.isSafeInteger(end - start + 1)) {
|
|
535
|
+
throw new Error(`invalid array bounds ${lower}..${upper}`);
|
|
536
|
+
}
|
|
537
|
+
return { start, end };
|
|
538
|
+
});
|
|
539
|
+
const enumMembers = (enumeration) => {
|
|
540
|
+
const members = [];
|
|
541
|
+
for (const member of enumeration.members) {
|
|
542
|
+
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));
|
|
543
|
+
members.push({ name: member.name, value });
|
|
544
|
+
}
|
|
545
|
+
return members;
|
|
546
|
+
};
|
|
547
|
+
return { constant, integer, declaration, aliasTarget, bounds, enumMembers };
|
|
548
|
+
}
|
|
445
549
|
|
|
446
550
|
// packages/typegen/src/codegen/generate.ts
|
|
447
551
|
var scalarType = (type) => {
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
return "boolean";
|
|
451
|
-
case "integer":
|
|
452
|
-
case "bits":
|
|
453
|
-
return type.bits === 64 ? "bigint" : "number";
|
|
454
|
-
case "real":
|
|
455
|
-
return "number";
|
|
456
|
-
case "duration":
|
|
457
|
-
case "date":
|
|
458
|
-
case "timeOfDay":
|
|
459
|
-
case "dateTime":
|
|
460
|
-
return type.bits === 32 ? "number" : undefined;
|
|
461
|
-
case "char":
|
|
462
|
-
case "string":
|
|
463
|
-
return;
|
|
552
|
+
if (type.family === "bool") {
|
|
553
|
+
return "boolean";
|
|
464
554
|
}
|
|
555
|
+
return isIntegerValued2(type) && !fitsNumber2(type) ? "bigint" : "number";
|
|
465
556
|
};
|
|
466
|
-
var scalars = Object.fromEntries([...elementaryTypesByName].flatMap(([name, type]) =>
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
if (entry.isDirectory()) {
|
|
480
|
-
return stFiles(file);
|
|
481
|
-
}
|
|
482
|
-
return entry.isFile() && /\.st$/i.test(file) ? [file] : [];
|
|
483
|
-
}));
|
|
484
|
-
return paths.flat();
|
|
485
|
-
}
|
|
557
|
+
var scalars = Object.fromEntries([...elementaryTypesByName].flatMap(([name, type]) => isWholeValue(type) ? [[name, scalarType(type)]] : []));
|
|
558
|
+
var sourceFiles = async (setting) => typeof setting === "string" ? stFiles(setting) : setting;
|
|
559
|
+
var contractNames = {
|
|
560
|
+
field: "PlcField",
|
|
561
|
+
globals: "PlcGlobals",
|
|
562
|
+
typeFields: "typeFields",
|
|
563
|
+
globalVariableLists: "globalVariableLists",
|
|
564
|
+
symbols: "symbols",
|
|
565
|
+
publication: "publication"
|
|
566
|
+
};
|
|
567
|
+
var fieldList = (index) => `_fields${index}`;
|
|
568
|
+
var isFieldList = (name) => /^_fields\d+$/.test(name);
|
|
569
|
+
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(" ");
|
|
486
570
|
var quote = (value) => JSON.stringify(value);
|
|
487
571
|
var documentation = (value) => value ? `/** ${value.replace(/\*\//g, "* /").replace(/\r?\n/g, `
|
|
488
572
|
* `)} */
|
|
489
573
|
` : "";
|
|
490
|
-
function
|
|
491
|
-
const
|
|
492
|
-
for (const
|
|
493
|
-
const key =
|
|
494
|
-
|
|
495
|
-
|
|
574
|
+
function assertUniqueNames(items) {
|
|
575
|
+
const seen = new Map;
|
|
576
|
+
for (const { name, source } of items) {
|
|
577
|
+
const key = name.toUpperCase();
|
|
578
|
+
const previous = seen.get(key);
|
|
579
|
+
if (previous !== undefined) {
|
|
580
|
+
throw new Error(`${source}: duplicate declaration ${name} (also in ${previous})`);
|
|
496
581
|
}
|
|
497
|
-
|
|
582
|
+
seen.set(key, source);
|
|
498
583
|
}
|
|
499
|
-
return result;
|
|
500
584
|
}
|
|
501
|
-
var readSources = (files) => Promise.all(files.map(async (name) => ({ name, text: await readFile(name, "utf8") })));
|
|
502
585
|
async function generateTypes(options) {
|
|
503
|
-
const typeFiles =
|
|
504
|
-
const
|
|
505
|
-
const globalFiles = typeof options.globals === "string" ? await stFiles(options.globals) : options.globals ?? [];
|
|
586
|
+
const typeFiles = await sourceFiles(options.types);
|
|
587
|
+
const globalFiles = await sourceFiles(options.globals);
|
|
506
588
|
if (!typeFiles.length && !globalFiles.length && (typeof options.types === "string" || typeof options.globals === "string")) {
|
|
507
589
|
throw new Error(`no .st declarations found in ${typeof options.types === "string" ? options.types : "the selected source files"}`);
|
|
508
590
|
}
|
|
509
|
-
const globals =
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
591
|
+
const { types: declarations, globals } = await parseSources({
|
|
592
|
+
types: typeFiles,
|
|
593
|
+
globals: globalFiles
|
|
594
|
+
});
|
|
595
|
+
const { publication } = options;
|
|
596
|
+
const contract = emit(declarations, publication ? published(globals, publication) : globals, {
|
|
597
|
+
publishedGlobalsOnly: publication !== null,
|
|
598
|
+
emitDeclarations: options.declarations
|
|
599
|
+
});
|
|
600
|
+
return publication ? `${contract}
|
|
601
|
+
export const ${contractNames.publication} = ${JSON.stringify(publication, null, 2)} as const;
|
|
514
602
|
` : contract;
|
|
515
603
|
}
|
|
516
604
|
function published(globals, publication) {
|
|
605
|
+
const selected = new Set([
|
|
606
|
+
...publication.production,
|
|
607
|
+
...publication.development
|
|
608
|
+
]);
|
|
517
609
|
return globals.map((list) => list.constant ? list : {
|
|
518
610
|
...list,
|
|
519
|
-
members: list.members.filter((member) =>
|
|
520
|
-
...publication.production,
|
|
521
|
-
...publication.development
|
|
522
|
-
].includes(`${list.name}.${member.name}`) : member.symbol !== undefined)
|
|
611
|
+
members: list.members.filter((member) => selected.has(`${list.name}.${member.name}`))
|
|
523
612
|
}).filter((list) => list.constant || list.members.length);
|
|
524
613
|
}
|
|
525
614
|
function emit(declarations, globals, {
|
|
526
615
|
publishedGlobalsOnly,
|
|
527
616
|
emitDeclarations
|
|
528
617
|
}) {
|
|
529
|
-
|
|
530
|
-
|
|
618
|
+
assertUniqueNames(declarations);
|
|
619
|
+
assertUniqueNames(globals);
|
|
531
620
|
const constants = globals.filter((list) => list.constant);
|
|
532
621
|
const constantLists = publishedGlobalsOnly ? constants.map((list) => ({
|
|
533
622
|
...list,
|
|
534
|
-
members: list.members.filter(
|
|
623
|
+
members: list.members.filter(isIntegerConstant)
|
|
535
624
|
})).filter((list) => list.members.length) : constants;
|
|
536
625
|
const variableLists = globals.filter((list) => !list.constant);
|
|
537
|
-
const constant =
|
|
538
|
-
function bound(expression) {
|
|
539
|
-
return integerExpression(expression, (name) => constant(name, null));
|
|
540
|
-
}
|
|
541
|
-
function dimensions(type) {
|
|
542
|
-
return type.dimensions.map(({ lower, upper }) => {
|
|
543
|
-
const start = bound(lower);
|
|
544
|
-
const end = bound(upper);
|
|
545
|
-
if (end < start || !Number.isSafeInteger(end - start + 1)) {
|
|
546
|
-
throw new Error(`invalid array bounds ${lower}..${upper}`);
|
|
547
|
-
}
|
|
548
|
-
return { start, end };
|
|
549
|
-
});
|
|
550
|
-
}
|
|
551
|
-
function declaration(name) {
|
|
552
|
-
const found = types.get(name.toUpperCase());
|
|
553
|
-
if (!found) {
|
|
554
|
-
throw new Error(`unknown IEC type ${name}`);
|
|
555
|
-
}
|
|
556
|
-
return found;
|
|
557
|
-
}
|
|
626
|
+
const { constant, integer, declaration, aliasTarget, bounds, enumMembers } = resolveDeclarations({ types: declarations, globals });
|
|
558
627
|
function tsType(type) {
|
|
559
628
|
if (type.kind === "array") {
|
|
560
|
-
|
|
629
|
+
bounds(type);
|
|
561
630
|
return type.dimensions.reduce((child) => `Array<${child}>`, tsType(type.element));
|
|
562
631
|
}
|
|
563
632
|
if (type.kind === "string") {
|
|
564
|
-
const length =
|
|
633
|
+
const length = integer(type.length);
|
|
565
634
|
if (length < 1) {
|
|
566
635
|
throw new Error(`invalid ${type.name} length ${length}`);
|
|
567
636
|
}
|
|
@@ -570,25 +639,23 @@ function emit(declarations, globals, {
|
|
|
570
639
|
return scalars[type.name.toUpperCase()] ?? declaration(type.name).name;
|
|
571
640
|
}
|
|
572
641
|
function resolved(type) {
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
const definition = declaration(type.name);
|
|
577
|
-
if (definition.kind === "alias") {
|
|
578
|
-
return resolved(definition.type);
|
|
579
|
-
}
|
|
580
|
-
if (definition.kind === "enum") {
|
|
581
|
-
return { kind: "named", name: definition.base };
|
|
642
|
+
const target = aliasTarget(type);
|
|
643
|
+
if (target.kind !== "named" || scalars[target.name.toUpperCase()]) {
|
|
644
|
+
return target;
|
|
582
645
|
}
|
|
583
|
-
|
|
646
|
+
const definition = declaration(target.name);
|
|
647
|
+
return definition.kind === "enum" ? { kind: "named", name: definition.base } : target;
|
|
584
648
|
}
|
|
585
649
|
function iecType(type) {
|
|
586
650
|
const actual = resolved(type);
|
|
587
651
|
if (actual.kind === "string") {
|
|
588
|
-
return
|
|
652
|
+
return stringTypeText({
|
|
653
|
+
wide: actual.name === "WSTRING",
|
|
654
|
+
capacity: integer(actual.length)
|
|
655
|
+
});
|
|
589
656
|
}
|
|
590
657
|
if (actual.kind === "array") {
|
|
591
|
-
return `ARRAY[${
|
|
658
|
+
return `ARRAY[${bounds(actual).map(({ start, end }) => `${start}..${end}`).join(", ")}] OF ${iecType(actual.element)}`;
|
|
592
659
|
}
|
|
593
660
|
return scalars[actual.name.toUpperCase()] ? actual.name.toUpperCase() : declaration(actual.name).name;
|
|
594
661
|
}
|
|
@@ -625,17 +692,19 @@ function emit(declarations, globals, {
|
|
|
625
692
|
ordered.push(type);
|
|
626
693
|
}
|
|
627
694
|
declarations.forEach(visit);
|
|
628
|
-
const reserved = new Set(
|
|
695
|
+
const reserved = new Set([
|
|
696
|
+
...javascriptReserved,
|
|
697
|
+
...Object.values(contractNames)
|
|
698
|
+
]);
|
|
629
699
|
for (const name of [
|
|
630
700
|
...declarations.map((type) => type.name),
|
|
631
701
|
...constantLists.map((list) => list.name)
|
|
632
702
|
]) {
|
|
633
|
-
if (!identifierPattern2.test(name) || reserved.has(name) ||
|
|
703
|
+
if (!identifierPattern2.test(name) || reserved.has(name) || isFieldList(name)) {
|
|
634
704
|
throw new Error(`name cannot be exported to TypeScript: ${name}`);
|
|
635
705
|
}
|
|
636
706
|
reserved.add(name);
|
|
637
707
|
}
|
|
638
|
-
const indexes = new Map(ordered.map((type, index) => [type.name, index]));
|
|
639
708
|
function complex(type) {
|
|
640
709
|
const actual = resolved(type);
|
|
641
710
|
if (actual.kind === "array") {
|
|
@@ -653,14 +722,14 @@ function emit(declarations, globals, {
|
|
|
653
722
|
function fields(type, path, description, depth = 0) {
|
|
654
723
|
const actual = resolved(type);
|
|
655
724
|
if (actual.kind === "named" && complex(actual)) {
|
|
656
|
-
const children =
|
|
725
|
+
const children = fieldList(ordered.indexOf(declaration(actual.name)));
|
|
657
726
|
if (path === '""') {
|
|
658
727
|
return children;
|
|
659
728
|
}
|
|
660
729
|
return `${children}.map((member) => ({ ...member, field: ${path} + "." + member.field }))`;
|
|
661
730
|
}
|
|
662
731
|
if (actual.kind === "array" && (complex(actual.element) || keyed(type))) {
|
|
663
|
-
const ranges =
|
|
732
|
+
const ranges = bounds(actual);
|
|
664
733
|
const coordinates = ranges.map((range, index) => `String(i${depth}_${index} + (${range.start}))`);
|
|
665
734
|
const arrayPath = `${path} + "[" + ${coordinates.join(' + "," + ')} + "]"`;
|
|
666
735
|
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));
|
|
@@ -671,10 +740,10 @@ function emit(declarations, globals, {
|
|
|
671
740
|
const output = [
|
|
672
741
|
`// Generated by @tsplc/typegen. Edit the PLC sources and regenerate.
|
|
673
742
|
`,
|
|
674
|
-
`export interface
|
|
743
|
+
`export interface ${contractNames.field} { field: string; type: string; description: string; }
|
|
675
744
|
`
|
|
676
745
|
];
|
|
677
|
-
for (const type of ordered) {
|
|
746
|
+
for (const [index, type] of ordered.entries()) {
|
|
678
747
|
try {
|
|
679
748
|
const doc = documentation(type.description);
|
|
680
749
|
if (type.kind === "struct") {
|
|
@@ -683,7 +752,7 @@ ${type.members.map((member) => `${documentation(member.description)}${quote(memb
|
|
|
683
752
|
`)}
|
|
684
753
|
}
|
|
685
754
|
`));
|
|
686
|
-
output.push(`const
|
|
755
|
+
output.push(`const ${fieldList(index)}: ${contractNames.field}[] = [
|
|
687
756
|
${type.members.map((member) => `...${fields(member.type, quote(member.name), member.description)},`).join(`
|
|
688
757
|
`)}
|
|
689
758
|
];
|
|
@@ -691,22 +760,17 @@ ${type.members.map((member) => `...${fields(member.type, quote(member.name), mem
|
|
|
691
760
|
} else if (type.kind === "alias") {
|
|
692
761
|
output.push(...declare(`${doc}export type ${type.name} = ${tsType(type.type)};
|
|
693
762
|
`));
|
|
694
|
-
output.push(`const
|
|
763
|
+
output.push(`const ${fieldList(index)}: ${contractNames.field}[] = ${fields({ kind: "named", name: type.name }, '""', type.description)};
|
|
695
764
|
`);
|
|
696
765
|
} else {
|
|
697
|
-
if (!
|
|
766
|
+
if (!fitsNumber2(elementaryType3(type.base))) {
|
|
698
767
|
throw new Error(`unsupported enum base ${type.base}`);
|
|
699
768
|
}
|
|
700
|
-
const
|
|
701
|
-
|
|
702
|
-
const previous = [...entries.values()].at(-1) ?? -1;
|
|
703
|
-
const value = member.value === undefined ? previous + 1 : integerExpression(member.value, (name) => entries.get(name.toUpperCase()) ?? constant(name, null));
|
|
704
|
-
entries.set(member.name.toUpperCase(), value);
|
|
705
|
-
}
|
|
706
|
-
output.push(...declare(`${doc}export const ${type.name} = { ${type.members.map((member) => `${quote(member.name)}: ${entries.get(member.name.toUpperCase())}`).join(", ")} } as const;
|
|
769
|
+
const members = enumMembers(type);
|
|
770
|
+
output.push(...declare(`${doc}export const ${type.name} = { ${members.map(({ name, value }) => `${quote(name)}: ${value}`).join(", ")} } as const;
|
|
707
771
|
export type ${type.name} = (typeof ${type.name})[keyof typeof ${type.name}];
|
|
708
772
|
`));
|
|
709
|
-
output.push(`const
|
|
773
|
+
output.push(`const ${fieldList(index)}: ${contractNames.field}[] = ${fields({ kind: "named", name: type.base }, '""', type.description)};
|
|
710
774
|
`);
|
|
711
775
|
}
|
|
712
776
|
} catch (error) {
|
|
@@ -717,9 +781,9 @@ export type ${type.name} = (typeof ${type.name})[keyof typeof ${type.name}];
|
|
|
717
781
|
iecType(member.type),
|
|
718
782
|
fields(member.type, '""', member.description)
|
|
719
783
|
]));
|
|
720
|
-
output.push(`export const typeFields = {
|
|
784
|
+
output.push(`export const ${contractNames.typeFields} = {
|
|
721
785
|
${[
|
|
722
|
-
...ordered.map((type) => `${quote(type.name)}:
|
|
786
|
+
...ordered.map((type, index) => `${quote(type.name)}: ${fieldList(index)},`),
|
|
723
787
|
...[...inlineArrays].map(([type, members]) => `${quote(type)}: ${members},`)
|
|
724
788
|
].join(`
|
|
725
789
|
`)}
|
|
@@ -732,7 +796,7 @@ ${list.members.map((member) => `${documentation(member.description)}${quote(memb
|
|
|
732
796
|
} as const;
|
|
733
797
|
`);
|
|
734
798
|
}
|
|
735
|
-
output.push(...declare(`export interface
|
|
799
|
+
output.push(...declare(`export interface ${contractNames.globals} {
|
|
736
800
|
${variableLists.map((list) => `${documentation(list.description)}${quote(list.name)}: {
|
|
737
801
|
${list.members.map((member) => `${documentation(member.description)}${quote(member.name)}: ${tsType(member.type)};`).join(`
|
|
738
802
|
`)}
|
|
@@ -740,9 +804,9 @@ ${list.members.map((member) => `${documentation(member.description)}${quote(memb
|
|
|
740
804
|
`)}
|
|
741
805
|
}
|
|
742
806
|
`));
|
|
743
|
-
output.push(`export const globalVariableLists = ${JSON.stringify(Object.fromEntries(variableLists.map((list) => [list.name, list.description])), null, "\t")} as const;
|
|
807
|
+
output.push(`export const ${contractNames.globalVariableLists} = ${JSON.stringify(Object.fromEntries(variableLists.map((list) => [list.name, list.description])), null, "\t")} as const;
|
|
744
808
|
`);
|
|
745
|
-
output.push(`export const symbols = ${JSON.stringify(variableLists.flatMap((list) => list.members.map((member) => ({
|
|
809
|
+
output.push(`export const ${contractNames.symbols} = ${JSON.stringify(variableLists.flatMap((list) => list.members.map((member) => ({
|
|
746
810
|
name: member.name,
|
|
747
811
|
gvl: list.name,
|
|
748
812
|
type: member.type.kind === "named" && !scalars[member.type.name.toUpperCase()] ? declaration(member.type.name).name : iecType(member.type),
|
|
@@ -753,51 +817,68 @@ ${list.members.map((member) => `${documentation(member.description)}${quote(memb
|
|
|
753
817
|
`);
|
|
754
818
|
}
|
|
755
819
|
|
|
820
|
+
// packages/typegen/src/outputs.ts
|
|
821
|
+
import { randomUUID } from "node:crypto";
|
|
822
|
+
import { mkdir, rename, rm, writeFile } from "node:fs/promises";
|
|
823
|
+
import { dirname } from "node:path";
|
|
824
|
+
import { format } from "prettier";
|
|
825
|
+
var formatTypeScript = (source) => format(source, { parser: "typescript" });
|
|
826
|
+
async function writeOutputs(outputs) {
|
|
827
|
+
for (const { path, content } of outputs) {
|
|
828
|
+
if (content === null) {
|
|
829
|
+
await rm(path, { force: true });
|
|
830
|
+
continue;
|
|
831
|
+
}
|
|
832
|
+
await mkdir(dirname(path), { recursive: true });
|
|
833
|
+
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
834
|
+
try {
|
|
835
|
+
await writeFile(temporary, content);
|
|
836
|
+
await rename(temporary, path);
|
|
837
|
+
} finally {
|
|
838
|
+
await rm(temporary, { force: true });
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
async function checkOutputs(outputs) {
|
|
843
|
+
for (const { path, content } of outputs) {
|
|
844
|
+
const actual = await readIfPresent(path);
|
|
845
|
+
const normalized = actual !== null && /\.ts$/i.test(path) ? await formatTypeScript(actual).catch(() => actual) : actual;
|
|
846
|
+
if (normalized !== content) {
|
|
847
|
+
throw new Error(`Generated file is missing or stale: ${path}`);
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
|
|
756
852
|
// packages/typegen/src/project.ts
|
|
757
|
-
import {
|
|
758
|
-
import { dirname, resolve as resolve2 } from "node:path";
|
|
853
|
+
import { resolve as resolve2 } from "node:path";
|
|
759
854
|
import {
|
|
760
855
|
ioSymbolsSchema,
|
|
761
|
-
loadTsplcConfig,
|
|
762
856
|
publicationSchema,
|
|
763
|
-
|
|
857
|
+
typegenSettings
|
|
764
858
|
} from "@tsplc/config";
|
|
765
859
|
import {
|
|
766
860
|
emittedFiles,
|
|
767
861
|
emittedStDirectory,
|
|
768
|
-
projectSnapshotFile
|
|
862
|
+
projectSnapshotFile,
|
|
863
|
+
stRoot
|
|
769
864
|
} from "@tsplc/config/project-files";
|
|
770
|
-
import {
|
|
865
|
+
import { isWithin } from "@tsplc/iec/st";
|
|
771
866
|
|
|
772
867
|
// packages/typegen/src/codegen/declarations.ts
|
|
773
|
-
import { readFile as
|
|
774
|
-
import { blockCommentEnd as blockCommentEnd2, lineCommentEnd as lineCommentEnd2 } from "@tsplc/iec/st";
|
|
775
|
-
var codeStart = (text, offset) => {
|
|
776
|
-
const start = offset + text.slice(offset).search(/\S|$/);
|
|
777
|
-
if (text.startsWith("(*", start)) {
|
|
778
|
-
const end = blockCommentEnd2(text, start);
|
|
779
|
-
return end === null ? start : codeStart(text, end);
|
|
780
|
-
}
|
|
781
|
-
if (text.startsWith("//", start)) {
|
|
782
|
-
return codeStart(text, lineCommentEnd2(text, start));
|
|
783
|
-
}
|
|
784
|
-
if (text.startsWith("{", start)) {
|
|
785
|
-
const end = text.indexOf("}", start);
|
|
786
|
-
return end < 0 ? start : codeStart(text, end + 1);
|
|
787
|
-
}
|
|
788
|
-
return start;
|
|
789
|
-
};
|
|
868
|
+
import { readFile as readFile3 } from "node:fs/promises";
|
|
790
869
|
var declarationFiles = async (files) => {
|
|
791
870
|
const sorted = {
|
|
792
871
|
types: [],
|
|
793
872
|
globals: []
|
|
794
873
|
};
|
|
795
874
|
for (const file of files) {
|
|
796
|
-
const
|
|
797
|
-
|
|
798
|
-
|
|
875
|
+
const keyword = firstCodeToken({
|
|
876
|
+
name: file,
|
|
877
|
+
text: await readFile3(file, "utf8")
|
|
878
|
+
})?.toUpperCase();
|
|
879
|
+
if (keyword === "TYPE") {
|
|
799
880
|
sorted.types.push(file);
|
|
800
|
-
} else if (
|
|
881
|
+
} else if (keyword === "VAR_GLOBAL") {
|
|
801
882
|
sorted.globals.push(file);
|
|
802
883
|
}
|
|
803
884
|
}
|
|
@@ -805,14 +886,35 @@ var declarationFiles = async (files) => {
|
|
|
805
886
|
};
|
|
806
887
|
|
|
807
888
|
// packages/typegen/src/hardware.ts
|
|
808
|
-
import {
|
|
889
|
+
import { readFile as readFile4 } from "node:fs/promises";
|
|
809
890
|
import { resolve } from "node:path";
|
|
891
|
+
import { tsplcConfigSchema } from "@tsplc/config/schema";
|
|
892
|
+
|
|
893
|
+
// packages/typegen/src/hardware/catalog.ts
|
|
894
|
+
var deviceChannel = (catalog, binding) => catalog.devices.find((device) => device.id === binding.device)?.channels.find((channel) => channel.id === binding.channel);
|
|
895
|
+
function boundChannel(catalog, symbol, binding) {
|
|
896
|
+
const channel = deviceChannel(catalog, binding);
|
|
897
|
+
if (!channel?.address) {
|
|
898
|
+
throw new Error(`${symbol}: unknown or unaddressable channel ${binding.device}.${binding.channel}.`);
|
|
899
|
+
}
|
|
900
|
+
return { ...channel, address: channel.address };
|
|
901
|
+
}
|
|
810
902
|
|
|
811
903
|
// packages/typegen/src/hardware/channels.ts
|
|
812
|
-
import { ioScalarBits } from "@tsplc/iec";
|
|
904
|
+
import { arrayTypeText, ioScalarBits } from "@tsplc/iec";
|
|
813
905
|
|
|
814
906
|
// packages/typegen/src/hardware/process-image.ts
|
|
815
|
-
import {
|
|
907
|
+
import {
|
|
908
|
+
elementaryTypes as elementaryTypes2,
|
|
909
|
+
ioArray,
|
|
910
|
+
ioScalar,
|
|
911
|
+
isIntegerValued as isIntegerValued3,
|
|
912
|
+
isWholeValue as isWholeValue2,
|
|
913
|
+
sizePrefix,
|
|
914
|
+
sizePrefixes
|
|
915
|
+
} from "@tsplc/iec";
|
|
916
|
+
var scalarLayout = (scalar) => isIntegerValued3(scalar) ? `INT${scalar.bits}` : scalar.name;
|
|
917
|
+
var scalarLayoutBits = new Map(elementaryTypes2.filter(isWholeValue2).map((scalar) => [scalarLayout(scalar), scalar.bits]));
|
|
816
918
|
function ioLayout(type) {
|
|
817
919
|
const array = ioArray(type.trim());
|
|
818
920
|
if (array) {
|
|
@@ -820,11 +922,9 @@ function ioLayout(type) {
|
|
|
820
922
|
return element && element !== "BOOL" ? `${array.length}x${element}` : undefined;
|
|
821
923
|
}
|
|
822
924
|
const scalar = ioScalar(type);
|
|
823
|
-
|
|
824
|
-
return `INT${scalar.bits}`;
|
|
825
|
-
}
|
|
826
|
-
return scalar?.name;
|
|
925
|
+
return scalar && scalarLayout(scalar);
|
|
827
926
|
}
|
|
927
|
+
var layoutBits = (layout) => scalarLayoutBits.get(layout.replace(/^\d+x/, ""));
|
|
828
928
|
var addressSize = (bits) => bits === 64 ? undefined : sizePrefix(bits);
|
|
829
929
|
function directAddress(region, base, offsetBits, bits) {
|
|
830
930
|
const size = addressSize(bits);
|
|
@@ -840,20 +940,23 @@ function directAddress(region, base, offsetBits, bits) {
|
|
|
840
940
|
}
|
|
841
941
|
return `%${region}${size}${byte / (bits / 8)}`;
|
|
842
942
|
}
|
|
843
|
-
|
|
943
|
+
function addressBits(address) {
|
|
944
|
+
const [, region, size, index, bit] = /^%([IQ])([A-Z])(\d+)(?:\.([0-7]))?$/.exec(address) ?? [];
|
|
945
|
+
const bits = size === undefined ? undefined : sizePrefixes.get(size)?.bits;
|
|
946
|
+
if (region !== "I" && region !== "Q" || bits === undefined || addressSize(bits) !== size || bits === 1 !== (bit !== undefined)) {
|
|
947
|
+
return;
|
|
948
|
+
}
|
|
949
|
+
const offsetBits = bits === 1 ? Number(index) * 8 + Number(bit) : Number(index) * bits;
|
|
950
|
+
return { region, offsetBits, bits };
|
|
951
|
+
}
|
|
952
|
+
var regionOf = (direction) => direction === "input" ? "I" : "Q";
|
|
844
953
|
function regionPlacer(regions, { generatedTree }) {
|
|
845
|
-
const taken = regions.flatMap(({ region, size,
|
|
846
|
-
{
|
|
847
|
-
region,
|
|
848
|
-
start: byteOffset(address),
|
|
849
|
-
end: byteOffset(address) + size
|
|
850
|
-
}
|
|
851
|
-
] : []);
|
|
954
|
+
const taken = regions.flatMap(({ region, size, offset }) => offset === undefined ? [] : [{ region, start: offset, end: offset + size }]);
|
|
852
955
|
const cursors = { I: 0, Q: 0 };
|
|
853
956
|
const aligned = (offset) => Math.ceil(offset / 4) * 4;
|
|
854
|
-
return ({ id, region, size,
|
|
855
|
-
if (
|
|
856
|
-
return
|
|
957
|
+
return ({ id, region, size, offset }) => {
|
|
958
|
+
if (offset !== undefined) {
|
|
959
|
+
return offset;
|
|
857
960
|
}
|
|
858
961
|
if (!generatedTree) {
|
|
859
962
|
throw new Error(`${id}: set the %${region}B address the template assigns to this assembly, or let codesys.deviceTree place it.`);
|
|
@@ -865,7 +968,7 @@ function regionPlacer(regions, { generatedTree }) {
|
|
|
865
968
|
const start = clear(aligned(cursors[region]));
|
|
866
969
|
taken.push({ region, start, end: start + size });
|
|
867
970
|
cursors[region] = start + size;
|
|
868
|
-
return
|
|
971
|
+
return start;
|
|
869
972
|
};
|
|
870
973
|
}
|
|
871
974
|
|
|
@@ -879,7 +982,7 @@ function assemblyChannels({
|
|
|
879
982
|
payloadSize
|
|
880
983
|
}) {
|
|
881
984
|
const prefix = `${direction}s`;
|
|
882
|
-
const region = direction
|
|
985
|
+
const region = regionOf(direction);
|
|
883
986
|
const payloadBits = payloadSize * 8;
|
|
884
987
|
const address = (offsetBits, bits) => directAddress(region, base, offsetBits, bits);
|
|
885
988
|
const channels = [];
|
|
@@ -957,7 +1060,11 @@ function assemblyChannels({
|
|
|
957
1060
|
const span = {
|
|
958
1061
|
...channel,
|
|
959
1062
|
bits: length * scalarBits,
|
|
960
|
-
type:
|
|
1063
|
+
type: arrayTypeText({
|
|
1064
|
+
lower: 0,
|
|
1065
|
+
upper: length - 1,
|
|
1066
|
+
element: member.type
|
|
1067
|
+
}),
|
|
961
1068
|
address: address(member.offsetBits, scalarBits)
|
|
962
1069
|
};
|
|
963
1070
|
channels.push(span);
|
|
@@ -996,6 +1103,23 @@ var cipTypes = {
|
|
|
996
1103
|
211: "DWORD",
|
|
997
1104
|
212: "LWORD"
|
|
998
1105
|
};
|
|
1106
|
+
var connectionFields = {
|
|
1107
|
+
transport: 0,
|
|
1108
|
+
outputSize: 3,
|
|
1109
|
+
outputFormat: 4,
|
|
1110
|
+
inputSize: 6,
|
|
1111
|
+
inputFormat: 7,
|
|
1112
|
+
name: 12,
|
|
1113
|
+
path: 14
|
|
1114
|
+
};
|
|
1115
|
+
var assemblyFields = {
|
|
1116
|
+
name: 0,
|
|
1117
|
+
path: 1,
|
|
1118
|
+
size: 2,
|
|
1119
|
+
descriptor: 3,
|
|
1120
|
+
firstMember: 6
|
|
1121
|
+
};
|
|
1122
|
+
var isConnection = (key) => /^Connection\d+$/.test(key);
|
|
999
1123
|
function stripComments(text) {
|
|
1000
1124
|
let clean = "";
|
|
1001
1125
|
const offsets = [];
|
|
@@ -1075,14 +1199,15 @@ function edsSections(text) {
|
|
|
1075
1199
|
if (!section) {
|
|
1076
1200
|
throw new Error("EDS record outside a section.");
|
|
1077
1201
|
}
|
|
1202
|
+
const start = offsets[match.index];
|
|
1203
|
+
const last = offsets[end - 1];
|
|
1204
|
+
if (key === undefined || body === undefined || start === undefined || last === undefined) {
|
|
1205
|
+
throw new Error("Malformed EDS record or section.");
|
|
1206
|
+
}
|
|
1078
1207
|
if (section.has(key)) {
|
|
1079
1208
|
throw new Error(`Duplicate EDS record ${key}.`);
|
|
1080
1209
|
}
|
|
1081
|
-
section.set(key, {
|
|
1082
|
-
fields: recordFields(body),
|
|
1083
|
-
start: offsets[match.index],
|
|
1084
|
-
end: offsets[end - 1] + 1
|
|
1085
|
-
});
|
|
1210
|
+
section.set(key, { fields: recordFields(body), start, end: last + 1 });
|
|
1086
1211
|
}
|
|
1087
1212
|
if (clean.slice(end).trim()) {
|
|
1088
1213
|
throw new Error("Unterminated EDS record.");
|
|
@@ -1128,21 +1253,29 @@ function logicalSegments(bytes) {
|
|
|
1128
1253
|
...logicalSegments(data.slice(length))
|
|
1129
1254
|
];
|
|
1130
1255
|
}
|
|
1131
|
-
function
|
|
1132
|
-
|
|
1133
|
-
if (
|
|
1256
|
+
function pathBytes(path, params) {
|
|
1257
|
+
return path.trim().split(/\s+/).filter(Boolean).flatMap((token) => {
|
|
1258
|
+
if (/^[0-9a-f]{2}$/i.test(token)) {
|
|
1259
|
+
return [parseInt(token, 16)];
|
|
1260
|
+
}
|
|
1261
|
+
const reference = /^\[(Param\d+)\]$/.exec(token)?.[1];
|
|
1262
|
+
const parameter = reference ? params.get(reference) : undefined;
|
|
1263
|
+
if (!parameter || parameter.default === undefined) {
|
|
1134
1264
|
throw new Error(`Unsupported EDS path token ${token}.`);
|
|
1135
1265
|
}
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1266
|
+
const value = parameter.default;
|
|
1267
|
+
return Array.from({ length: parameter.size }, (_, index) => Math.floor(value / 2 ** (index * 8)) % 256);
|
|
1268
|
+
});
|
|
1269
|
+
}
|
|
1270
|
+
function logicalPath(path, params) {
|
|
1271
|
+
const segments = logicalSegments(pathBytes(path, params));
|
|
1139
1272
|
return {
|
|
1140
1273
|
instance: segments.filter(({ type }) => type === 36).at(-1)?.value,
|
|
1141
1274
|
points: segments.filter(({ type }) => type === 44).map(({ value }) => value)
|
|
1142
1275
|
};
|
|
1143
1276
|
}
|
|
1144
1277
|
var optionalNumber = (value) => value?.trim() && Number.isFinite(Number(value)) ? Number(value) : undefined;
|
|
1145
|
-
function parseEds(text, file
|
|
1278
|
+
function parseEds(text, file) {
|
|
1146
1279
|
const records = readEdsRecords(text);
|
|
1147
1280
|
const device = records.Device;
|
|
1148
1281
|
if (!device?.ProdName?.[0]) {
|
|
@@ -1161,6 +1294,7 @@ function parseEds(text, file = "device.eds") {
|
|
|
1161
1294
|
}));
|
|
1162
1295
|
const params = new Map(parameters.map((parameter) => [parameter.id, parameter]));
|
|
1163
1296
|
const instances = new Map;
|
|
1297
|
+
const recordless = new Map;
|
|
1164
1298
|
const size = (value) => {
|
|
1165
1299
|
if (!value) {
|
|
1166
1300
|
return;
|
|
@@ -1179,18 +1313,24 @@ function parseEds(text, file = "device.eds") {
|
|
|
1179
1313
|
maximum: parameter.maximum
|
|
1180
1314
|
};
|
|
1181
1315
|
};
|
|
1182
|
-
const connections = Object.entries(records["Connection Manager"] ?? {}).filter(([id]) =>
|
|
1183
|
-
const path = fields[
|
|
1184
|
-
const points = logicalPath(path).points;
|
|
1185
|
-
const
|
|
1316
|
+
const connections = Object.entries(records["Connection Manager"] ?? {}).filter(([id]) => isConnection(id)).map(([id, fields]) => {
|
|
1317
|
+
const path = fields[connectionFields.path] ?? "";
|
|
1318
|
+
const points = logicalPath(path, params).points;
|
|
1319
|
+
const outputSize = size(fields[connectionFields.outputSize]);
|
|
1320
|
+
const inputSize = size(fields[connectionFields.inputSize]);
|
|
1321
|
+
const assembly = (reference, point, payload) => {
|
|
1186
1322
|
if (!reference) {
|
|
1187
|
-
|
|
1323
|
+
if (!payload || payload.value <= 0 || point === undefined) {
|
|
1324
|
+
return;
|
|
1325
|
+
}
|
|
1326
|
+
recordless.set(point, Math.max(recordless.get(point) ?? 0, payload.maximum ?? payload.value));
|
|
1327
|
+
return point;
|
|
1188
1328
|
}
|
|
1189
1329
|
const record = records.Assembly?.[reference];
|
|
1190
1330
|
if (!/^Assem\d+$/.test(reference) || !record) {
|
|
1191
1331
|
throw new Error(`${file}: unknown connection assembly ${reference}.`);
|
|
1192
1332
|
}
|
|
1193
|
-
const instance = point ?? logicalPath(record[
|
|
1333
|
+
const instance = point ?? logicalPath(record[assemblyFields.path] ?? "", params).instance;
|
|
1194
1334
|
if (instance === undefined) {
|
|
1195
1335
|
throw new Error(`${file}: no runtime instance for ${reference}.`);
|
|
1196
1336
|
}
|
|
@@ -1203,19 +1343,19 @@ function parseEds(text, file = "device.eds") {
|
|
|
1203
1343
|
};
|
|
1204
1344
|
return {
|
|
1205
1345
|
id,
|
|
1206
|
-
name: fields[
|
|
1207
|
-
owner: /^0x[\da-f]{8}$/i.test(fields[
|
|
1346
|
+
name: fields[connectionFields.name] || id,
|
|
1347
|
+
owner: /^0x[\da-f]{8}$/i.test(fields[connectionFields.transport] ?? "") && (Number(fields[connectionFields.transport]) >>> 24 & 15) === 4,
|
|
1208
1348
|
path,
|
|
1209
|
-
outputAssembly: assembly(fields[
|
|
1210
|
-
inputAssembly: assembly(fields[
|
|
1211
|
-
outputSize
|
|
1212
|
-
inputSize
|
|
1349
|
+
outputAssembly: assembly(fields[connectionFields.outputFormat], points.at(-2), outputSize),
|
|
1350
|
+
inputAssembly: assembly(fields[connectionFields.inputFormat], points.at(-1), inputSize),
|
|
1351
|
+
outputSize,
|
|
1352
|
+
inputSize
|
|
1213
1353
|
};
|
|
1214
1354
|
});
|
|
1215
1355
|
const assemblies = Object.entries(records.Assembly ?? {}).filter(([id]) => /^Assem\d+$/.test(id)).map(([id, fields]) => {
|
|
1216
1356
|
const members = [];
|
|
1217
1357
|
let offsetBits = 0;
|
|
1218
|
-
for (let index =
|
|
1358
|
+
for (let index = assemblyFields.firstMember;index < fields.length; index += 2) {
|
|
1219
1359
|
if (!fields[index] && !fields[index + 1]) {
|
|
1220
1360
|
continue;
|
|
1221
1361
|
}
|
|
@@ -1238,13 +1378,31 @@ function parseEds(text, file = "device.eds") {
|
|
|
1238
1378
|
});
|
|
1239
1379
|
offsetBits += bits;
|
|
1240
1380
|
}
|
|
1241
|
-
const
|
|
1381
|
+
const declared = fields[assemblyFields.size];
|
|
1382
|
+
const size = declared ? integer(declared, `${id} size`, { minimum: 0 }) : Math.ceil(offsetBits / 8);
|
|
1242
1383
|
if (offsetBits > size * 8) {
|
|
1243
1384
|
throw new Error(`${file}: ${id} members exceed its ${size} byte payload.`);
|
|
1244
1385
|
}
|
|
1245
|
-
const instance = logicalPath(fields[
|
|
1246
|
-
return {
|
|
1386
|
+
const instance = logicalPath(fields[assemblyFields.path] ?? "", params).instance ?? instances.get(id);
|
|
1387
|
+
return {
|
|
1388
|
+
id,
|
|
1389
|
+
instance,
|
|
1390
|
+
name: fields[assemblyFields.name] || id,
|
|
1391
|
+
size,
|
|
1392
|
+
members
|
|
1393
|
+
};
|
|
1247
1394
|
});
|
|
1395
|
+
for (const [instance, payloadSize] of recordless) {
|
|
1396
|
+
if (!assemblies.some((assembly) => assembly.instance === instance)) {
|
|
1397
|
+
assemblies.push({
|
|
1398
|
+
id: `Instance${instance}`,
|
|
1399
|
+
instance,
|
|
1400
|
+
name: `Assembly ${instance}`,
|
|
1401
|
+
size: payloadSize,
|
|
1402
|
+
members: []
|
|
1403
|
+
});
|
|
1404
|
+
}
|
|
1405
|
+
}
|
|
1248
1406
|
return {
|
|
1249
1407
|
file,
|
|
1250
1408
|
name: device.ProdName[0],
|
|
@@ -1263,21 +1421,35 @@ function placeModbusRegisters(device, registers, place) {
|
|
|
1263
1421
|
if (!entries.length) {
|
|
1264
1422
|
return [];
|
|
1265
1423
|
}
|
|
1266
|
-
const outputBase =
|
|
1267
|
-
|
|
1424
|
+
const outputBase = place({
|
|
1425
|
+
id: device,
|
|
1426
|
+
region: "Q",
|
|
1427
|
+
size: entries.length * registerBytes.Q
|
|
1428
|
+
});
|
|
1429
|
+
const inputBase = place({
|
|
1430
|
+
id: device,
|
|
1431
|
+
region: "I",
|
|
1432
|
+
size: entries.length * registerBytes.I
|
|
1433
|
+
});
|
|
1268
1434
|
return entries.map(([name, offset], index) => {
|
|
1269
|
-
const channel = (field, direction, offsetBits, bits, type, description) =>
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1435
|
+
const channel = (field, direction, offsetBits, bits, type, description) => {
|
|
1436
|
+
const address = directAddress(regionOf(direction), direction === "input" ? inputBase + index * registerBytes.I : outputBase + index * registerBytes.Q, offsetBits, bits);
|
|
1437
|
+
if (!address) {
|
|
1438
|
+
throw new Error(`${device}: Modbus register ${name} ${field} has no direct address.`);
|
|
1439
|
+
}
|
|
1440
|
+
return {
|
|
1441
|
+
device,
|
|
1442
|
+
id: `modbus.${name}.${field}`,
|
|
1443
|
+
name: `${name} ${field}`,
|
|
1444
|
+
direction,
|
|
1445
|
+
offsetBits,
|
|
1446
|
+
bits,
|
|
1447
|
+
type,
|
|
1448
|
+
address,
|
|
1449
|
+
unit: "",
|
|
1450
|
+
description
|
|
1451
|
+
};
|
|
1452
|
+
};
|
|
1281
1453
|
const value = channel("value", "output", 0, 16, "WORD", "Value to write");
|
|
1282
1454
|
const write = channel("write", "output", 16, 1, "BOOL", "Writes the value when it rises");
|
|
1283
1455
|
const status = channel("status", "input", 0, 8, "BYTE", "The last answer: 0 accepted, otherwise the exception code");
|
|
@@ -1316,6 +1488,14 @@ function selectConnection(id, settings, descriptor) {
|
|
|
1316
1488
|
const choices = compatible.map((item) => `${item.id} "${item.name}" (in ${item.inputAssembly ?? "-"}, out ${item.outputAssembly ?? "-"})`).join(", ");
|
|
1317
1489
|
throw new Error(`${id}: select connection; ${settings.file} offers ${choices}.`);
|
|
1318
1490
|
}
|
|
1491
|
+
function configuredByte(id, direction, address) {
|
|
1492
|
+
const region = regionOf(direction);
|
|
1493
|
+
const location = addressBits(address);
|
|
1494
|
+
if (location?.region !== region || location.bits !== 8) {
|
|
1495
|
+
throw new Error(`${id}: ${direction} assembly needs a %${region}B address.`);
|
|
1496
|
+
}
|
|
1497
|
+
return location.offsetBits / 8;
|
|
1498
|
+
}
|
|
1319
1499
|
function selectAssemblies(id, settings, descriptor, connection) {
|
|
1320
1500
|
return ["input", "output"].flatMap((direction) => {
|
|
1321
1501
|
const selection = direction === "input" ? settings.inputs : settings.outputs;
|
|
@@ -1330,10 +1510,8 @@ function selectAssemblies(id, settings, descriptor, connection) {
|
|
|
1330
1510
|
if (!assembly) {
|
|
1331
1511
|
throw new Error(`${id}: assembly ${instance} is not present in ${settings.file}.`);
|
|
1332
1512
|
}
|
|
1333
|
-
const region = direction
|
|
1334
|
-
|
|
1335
|
-
throw new Error(`${id}: ${direction} assembly needs a %${region}B address.`);
|
|
1336
|
-
}
|
|
1513
|
+
const region = regionOf(direction);
|
|
1514
|
+
const offset = selection?.address === undefined ? undefined : configuredByte(id, direction, selection.address);
|
|
1337
1515
|
const declaredSize = direction === "input" ? connection?.inputSize : connection?.outputSize;
|
|
1338
1516
|
const payloadSize = selection?.size ?? declaredSize?.value ?? assembly.size;
|
|
1339
1517
|
if (!Number.isSafeInteger(payloadSize) || payloadSize <= 0 || payloadSize > assembly.size || declaredSize?.minimum !== undefined && payloadSize < declaredSize.minimum || declaredSize?.maximum !== undefined && payloadSize > declaredSize.maximum || selection?.size !== undefined && declaredSize && !declaredSize.parameter && payloadSize !== declaredSize.value) {
|
|
@@ -1347,29 +1525,51 @@ function selectAssemblies(id, settings, descriptor, connection) {
|
|
|
1347
1525
|
instance,
|
|
1348
1526
|
assembly,
|
|
1349
1527
|
size: payloadSize,
|
|
1350
|
-
|
|
1528
|
+
offset
|
|
1351
1529
|
}
|
|
1352
1530
|
];
|
|
1353
1531
|
});
|
|
1354
1532
|
}
|
|
1355
1533
|
|
|
1356
1534
|
// packages/typegen/src/hardware.ts
|
|
1357
|
-
import { ioScalarBits as
|
|
1535
|
+
import { ioScalarBits as ioScalarBits2 } from "@tsplc/iec";
|
|
1358
1536
|
|
|
1537
|
+
// packages/typegen/src/device-tree.ts
|
|
1538
|
+
import { iecName } from "@tsplc/config/build";
|
|
1359
1539
|
// packages/typegen/src/hardware/mapping-types.ts
|
|
1360
|
-
import {
|
|
1540
|
+
import { relative, sep } from "node:path";
|
|
1541
|
+
import { sizePrefixes as sizePrefixes2 } from "@tsplc/iec";
|
|
1542
|
+
var region = '${"I" | "Q"}';
|
|
1543
|
+
var bitAddress = `\`%${region}X\${number}.\${0 | 1 | 2 | 3 | 4 | 5 | 6 | 7}\``;
|
|
1544
|
+
var byteSizes = [...sizePrefixes2].filter(([prefix, type]) => type.bits > 1 && addressSize(type.bits) === prefix).map(([prefix]) => JSON.stringify(prefix)).join(" | ");
|
|
1545
|
+
var addressBinding = (address) => `{ address: ${address}; type?: string }`;
|
|
1361
1546
|
var directBinding = (layout) => {
|
|
1362
|
-
const
|
|
1363
|
-
const integer = /^INT(\d+)$/.exec(scalar);
|
|
1364
|
-
const bits = integer ? Number(integer[1]) : ioScalarBits2(scalar);
|
|
1547
|
+
const bits = layoutBits(layout);
|
|
1365
1548
|
const size = bits === undefined ? undefined : addressSize(bits);
|
|
1366
1549
|
if (!size) {
|
|
1367
1550
|
return;
|
|
1368
1551
|
}
|
|
1369
|
-
return size === "X" ?
|
|
1552
|
+
return addressBinding(size === "X" ? bitAddress : `\`%${region}${size}\${number}\``);
|
|
1553
|
+
};
|
|
1554
|
+
var portableCatalog = (catalog, root) => {
|
|
1555
|
+
const portable = (file) => relative(root, file).split(sep).join("/");
|
|
1556
|
+
return {
|
|
1557
|
+
descriptors: catalog.descriptors.map((descriptor) => ({
|
|
1558
|
+
...descriptor,
|
|
1559
|
+
file: portable(descriptor.file)
|
|
1560
|
+
})),
|
|
1561
|
+
devices: catalog.devices.map((device) => ({
|
|
1562
|
+
...device,
|
|
1563
|
+
descriptor: portable(device.descriptor)
|
|
1564
|
+
}))
|
|
1565
|
+
};
|
|
1370
1566
|
};
|
|
1371
|
-
function generateHardwareTypes(catalog,
|
|
1372
|
-
|
|
1567
|
+
function generateHardwareTypes(catalog, {
|
|
1568
|
+
root,
|
|
1569
|
+
targets,
|
|
1570
|
+
ioTypes
|
|
1571
|
+
}) {
|
|
1572
|
+
const selectors = targets?.publication.map((selector) => JSON.stringify(selector)).join(" | ") ?? "string";
|
|
1373
1573
|
const publicationTypes = `// Generated by tsPLC. Run tsplc typegen after changing EDS files, device selections or PLC storage.
|
|
1374
1574
|
export type PublicationSelector = ${selectors || "never"};
|
|
1375
1575
|
export type PlcPublication = { readonly production: readonly PublicationSelector[]; readonly development: readonly PublicationSelector[] };
|
|
@@ -1382,11 +1582,11 @@ export type PlcPublication = { readonly production: readonly PublicationSelector
|
|
|
1382
1582
|
binding: channel(device.id, item.id, item.direction === "input" && item.type === "BOOL" ? "; inverted?: boolean; shared?: boolean" : ""),
|
|
1383
1583
|
layout: ioLayout(item.type)
|
|
1384
1584
|
})));
|
|
1385
|
-
const direct =
|
|
1585
|
+
const direct = addressBinding(`\`%${region}\${${byteSizes}}\${number}\` | ${bitAddress}`);
|
|
1386
1586
|
const anyBinding = [...channels.map((item) => item.binding), direct].join(`
|
|
1387
1587
|
| `);
|
|
1388
|
-
const mapping = targets ? [...new Set(targets.map((target) => target.layout))].sort().map((layout) => {
|
|
1389
|
-
const keys = targets.filter((target) => target.layout === layout).map((target) => `\`${target.key}\``);
|
|
1588
|
+
const mapping = targets ? [...new Set(targets.io.map((target) => target.layout))].sort().map((layout) => {
|
|
1589
|
+
const keys = targets.io.filter((target) => target.layout === layout).map((target) => `\`${target.key}\``);
|
|
1390
1590
|
const bindings = [
|
|
1391
1591
|
...channels.filter((item) => item.layout === layout).map((item) => item.binding),
|
|
1392
1592
|
directBinding(layout)
|
|
@@ -1397,45 +1597,37 @@ export type PlcPublication = { readonly production: readonly PublicationSelector
|
|
|
1397
1597
|
}).join(" & ") || "Readonly<Record<string, never>>" : "Readonly<Record<string, HardwareIoBinding>>";
|
|
1398
1598
|
return `${publicationTypes}export type HardwareIoBinding = ${anyBinding};
|
|
1399
1599
|
export type HardwareIoMapping = ${mapping};
|
|
1400
|
-
export const hardware = ${JSON.stringify(catalog, null, 2)} as const;
|
|
1600
|
+
export const hardware = ${JSON.stringify(portableCatalog(catalog, root), null, 2)} as const;
|
|
1401
1601
|
`;
|
|
1402
1602
|
}
|
|
1403
1603
|
|
|
1404
1604
|
// packages/typegen/src/hardware.ts
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
}
|
|
1410
|
-
throw cause;
|
|
1411
|
-
});
|
|
1412
|
-
const files = [];
|
|
1413
|
-
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
1414
|
-
const path = resolve(directory, entry.name);
|
|
1415
|
-
if (entry.isDirectory()) {
|
|
1416
|
-
files.push(...await edsFiles(path));
|
|
1417
|
-
} else if (entry.isFile() && /\.eds$/i.test(entry.name)) {
|
|
1418
|
-
files.push(path);
|
|
1419
|
-
}
|
|
1605
|
+
var defaultEds = tsplcConfigSchema.shape.eds.parse(undefined);
|
|
1606
|
+
var edsFiles = (config, directory) => filesUnder(directory, "eds", (a, b) => a.localeCompare(b)).catch((error) => {
|
|
1607
|
+
if (config.eds === defaultEds && isMissingFile(error)) {
|
|
1608
|
+
return [];
|
|
1420
1609
|
}
|
|
1421
|
-
|
|
1422
|
-
}
|
|
1610
|
+
throw error;
|
|
1611
|
+
});
|
|
1423
1612
|
async function readDescriptors(config, root) {
|
|
1424
1613
|
const files = new Set;
|
|
1425
1614
|
for (const directory of [config.eds].flat()) {
|
|
1426
|
-
for (const file of await edsFiles(resolve(root, directory))) {
|
|
1615
|
+
for (const file of await edsFiles(config, resolve(root, directory))) {
|
|
1427
1616
|
files.add(file);
|
|
1428
1617
|
}
|
|
1429
1618
|
}
|
|
1430
1619
|
for (const device of Object.values(config.devices)) {
|
|
1431
1620
|
files.add(resolve(root, device.file));
|
|
1432
1621
|
}
|
|
1433
|
-
return Promise.all([...files].map(async (file) => parseEds(await
|
|
1622
|
+
return new Map(await Promise.all([...files].map(async (file) => [file, parseEds(await readFile4(file, "utf8"), file)])));
|
|
1434
1623
|
}
|
|
1435
1624
|
async function loadHardware(config, root) {
|
|
1436
1625
|
const descriptors = await readDescriptors(config, root);
|
|
1437
1626
|
const selected = Object.entries(config.devices).map(([id, settings]) => {
|
|
1438
|
-
const descriptor = descriptors.
|
|
1627
|
+
const descriptor = descriptors.get(resolve(root, settings.file));
|
|
1628
|
+
if (!descriptor) {
|
|
1629
|
+
throw new Error(`${id}: ${settings.file} was not read.`);
|
|
1630
|
+
}
|
|
1439
1631
|
const connection = selectConnection(id, settings, descriptor);
|
|
1440
1632
|
const selections = selectAssemblies(id, settings, descriptor, connection);
|
|
1441
1633
|
return { id, settings, descriptor, connection, selections };
|
|
@@ -1443,10 +1635,14 @@ async function loadHardware(config, root) {
|
|
|
1443
1635
|
const place = regionPlacer(selected.flatMap((device) => device.selections), { generatedTree: config.codesys?.deviceTree !== undefined });
|
|
1444
1636
|
const placed = selected.map((device) => ({
|
|
1445
1637
|
...device,
|
|
1446
|
-
assemblies: device.selections.map((selection) =>
|
|
1447
|
-
|
|
1448
|
-
address
|
|
1449
|
-
|
|
1638
|
+
assemblies: device.selections.map((selection) => {
|
|
1639
|
+
const offset = place(selection);
|
|
1640
|
+
const address = directAddress(selection.region, offset, 0, 8);
|
|
1641
|
+
if (!address) {
|
|
1642
|
+
throw new Error(`${device.id}: byte ${offset} has no direct address.`);
|
|
1643
|
+
}
|
|
1644
|
+
return { ...selection, offset, address };
|
|
1645
|
+
})
|
|
1450
1646
|
}));
|
|
1451
1647
|
const devices = placed.map(({ id, settings, descriptor, connection, assemblies }) => {
|
|
1452
1648
|
const registers = placeModbusRegisters(id, settings.modbus?.registers ?? {}, place);
|
|
@@ -1468,12 +1664,12 @@ async function loadHardware(config, root) {
|
|
|
1468
1664
|
})),
|
|
1469
1665
|
channels: [
|
|
1470
1666
|
...registers.flatMap((register) => register.channels),
|
|
1471
|
-
...assemblies.flatMap(({ direction, instance, assembly, size,
|
|
1667
|
+
...assemblies.flatMap(({ direction, instance, assembly, size, offset }) => assemblyChannels({
|
|
1472
1668
|
device: id,
|
|
1473
1669
|
direction,
|
|
1474
1670
|
instance,
|
|
1475
1671
|
members: assembly.members,
|
|
1476
|
-
base:
|
|
1672
|
+
base: offset,
|
|
1477
1673
|
payloadSize: size
|
|
1478
1674
|
}))
|
|
1479
1675
|
],
|
|
@@ -1486,18 +1682,14 @@ async function loadHardware(config, root) {
|
|
|
1486
1682
|
}
|
|
1487
1683
|
};
|
|
1488
1684
|
});
|
|
1489
|
-
return { descriptors, devices };
|
|
1685
|
+
return { descriptors: [...descriptors.values()], devices };
|
|
1490
1686
|
}
|
|
1491
1687
|
function resolveIo(config, catalog) {
|
|
1492
1688
|
return Object.fromEntries(Object.entries(config.io).map(([symbol, binding]) => {
|
|
1493
1689
|
if ("address" in binding) {
|
|
1494
1690
|
return [symbol, binding];
|
|
1495
1691
|
}
|
|
1496
|
-
const
|
|
1497
|
-
const channel = device?.channels.find((c) => c.id === binding.channel);
|
|
1498
|
-
if (!channel?.address) {
|
|
1499
|
-
throw new Error(`${symbol}: unknown or unaddressable channel ${binding.device}.${binding.channel}.`);
|
|
1500
|
-
}
|
|
1692
|
+
const channel = boundChannel(catalog, symbol, binding);
|
|
1501
1693
|
return [
|
|
1502
1694
|
symbol,
|
|
1503
1695
|
{
|
|
@@ -1511,22 +1703,24 @@ function resolveIo(config, catalog) {
|
|
|
1511
1703
|
}
|
|
1512
1704
|
|
|
1513
1705
|
// packages/typegen/src/project.ts
|
|
1514
|
-
var
|
|
1515
|
-
var
|
|
1706
|
+
var emittedPath = (root, file) => resolve2(root, emittedStDirectory, file);
|
|
1707
|
+
var missingEmission = (root) => new Error(`No emitted Structured Text in ${resolve2(root, emittedStDirectory)}: emit the program with tsplc build --emit-only, or check with tsplc typegen --check, which emits it first.`);
|
|
1708
|
+
var readPublication = async (root) => {
|
|
1709
|
+
const text = await readIfPresent(emittedPath(root, emittedFiles.publication));
|
|
1710
|
+
if (text === null) {
|
|
1711
|
+
throw missingEmission(root);
|
|
1712
|
+
}
|
|
1713
|
+
return publicationSchema.parse(JSON.parse(text));
|
|
1714
|
+
};
|
|
1516
1715
|
var generatedFiles = {
|
|
1517
1716
|
hardware: "hardware.ts",
|
|
1518
1717
|
contract: "plc.ts",
|
|
1519
1718
|
machines: "machines.ts"
|
|
1520
1719
|
};
|
|
1521
1720
|
async function readIoSymbols(root) {
|
|
1522
|
-
const file =
|
|
1523
|
-
const text = await
|
|
1524
|
-
|
|
1525
|
-
return "{}";
|
|
1526
|
-
}
|
|
1527
|
-
throw error;
|
|
1528
|
-
});
|
|
1529
|
-
const symbols = ioSymbolsSchema.safeParse(JSON.parse(text));
|
|
1721
|
+
const file = emittedPath(root, emittedFiles.ioSymbols);
|
|
1722
|
+
const text = await readIfPresent(file);
|
|
1723
|
+
const symbols = ioSymbolsSchema.safeParse(JSON.parse(text ?? "{}"));
|
|
1530
1724
|
if (!symbols.success) {
|
|
1531
1725
|
throw new Error(`Invalid IO symbols in ${file}`, { cause: symbols.error });
|
|
1532
1726
|
}
|
|
@@ -1537,6 +1731,7 @@ async function contractSources(config, root, settings) {
|
|
|
1537
1731
|
const types = directories(settings.types);
|
|
1538
1732
|
const globals = directories(settings.globals);
|
|
1539
1733
|
if (types.length || globals.length) {
|
|
1734
|
+
const filesIn = async (directories) => (await Promise.all(directories.map(stFiles))).flat();
|
|
1540
1735
|
const sources = {
|
|
1541
1736
|
types: await filesIn(types),
|
|
1542
1737
|
globals: await filesIn(globals),
|
|
@@ -1547,56 +1742,32 @@ async function contractSources(config, root, settings) {
|
|
|
1547
1742
|
}
|
|
1548
1743
|
return sources;
|
|
1549
1744
|
}
|
|
1550
|
-
const source = config
|
|
1745
|
+
const source = stRoot(config);
|
|
1551
1746
|
if (!source) {
|
|
1552
|
-
|
|
1553
|
-
throw new Error("Configure build.sourceDir or typegen.types/globals to generate PLC types.");
|
|
1554
|
-
}
|
|
1555
|
-
return;
|
|
1747
|
+
throw new Error("Configure build.sourceDir or typegen.types/globals to generate PLC types.");
|
|
1556
1748
|
}
|
|
1557
1749
|
const sourceRoot = resolve2(root, source);
|
|
1558
|
-
const files = await stFiles(sourceRoot)
|
|
1750
|
+
const files = await stFiles(sourceRoot).catch((cause) => {
|
|
1751
|
+
if (!isMissingFile(cause)) {
|
|
1752
|
+
throw cause;
|
|
1753
|
+
}
|
|
1754
|
+
throw config.compiler ? missingEmission(root) : new Error(`build.sourceDir ${sourceRoot} doesn't exist.`);
|
|
1755
|
+
});
|
|
1559
1756
|
if (!files.length) {
|
|
1560
1757
|
throw new Error(`no .st declarations found in ${sourceRoot}`);
|
|
1561
1758
|
}
|
|
1562
1759
|
return { ...await declarationFiles(files), explicit: false };
|
|
1563
1760
|
}
|
|
1564
|
-
async function filesIn(directories) {
|
|
1565
|
-
const files = [];
|
|
1566
|
-
for (const directory of directories) {
|
|
1567
|
-
files.push(...await stFiles(directory));
|
|
1568
|
-
}
|
|
1569
|
-
return files;
|
|
1570
|
-
}
|
|
1571
1761
|
function checkHmiTargets(controls, published) {
|
|
1572
1762
|
for (const { target } of controls) {
|
|
1573
|
-
if (!published.some((symbol) =>
|
|
1763
|
+
if (!published.some((symbol) => isWithin(symbol, target))) {
|
|
1574
1764
|
throw new Error(`HMI control ${target} is not in the production publication.`);
|
|
1575
1765
|
}
|
|
1576
1766
|
}
|
|
1577
1767
|
}
|
|
1578
|
-
async function
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
const temp = `${output.path}.${process.pid}.tmp`;
|
|
1582
|
-
await writeFile(temp, output.content);
|
|
1583
|
-
await rename(temp, output.path);
|
|
1584
|
-
}
|
|
1585
|
-
}
|
|
1586
|
-
async function checkOutputs(outputs) {
|
|
1587
|
-
for (const output of outputs) {
|
|
1588
|
-
const actual = await readFile4(output.path, "utf8").catch(() => {
|
|
1589
|
-
return;
|
|
1590
|
-
});
|
|
1591
|
-
const normalized = actual !== undefined && /\.ts$/i.test(output.path) ? await formatTypeScript(actual) : actual;
|
|
1592
|
-
if (normalized !== output.content) {
|
|
1593
|
-
throw new Error(`Generated file is missing or stale: ${output.path}`);
|
|
1594
|
-
}
|
|
1595
|
-
}
|
|
1596
|
-
}
|
|
1597
|
-
async function generateProject(file = "tsplc.config.ts", options = {}) {
|
|
1598
|
-
const { config, root, configFile } = options.loaded ?? await loadTsplcConfig(file);
|
|
1599
|
-
const settings = typegenSchema.parse(config.typegen ?? {});
|
|
1768
|
+
async function generateProject({ config, root, configFile }, options = {}) {
|
|
1769
|
+
const hardwareOnly = options.hardwareOnly || !config.compiler && !config.typegen;
|
|
1770
|
+
const settings = typegenSettings(config);
|
|
1600
1771
|
const catalog = await loadHardware(config, root);
|
|
1601
1772
|
const io = resolveIo(config, catalog);
|
|
1602
1773
|
const project = {
|
|
@@ -1608,44 +1779,53 @@ async function generateProject(file = "tsplc.config.ts", options = {}) {
|
|
|
1608
1779
|
const outputs = [
|
|
1609
1780
|
{
|
|
1610
1781
|
path: resolve2(root, settings.dir, generatedFiles.hardware),
|
|
1611
|
-
content: await formatTypeScript(generateHardwareTypes(catalog,
|
|
1782
|
+
content: await formatTypeScript(generateHardwareTypes(catalog, {
|
|
1783
|
+
root,
|
|
1784
|
+
targets: options.targets ?? null,
|
|
1785
|
+
ioTypes: settings.ioTypes
|
|
1786
|
+
}))
|
|
1612
1787
|
},
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1788
|
+
...options.check ? [] : [
|
|
1789
|
+
{
|
|
1790
|
+
path: resolve2(root, projectSnapshotFile),
|
|
1791
|
+
content: `${JSON.stringify(project, null, 2)}
|
|
1616
1792
|
`
|
|
1617
|
-
|
|
1793
|
+
}
|
|
1794
|
+
]
|
|
1618
1795
|
];
|
|
1619
|
-
const sources =
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1796
|
+
const sources = hardwareOnly ? null : await contractSources(config, root, settings);
|
|
1797
|
+
const inferred = sources !== null && !!config.compiler && !sources.explicit;
|
|
1798
|
+
const hmi = config.compiler && config.publish && !hardwareOnly ? config.hmi : undefined;
|
|
1799
|
+
const publication = inferred || hmi ? await readPublication(root) : null;
|
|
1800
|
+
const contract = sources && {
|
|
1801
|
+
path: resolve2(root, settings.dir, generatedFiles.contract),
|
|
1802
|
+
content: await formatTypeScript(await generateTypes({
|
|
1803
|
+
types: sources.types,
|
|
1804
|
+
globals: sources.globals,
|
|
1805
|
+
publication: inferred ? publication : null,
|
|
1806
|
+
declarations: settings.declarations
|
|
1807
|
+
}))
|
|
1808
|
+
};
|
|
1809
|
+
if (contract) {
|
|
1810
|
+
outputs.push(contract);
|
|
1632
1811
|
}
|
|
1633
|
-
if (
|
|
1634
|
-
checkHmiTargets(
|
|
1812
|
+
if (hmi && publication) {
|
|
1813
|
+
checkHmiTargets(hmi.controls, publication.production);
|
|
1635
1814
|
}
|
|
1636
|
-
if (config.compiler && !
|
|
1637
|
-
const
|
|
1638
|
-
|
|
1815
|
+
if (config.compiler && !hardwareOnly) {
|
|
1816
|
+
const machines = await readIfPresent(emittedPath(root, emittedFiles.machines));
|
|
1817
|
+
outputs.push({
|
|
1818
|
+
path: resolve2(root, settings.dir, generatedFiles.machines),
|
|
1819
|
+
content: machines === null ? null : await formatTypeScript(machines)
|
|
1639
1820
|
});
|
|
1640
|
-
if (machine) {
|
|
1641
|
-
outputs.push({
|
|
1642
|
-
path: resolve2(root, settings.dir, generatedFiles.machines),
|
|
1643
|
-
content: await formatTypeScript(machine)
|
|
1644
|
-
});
|
|
1645
|
-
}
|
|
1646
1821
|
}
|
|
1647
1822
|
await (options.check ? checkOutputs(outputs) : writeOutputs(outputs));
|
|
1648
|
-
return {
|
|
1823
|
+
return {
|
|
1824
|
+
catalog,
|
|
1825
|
+
io,
|
|
1826
|
+
files: outputs.flatMap((output) => output.content === null ? [] : [output.path]),
|
|
1827
|
+
contract: contract?.path ?? null
|
|
1828
|
+
};
|
|
1649
1829
|
}
|
|
1650
1830
|
|
|
1651
1831
|
// packages/typegen/src/cli.ts
|
|
@@ -1661,17 +1841,23 @@ async function main() {
|
|
|
1661
1841
|
}
|
|
1662
1842
|
});
|
|
1663
1843
|
if (values.help) {
|
|
1664
|
-
console.log(`Usage: tsplc-typegen
|
|
1844
|
+
console.log(`Usage: tsplc-typegen [--config ${configFileName}] [--check]
|
|
1845
|
+
tsplc-typegen --types src/types [--globals src/globals] --out generated.ts [--check]
|
|
1665
1846
|
|
|
1666
1847
|
Generate TypeScript types and runtime field metadata from CODESYS ST declarations.
|
|
1848
|
+
Without --types and --out, generates the files the project's config names.
|
|
1667
1849
|
--check exits unsuccessfully if the output is missing or stale, without writing files.`);
|
|
1668
1850
|
return;
|
|
1669
1851
|
}
|
|
1670
1852
|
if (!values.types && !values.out) {
|
|
1671
|
-
const
|
|
1672
|
-
|
|
1853
|
+
const loaded = await loadTsplcConfig(values.config ?? configFileName, {
|
|
1854
|
+
env: process.env,
|
|
1855
|
+
target: undefined,
|
|
1856
|
+
forAgent: false
|
|
1673
1857
|
});
|
|
1674
|
-
|
|
1858
|
+
const result = await generateProject(loaded, { check: values.check });
|
|
1859
|
+
const files = result.files.join(", ");
|
|
1860
|
+
console.log(values.check ? `Up to date: ${files}` : `Generated ${files}`);
|
|
1675
1861
|
return;
|
|
1676
1862
|
}
|
|
1677
1863
|
if (!values.types || !values.out) {
|
|
@@ -1681,31 +1867,21 @@ Generate TypeScript types and runtime field metadata from CODESYS ST declaration
|
|
|
1681
1867
|
if (!/\.ts$/i.test(out) || /\.d\.ts$/i.test(out)) {
|
|
1682
1868
|
throw new Error("--out must be a .ts file (the generated file contains runtime metadata)");
|
|
1683
1869
|
}
|
|
1684
|
-
const
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1870
|
+
const contract = {
|
|
1871
|
+
path: out,
|
|
1872
|
+
content: await formatTypeScript(await generateTypes({
|
|
1873
|
+
types: resolve3(values.types),
|
|
1874
|
+
globals: values.globals ? resolve3(values.globals) : [],
|
|
1875
|
+
publication: null,
|
|
1876
|
+
declarations: true
|
|
1877
|
+
}))
|
|
1878
|
+
};
|
|
1688
1879
|
if (values.check) {
|
|
1689
|
-
|
|
1690
|
-
if (error instanceof Error && "code" in error && error.code === "ENOENT") {
|
|
1691
|
-
return;
|
|
1692
|
-
}
|
|
1693
|
-
throw error;
|
|
1694
|
-
});
|
|
1695
|
-
if (existing !== result) {
|
|
1696
|
-
throw new Error(`${out} is missing or stale; rerun tsplc-typegen without --check`);
|
|
1697
|
-
}
|
|
1880
|
+
await checkOutputs([contract]);
|
|
1698
1881
|
console.log(`Up to date: ${out}`);
|
|
1699
1882
|
return;
|
|
1700
1883
|
}
|
|
1701
|
-
await
|
|
1702
|
-
const temporary = `${out}.${process.pid}.tmp`;
|
|
1703
|
-
try {
|
|
1704
|
-
await writeFile2(temporary, result, { flag: "wx" });
|
|
1705
|
-
await rename2(temporary, out);
|
|
1706
|
-
} finally {
|
|
1707
|
-
await rm(temporary, { force: true });
|
|
1708
|
-
}
|
|
1884
|
+
await writeOutputs([contract]);
|
|
1709
1885
|
console.log(`Generated ${out}`);
|
|
1710
1886
|
}
|
|
1711
1887
|
main().catch((error) => {
|
|
@@ -1713,5 +1889,5 @@ main().catch((error) => {
|
|
|
1713
1889
|
process.exitCode = 1;
|
|
1714
1890
|
});
|
|
1715
1891
|
|
|
1716
|
-
//# debugId=
|
|
1892
|
+
//# debugId=D17F9A6BF987DBC364756E2164756E21
|
|
1717
1893
|
//# sourceMappingURL=cli.js.map
|