@tsplc/typegen 0.2.17 → 0.2.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/cli.js +798 -544
- package/dist/cli.js.map +15 -9
- package/dist/codegen.js +252 -177
- package/dist/codegen.js.map +5 -5
- package/dist/hardware.js +447 -338
- package/dist/hardware.js.map +10 -5
- package/dist/index.js +848 -602
- package/dist/index.js.map +16 -9
- package/package.json +55 -62
- package/src/cli.ts +68 -51
- package/src/codegen/constants.ts +177 -86
- package/src/codegen/generate.ts +436 -388
- package/src/codegen/parser.ts +358 -287
- package/src/device-tree.ts +152 -140
- package/src/hardware/channels.ts +157 -0
- package/src/hardware/eds.ts +408 -0
- package/src/hardware/mapping-types.ts +88 -0
- package/src/hardware/modbus.ts +105 -0
- package/src/hardware/process-image.ts +102 -0
- package/src/hardware/selection.ts +136 -0
- package/src/hardware.ts +195 -844
- package/src/index.ts +25 -1
- package/src/project.ts +246 -151
package/dist/index.js
CHANGED
|
@@ -3,62 +3,65 @@ import { readdir, readFile } from "node:fs/promises";
|
|
|
3
3
|
import { basename, join } from "node:path";
|
|
4
4
|
|
|
5
5
|
// packages/typegen/src/codegen/constants.ts
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
UDINT: 32,
|
|
16
|
-
DWORD: 32,
|
|
17
|
-
REAL: 32,
|
|
18
|
-
LINT: 64,
|
|
19
|
-
ULINT: 64,
|
|
20
|
-
LWORD: 64,
|
|
21
|
-
LREAL: 64
|
|
6
|
+
import {
|
|
7
|
+
elementaryType,
|
|
8
|
+
elementaryTypes,
|
|
9
|
+
integerRange,
|
|
10
|
+
isIntegerValued
|
|
11
|
+
} from "@tsplc/iec";
|
|
12
|
+
var isNumberInteger = (name) => {
|
|
13
|
+
const type = elementaryType(name);
|
|
14
|
+
return isIntegerValued(type) && type.bits <= 32;
|
|
22
15
|
};
|
|
16
|
+
var integerRanges = new Map(elementaryTypes.filter(isIntegerValued).map((type) => [type.name, integerRange(type)]));
|
|
17
|
+
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_]*|[A-Za-z_]\w*(?:\s*\.\s*[A-Za-z_]\w*)?|[()+\-*/]`, "g");
|
|
23
18
|
function integerExpression(text, lookup) {
|
|
24
19
|
const compact = text.replace(/\s+/g, "");
|
|
25
|
-
const tokens = (text.match(
|
|
26
|
-
if (tokens.join("") !== compact || !tokens.length)
|
|
20
|
+
const tokens = (text.match(integerToken) ?? []).map((token) => token.replace(/\s+/g, ""));
|
|
21
|
+
if (tokens.join("") !== compact || !tokens.length) {
|
|
27
22
|
throw new Error(`unsupported integer expression: ${text}`);
|
|
23
|
+
}
|
|
24
|
+
const safe = (value) => {
|
|
25
|
+
if (!Number.isSafeInteger(value)) {
|
|
26
|
+
throw new Error(`integer outside JavaScript's safe range: ${text}`);
|
|
27
|
+
}
|
|
28
|
+
return value;
|
|
29
|
+
};
|
|
28
30
|
let position = 0;
|
|
29
31
|
function atom() {
|
|
30
32
|
const token = tokens[position++];
|
|
31
|
-
if (token === "+")
|
|
33
|
+
if (token === "+") {
|
|
32
34
|
return atom();
|
|
33
|
-
|
|
35
|
+
}
|
|
36
|
+
if (token === "-") {
|
|
34
37
|
return -atom();
|
|
38
|
+
}
|
|
35
39
|
if (token === "(") {
|
|
36
40
|
const value = sum();
|
|
37
|
-
if (tokens[position++] !== ")")
|
|
41
|
+
if (tokens[position++] !== ")") {
|
|
38
42
|
throw new Error(`unclosed integer expression: ${text}`);
|
|
43
|
+
}
|
|
39
44
|
return value;
|
|
40
45
|
}
|
|
41
|
-
const typed = token &&
|
|
46
|
+
const typed = token && [...integerRanges].find(([name]) => token.toUpperCase().startsWith(`${name}#`));
|
|
42
47
|
if (typed) {
|
|
43
|
-
const
|
|
44
|
-
const
|
|
45
|
-
|
|
46
|
-
const limit = 1n << BigInt(bits - (signed ? 1 : 0));
|
|
47
|
-
if (BigInt(value) < (signed ? -limit : 0n) || BigInt(value) >= limit)
|
|
48
|
+
const [name, [minimum, maximum]] = typed;
|
|
49
|
+
const value = integerExpression(token.slice(name.length + 1), lookup);
|
|
50
|
+
if (BigInt(value) < minimum || BigInt(value) > maximum) {
|
|
48
51
|
throw new Error(`typed integer outside ${name}: ${token}`);
|
|
52
|
+
}
|
|
49
53
|
return value;
|
|
50
54
|
}
|
|
51
55
|
if (token && /^\d/.test(token)) {
|
|
52
56
|
const [base, digits] = token.replace(/_/g, "").split("#");
|
|
53
|
-
if (digits !== undefined && ![...digits].every((digit) => parseInt(digit, 16) < Number(base)))
|
|
57
|
+
if (digits !== undefined && ![...digits].every((digit) => parseInt(digit, 16) < Number(base))) {
|
|
54
58
|
throw new Error(`invalid base-${base} literal: ${token}`);
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
throw new Error(`integer outside JavaScript's safe range: ${text}`);
|
|
58
|
-
return value;
|
|
59
|
+
}
|
|
60
|
+
return safe(digits === undefined ? Number(base) : parseInt(digits, Number(base)));
|
|
59
61
|
}
|
|
60
|
-
if (token && /^[A-Za-z_]/.test(token))
|
|
62
|
+
if (token && /^[A-Za-z_]/.test(token)) {
|
|
61
63
|
return lookup(token);
|
|
64
|
+
}
|
|
62
65
|
throw new Error(`invalid integer expression: ${text}`);
|
|
63
66
|
}
|
|
64
67
|
function product() {
|
|
@@ -66,11 +69,10 @@ function integerExpression(text, lookup) {
|
|
|
66
69
|
while (tokens[position] === "*" || tokens[position] === "/") {
|
|
67
70
|
const operator = tokens[position++];
|
|
68
71
|
const right = atom();
|
|
69
|
-
if (operator === "/" && right === 0)
|
|
72
|
+
if (operator === "/" && right === 0) {
|
|
70
73
|
throw new Error(`division by zero: ${text}`);
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
throw new Error(`integer outside JavaScript's safe range: ${text}`);
|
|
74
|
+
}
|
|
75
|
+
value = safe(operator === "*" ? value * right : Math.trunc(value / right));
|
|
74
76
|
}
|
|
75
77
|
return value;
|
|
76
78
|
}
|
|
@@ -79,19 +81,63 @@ function integerExpression(text, lookup) {
|
|
|
79
81
|
while (tokens[position] === "+" || tokens[position] === "-") {
|
|
80
82
|
const operator = tokens[position++];
|
|
81
83
|
const right = product();
|
|
82
|
-
value = operator === "+" ? value + right : value - right;
|
|
83
|
-
if (!Number.isSafeInteger(value))
|
|
84
|
-
throw new Error(`integer outside JavaScript's safe range: ${text}`);
|
|
84
|
+
value = safe(operator === "+" ? value + right : value - right);
|
|
85
85
|
}
|
|
86
86
|
return value;
|
|
87
87
|
}
|
|
88
88
|
const value = sum();
|
|
89
|
-
if (position !== tokens.length || !Number.isSafeInteger(value))
|
|
89
|
+
if (position !== tokens.length || !Number.isSafeInteger(value)) {
|
|
90
90
|
throw new Error(`invalid or unsafe integer expression: ${text}`);
|
|
91
|
+
}
|
|
91
92
|
return value;
|
|
92
93
|
}
|
|
94
|
+
function constantResolver(lists) {
|
|
95
|
+
const values = new Map;
|
|
96
|
+
const resolving = new Set;
|
|
97
|
+
const definitions = lists.flatMap((list) => list.members.map((member) => ({
|
|
98
|
+
list,
|
|
99
|
+
member,
|
|
100
|
+
key: `${list.name}.${member.name}`.toUpperCase()
|
|
101
|
+
})));
|
|
102
|
+
const constant = (name, scope) => {
|
|
103
|
+
const key = name.toUpperCase();
|
|
104
|
+
const scoped = scope === null ? undefined : definitions.find((item) => item.key === `${scope}.${name}`.toUpperCase());
|
|
105
|
+
const [definition, ...others] = scoped ? [scoped] : definitions.filter((item) => item.key === key || !name.includes(".") && item.member.name.toUpperCase() === key);
|
|
106
|
+
if (!definition || others.length) {
|
|
107
|
+
throw new Error(`unknown or ambiguous constant ${name}`);
|
|
108
|
+
}
|
|
109
|
+
const cached = values.get(definition.key);
|
|
110
|
+
if (cached !== undefined) {
|
|
111
|
+
return cached;
|
|
112
|
+
}
|
|
113
|
+
if (resolving.has(definition.key)) {
|
|
114
|
+
throw new Error(`cyclic constant ${name}`);
|
|
115
|
+
}
|
|
116
|
+
const { member, list } = definition;
|
|
117
|
+
if (member.initial === undefined || member.type.kind !== "named" || !isNumberInteger(member.type.name.toUpperCase())) {
|
|
118
|
+
throw new Error(`${list.source}: constant ${member.name} must have an integer type and initializer`);
|
|
119
|
+
}
|
|
120
|
+
resolving.add(definition.key);
|
|
121
|
+
const value = integerExpression(member.initial, (reference) => constant(reference, list.name));
|
|
122
|
+
resolving.delete(definition.key);
|
|
123
|
+
values.set(definition.key, value);
|
|
124
|
+
return value;
|
|
125
|
+
};
|
|
126
|
+
return constant;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// packages/typegen/src/codegen/generate.ts
|
|
130
|
+
import { elementaryTypesByName } from "@tsplc/iec";
|
|
131
|
+
import { identifierPattern as identifierPattern2 } from "@tsplc/iec/st";
|
|
93
132
|
|
|
94
133
|
// packages/typegen/src/codegen/parser.ts
|
|
134
|
+
import {
|
|
135
|
+
blockCommentEnd,
|
|
136
|
+
directAddressEnd,
|
|
137
|
+
identifierPattern,
|
|
138
|
+
lineCommentEnd,
|
|
139
|
+
qualifiers
|
|
140
|
+
} from "@tsplc/iec/st";
|
|
95
141
|
function tokenize(source) {
|
|
96
142
|
const tokens = [];
|
|
97
143
|
let offset = 0;
|
|
@@ -103,34 +149,26 @@ function tokenize(source) {
|
|
|
103
149
|
continue;
|
|
104
150
|
}
|
|
105
151
|
if (rest.startsWith("(*")) {
|
|
106
|
-
const
|
|
107
|
-
|
|
108
|
-
offset += 2;
|
|
109
|
-
while (depth && offset < source.text.length) {
|
|
110
|
-
const pair = source.text.slice(offset, offset + 2);
|
|
111
|
-
if (pair === "(*" || pair === "*)") {
|
|
112
|
-
depth += pair === "(*" ? 1 : -1;
|
|
113
|
-
offset += 2;
|
|
114
|
-
} else
|
|
115
|
-
offset++;
|
|
116
|
-
}
|
|
117
|
-
if (depth)
|
|
152
|
+
const end = blockCommentEnd(source.text, offset);
|
|
153
|
+
if (end === null) {
|
|
118
154
|
throw new Error(`${source.name}: unterminated comment`);
|
|
155
|
+
}
|
|
119
156
|
tokens.push({
|
|
120
|
-
text: source.text.slice(
|
|
121
|
-
offset
|
|
157
|
+
text: source.text.slice(offset + 2, end - 2).trim(),
|
|
158
|
+
offset,
|
|
122
159
|
kind: "comment"
|
|
123
160
|
});
|
|
161
|
+
offset = end;
|
|
124
162
|
continue;
|
|
125
163
|
}
|
|
126
|
-
|
|
127
|
-
|
|
164
|
+
if (rest.startsWith("//")) {
|
|
165
|
+
const end = lineCommentEnd(source.text, offset);
|
|
128
166
|
tokens.push({
|
|
129
|
-
text:
|
|
167
|
+
text: source.text.slice(offset + 2, end).trim(),
|
|
130
168
|
offset,
|
|
131
169
|
kind: "comment"
|
|
132
170
|
});
|
|
133
|
-
offset
|
|
171
|
+
offset = end;
|
|
134
172
|
continue;
|
|
135
173
|
}
|
|
136
174
|
const attribute = /^\{(?:[^}'"]|'(?:\$[\s\S]|''|[^'])*'|"(?:\$[\s\S]|""|[^"])*")*\}/.exec(rest);
|
|
@@ -139,10 +177,21 @@ function tokenize(source) {
|
|
|
139
177
|
offset += attribute[0].length;
|
|
140
178
|
continue;
|
|
141
179
|
}
|
|
142
|
-
const
|
|
143
|
-
if (
|
|
180
|
+
const addressEnd = directAddressEnd(source.text, offset);
|
|
181
|
+
if (addressEnd !== null) {
|
|
182
|
+
tokens.push({
|
|
183
|
+
text: source.text.slice(offset, addressEnd),
|
|
184
|
+
offset,
|
|
185
|
+
kind: "code"
|
|
186
|
+
});
|
|
187
|
+
offset = addressEnd;
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
190
|
+
const code = /^(?:'(?:\$[\s\S]|''|[^'])*'|"(?:\$[\s\S]|""|[^"])*"|\d[\d_]*#[\da-fA-F_]+|\d[\d_]*(?:\.(?!\.)[\d_]+)?(?:[eE][+-]?\d+)?|[A-Za-z_]\w*|:=|\.\.|[[\]():;,.+\-*/#])/i.exec(rest);
|
|
191
|
+
if (!code) {
|
|
144
192
|
throw new Error(`${source.name}:${source.text.slice(0, offset).split(`
|
|
145
193
|
`).length}: unsupported token ${JSON.stringify(rest.slice(0, 24))}`);
|
|
194
|
+
}
|
|
146
195
|
tokens.push({ text: code[0], offset, kind: "code" });
|
|
147
196
|
offset += code[0].length;
|
|
148
197
|
}
|
|
@@ -159,8 +208,9 @@ class Parser {
|
|
|
159
208
|
}
|
|
160
209
|
nextIndex() {
|
|
161
210
|
let index = this.position;
|
|
162
|
-
while (this.tokens
|
|
211
|
+
while (index < this.tokens.length && this.tokens[index]?.kind !== "code") {
|
|
163
212
|
index++;
|
|
213
|
+
}
|
|
164
214
|
return index;
|
|
165
215
|
}
|
|
166
216
|
peek() {
|
|
@@ -174,24 +224,28 @@ class Parser {
|
|
|
174
224
|
take() {
|
|
175
225
|
this.position = this.nextIndex();
|
|
176
226
|
const token = this.tokens[this.position++];
|
|
177
|
-
if (!token)
|
|
227
|
+
if (!token) {
|
|
178
228
|
this.error("unexpected end of declaration");
|
|
229
|
+
}
|
|
179
230
|
return token.text;
|
|
180
231
|
}
|
|
181
232
|
accept(value) {
|
|
182
|
-
if (this.peek() !== value)
|
|
233
|
+
if (this.peek() !== value) {
|
|
183
234
|
return false;
|
|
235
|
+
}
|
|
184
236
|
this.take();
|
|
185
237
|
return true;
|
|
186
238
|
}
|
|
187
239
|
expect(value) {
|
|
188
|
-
if (!this.accept(value))
|
|
240
|
+
if (!this.accept(value)) {
|
|
189
241
|
this.error(`expected ${value}, found ${this.peek() || "end of file"}`);
|
|
242
|
+
}
|
|
190
243
|
}
|
|
191
244
|
identifier() {
|
|
192
245
|
const name = this.take();
|
|
193
|
-
if (
|
|
246
|
+
if (!identifierPattern.test(name)) {
|
|
194
247
|
this.error(`expected identifier, found ${name}`);
|
|
248
|
+
}
|
|
195
249
|
return name;
|
|
196
250
|
}
|
|
197
251
|
documentation() {
|
|
@@ -206,16 +260,19 @@ class Parser {
|
|
|
206
260
|
const closing = [];
|
|
207
261
|
while (this.peek() && (closing.length || !stops.includes(this.peek()))) {
|
|
208
262
|
const token = this.take();
|
|
209
|
-
if (token === "(" || token === "[")
|
|
263
|
+
if (token === "(" || token === "[") {
|
|
210
264
|
closing.push(token === "(" ? ")" : "]");
|
|
265
|
+
}
|
|
211
266
|
if (token === ")" || token === "]") {
|
|
212
|
-
if (closing.pop() !== token)
|
|
267
|
+
if (closing.pop() !== token) {
|
|
213
268
|
this.error(`unmatched ${token}`);
|
|
269
|
+
}
|
|
214
270
|
}
|
|
215
271
|
values.push(token);
|
|
216
272
|
}
|
|
217
|
-
if (!values.length || closing.length)
|
|
273
|
+
if (!values.length || closing.length) {
|
|
218
274
|
this.error("incomplete expression");
|
|
275
|
+
}
|
|
219
276
|
return values.join(" ");
|
|
220
277
|
}
|
|
221
278
|
reference() {
|
|
@@ -233,14 +290,16 @@ class Parser {
|
|
|
233
290
|
return { kind: "array", dimensions, element: this.reference() };
|
|
234
291
|
}
|
|
235
292
|
const parts = [this.identifier()];
|
|
236
|
-
while (this.accept("."))
|
|
293
|
+
while (this.accept(".")) {
|
|
237
294
|
parts.push(this.identifier());
|
|
295
|
+
}
|
|
238
296
|
const name = parts.join(".");
|
|
239
297
|
const upper = name.toUpperCase();
|
|
240
298
|
if (upper === "STRING" || upper === "WSTRING") {
|
|
241
299
|
const opening = this.peek();
|
|
242
|
-
if (opening !== "(" && opening !== "[")
|
|
300
|
+
if (opening !== "(" && opening !== "[") {
|
|
243
301
|
return { kind: "string", name: upper, length: "80" };
|
|
302
|
+
}
|
|
244
303
|
this.take();
|
|
245
304
|
const closing = opening === "(" ? ")" : "]";
|
|
246
305
|
const length = this.expression([closing]);
|
|
@@ -255,20 +314,23 @@ class Parser {
|
|
|
255
314
|
const published = this.tokens.slice(this.position, this.nextIndex()).some((token) => token.kind === "attribute" && /^\{\s*attribute\s+'symbol'\s*:=\s*'(?:read|write|readwrite)'\s*\}$/i.test(token.text));
|
|
256
315
|
const description = this.documentation();
|
|
257
316
|
const names = [this.identifier()];
|
|
258
|
-
while (this.accept(","))
|
|
317
|
+
while (this.accept(",")) {
|
|
259
318
|
names.push(this.identifier());
|
|
319
|
+
}
|
|
260
320
|
if (this.accept("AT")) {
|
|
261
321
|
const address = this.take();
|
|
262
|
-
if (
|
|
322
|
+
if (directAddressEnd(address, 0) !== address.length) {
|
|
263
323
|
this.error(`expected direct address after AT, found ${address}`);
|
|
324
|
+
}
|
|
264
325
|
}
|
|
265
326
|
this.expect(":");
|
|
266
327
|
const type = this.reference();
|
|
267
328
|
const initial = this.accept(":=") ? this.expression([";"]) : undefined;
|
|
268
329
|
this.expect(";");
|
|
269
330
|
for (const name of names) {
|
|
270
|
-
if (members.some((member) => member.name.toUpperCase() === name.toUpperCase()))
|
|
331
|
+
if (members.some((member) => member.name.toUpperCase() === name.toUpperCase())) {
|
|
271
332
|
this.error(`duplicate member ${name}`);
|
|
333
|
+
}
|
|
272
334
|
members.push({
|
|
273
335
|
name,
|
|
274
336
|
description,
|
|
@@ -302,8 +364,9 @@ class Parser {
|
|
|
302
364
|
do {
|
|
303
365
|
const member = this.identifier();
|
|
304
366
|
const value = this.accept(":=") ? this.expression([",", ")"]) : undefined;
|
|
305
|
-
if (members.some((item) => item.name.toUpperCase() === member.toUpperCase()))
|
|
367
|
+
if (members.some((item) => item.name.toUpperCase() === member.toUpperCase())) {
|
|
306
368
|
this.error(`duplicate enum member ${member}`);
|
|
369
|
+
}
|
|
307
370
|
members.push({ name: member, value });
|
|
308
371
|
} while (this.accept(",") && this.peek() !== ")");
|
|
309
372
|
this.expect(")");
|
|
@@ -313,33 +376,44 @@ class Parser {
|
|
|
313
376
|
} else {
|
|
314
377
|
const type = this.reference();
|
|
315
378
|
this.expect(";");
|
|
316
|
-
declarations.push({
|
|
379
|
+
declarations.push({
|
|
380
|
+
...common,
|
|
381
|
+
kind: "alias",
|
|
382
|
+
type,
|
|
383
|
+
...keyed ? { keyed } : {}
|
|
384
|
+
});
|
|
317
385
|
}
|
|
318
386
|
this.expect("END_TYPE");
|
|
319
387
|
this.accept(";");
|
|
320
388
|
}
|
|
321
|
-
if (!declarations.length)
|
|
389
|
+
if (!declarations.length) {
|
|
322
390
|
this.error("no TYPE declarations found");
|
|
391
|
+
}
|
|
323
392
|
return declarations;
|
|
324
393
|
}
|
|
325
394
|
globals(name) {
|
|
326
395
|
const description = this.documentation();
|
|
327
396
|
this.expect("VAR_GLOBAL");
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
while (["CONSTANT", "RETAIN", "PERSISTENT"].includes(this.peek())) {
|
|
397
|
+
const written = new Set;
|
|
398
|
+
while (qualifiers.has(this.peek())) {
|
|
331
399
|
const qualifier = this.take().toUpperCase();
|
|
332
|
-
if (
|
|
400
|
+
if (written.has(qualifier)) {
|
|
333
401
|
this.error(`duplicate ${qualifier} qualifier`);
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
constant = true;
|
|
402
|
+
}
|
|
403
|
+
written.add(qualifier);
|
|
337
404
|
}
|
|
338
405
|
const members = this.members("END_VAR");
|
|
339
406
|
this.accept(";");
|
|
340
|
-
if (this.peek())
|
|
407
|
+
if (this.peek()) {
|
|
341
408
|
this.error("only one VAR_GLOBAL block per file is supported");
|
|
342
|
-
|
|
409
|
+
}
|
|
410
|
+
return {
|
|
411
|
+
name,
|
|
412
|
+
description,
|
|
413
|
+
source: this.source.name,
|
|
414
|
+
constant: written.has("CONSTANT"),
|
|
415
|
+
members
|
|
416
|
+
};
|
|
343
417
|
}
|
|
344
418
|
}
|
|
345
419
|
function parseDeclarations(source) {
|
|
@@ -350,40 +424,41 @@ function parseGlobals(source, name) {
|
|
|
350
424
|
}
|
|
351
425
|
|
|
352
426
|
// packages/typegen/src/codegen/generate.ts
|
|
353
|
-
var
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
TOD: "number",
|
|
372
|
-
TIME_OF_DAY: "number",
|
|
373
|
-
DATE: "number",
|
|
374
|
-
DT: "number",
|
|
375
|
-
DATE_AND_TIME: "number"
|
|
427
|
+
var scalarType = (type) => {
|
|
428
|
+
switch (type.family) {
|
|
429
|
+
case "bool":
|
|
430
|
+
return "boolean";
|
|
431
|
+
case "integer":
|
|
432
|
+
case "bits":
|
|
433
|
+
return type.bits === 64 ? "bigint" : "number";
|
|
434
|
+
case "real":
|
|
435
|
+
return "number";
|
|
436
|
+
case "duration":
|
|
437
|
+
case "date":
|
|
438
|
+
case "timeOfDay":
|
|
439
|
+
case "dateTime":
|
|
440
|
+
return type.bits === 32 ? "number" : undefined;
|
|
441
|
+
case "char":
|
|
442
|
+
case "string":
|
|
443
|
+
return;
|
|
444
|
+
}
|
|
376
445
|
};
|
|
446
|
+
var scalars = Object.fromEntries([...elementaryTypesByName].flatMap(([name, type]) => {
|
|
447
|
+
const typescript = scalarType(type);
|
|
448
|
+
return typescript ? [[name, typescript]] : [];
|
|
449
|
+
}));
|
|
377
450
|
async function stFiles(directory) {
|
|
378
451
|
const entries = await readdir(directory, { withFileTypes: true });
|
|
379
452
|
const paths = await Promise.all(entries.sort((a, b) => {
|
|
380
|
-
if (a.name === b.name)
|
|
453
|
+
if (a.name === b.name) {
|
|
381
454
|
return 0;
|
|
455
|
+
}
|
|
382
456
|
return a.name < b.name ? -1 : 1;
|
|
383
457
|
}).map(async (entry) => {
|
|
384
458
|
const file = join(directory, entry.name);
|
|
385
|
-
if (entry.isDirectory())
|
|
459
|
+
if (entry.isDirectory()) {
|
|
386
460
|
return stFiles(file);
|
|
461
|
+
}
|
|
387
462
|
return entry.isFile() && /\.st$/i.test(file) ? [file] : [];
|
|
388
463
|
}));
|
|
389
464
|
return paths.flat();
|
|
@@ -396,85 +471,68 @@ function unique(items) {
|
|
|
396
471
|
const result = new Map;
|
|
397
472
|
for (const item of items) {
|
|
398
473
|
const key = item.name.toUpperCase();
|
|
399
|
-
if (result.has(key))
|
|
474
|
+
if (result.has(key)) {
|
|
400
475
|
throw new Error(`${item.source}: duplicate declaration ${item.name} (also in ${result.get(key)?.source})`);
|
|
476
|
+
}
|
|
401
477
|
result.set(key, item);
|
|
402
478
|
}
|
|
403
479
|
return result;
|
|
404
480
|
}
|
|
481
|
+
var readSources = (files) => Promise.all(files.map(async (name) => ({ name, text: await readFile(name, "utf8") })));
|
|
405
482
|
async function generateTypes(options) {
|
|
406
483
|
const typeFiles = typeof options.types === "string" ? await stFiles(options.types) : options.types;
|
|
407
|
-
const declarations = (await
|
|
484
|
+
const declarations = (await readSources(typeFiles)).flatMap((source) => parseDeclarations(source));
|
|
408
485
|
const globalFiles = typeof options.globals === "string" ? await stFiles(options.globals) : options.globals ?? [];
|
|
409
|
-
if (!typeFiles.length && !globalFiles.length && (typeof options.types === "string" || typeof options.globals === "string"))
|
|
486
|
+
if (!typeFiles.length && !globalFiles.length && (typeof options.types === "string" || typeof options.globals === "string")) {
|
|
410
487
|
throw new Error(`no .st declarations found in ${typeof options.types === "string" ? options.types : "the selected source files"}`);
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
members: list.members.filter((member) => options.publication ? [
|
|
416
|
-
...options.publication.production,
|
|
417
|
-
...options.publication.development
|
|
418
|
-
].includes(`${list.name}.${member.name}`) : member.published)
|
|
419
|
-
}).filter((list) => list.constant || list.members.length);
|
|
420
|
-
const contract = emit(declarations, globals, options.publishedGlobalsOnly ?? false, options.declarations ?? true);
|
|
488
|
+
}
|
|
489
|
+
const globals = (await readSources(globalFiles)).map((source) => parseGlobals(source, basename(source.name).replace(/\.st$/i, "")));
|
|
490
|
+
const publishedGlobalsOnly = options.publishedGlobalsOnly ?? false;
|
|
491
|
+
const contract = emit(declarations, publishedGlobalsOnly ? published(globals, options.publication) : globals, { publishedGlobalsOnly, emitDeclarations: options.declarations ?? true });
|
|
421
492
|
return options.publication ? `${contract}
|
|
422
493
|
export const publication = ${JSON.stringify(options.publication, null, 2)} as const;
|
|
423
494
|
` : contract;
|
|
424
495
|
}
|
|
425
|
-
function
|
|
496
|
+
function published(globals, publication) {
|
|
497
|
+
return globals.map((list) => list.constant ? list : {
|
|
498
|
+
...list,
|
|
499
|
+
members: list.members.filter((member) => publication ? [
|
|
500
|
+
...publication.production,
|
|
501
|
+
...publication.development
|
|
502
|
+
].includes(`${list.name}.${member.name}`) : member.published)
|
|
503
|
+
}).filter((list) => list.constant || list.members.length);
|
|
504
|
+
}
|
|
505
|
+
function emit(declarations, globals, {
|
|
506
|
+
publishedGlobalsOnly,
|
|
507
|
+
emitDeclarations
|
|
508
|
+
}) {
|
|
426
509
|
const types = unique(declarations);
|
|
427
510
|
unique(globals);
|
|
428
511
|
const constants = globals.filter((list) => list.constant);
|
|
429
512
|
const constantLists = publishedGlobalsOnly ? constants.map((list) => ({
|
|
430
513
|
...list,
|
|
431
|
-
members: list.members.filter((member) => member.type.kind === "named" &&
|
|
514
|
+
members: list.members.filter((member) => member.type.kind === "named" && isNumberInteger(member.type.name.toUpperCase()))
|
|
432
515
|
})).filter((list) => list.members.length) : constants;
|
|
433
516
|
const variableLists = globals.filter((list) => !list.constant);
|
|
434
|
-
const
|
|
435
|
-
const resolvingConstants = new Set;
|
|
436
|
-
const constantDefinitions = constants.flatMap((list) => list.members.map((member) => ({
|
|
437
|
-
list,
|
|
438
|
-
member,
|
|
439
|
-
key: `${list.name}.${member.name}`.toUpperCase()
|
|
440
|
-
})));
|
|
441
|
-
function constant(name, scope) {
|
|
442
|
-
const key = name.toUpperCase();
|
|
443
|
-
const scoped = constantDefinitions.find((item) => item.key === `${scope}.${name}`.toUpperCase());
|
|
444
|
-
const candidates = scoped ? [scoped] : constantDefinitions.filter((item) => item.key === key || !name.includes(".") && item.member.name.toUpperCase() === key);
|
|
445
|
-
if (candidates.length !== 1)
|
|
446
|
-
throw new Error(`unknown or ambiguous constant ${name}`);
|
|
447
|
-
const definition = candidates[0];
|
|
448
|
-
const cached = constantValues.get(definition.key);
|
|
449
|
-
if (cached !== undefined)
|
|
450
|
-
return cached;
|
|
451
|
-
if (resolvingConstants.has(definition.key))
|
|
452
|
-
throw new Error(`cyclic constant ${name}`);
|
|
453
|
-
const { member, list } = definition;
|
|
454
|
-
if (member.initial === undefined || member.type.kind !== "named" || !integerTypePattern.test(member.type.name.toUpperCase()))
|
|
455
|
-
throw new Error(`${list.source}: constant ${member.name} must have an integer type and initializer`);
|
|
456
|
-
resolvingConstants.add(definition.key);
|
|
457
|
-
const value = integerExpression(member.initial, (reference) => constant(reference, list.name));
|
|
458
|
-
resolvingConstants.delete(definition.key);
|
|
459
|
-
constantValues.set(definition.key, value);
|
|
460
|
-
return value;
|
|
461
|
-
}
|
|
517
|
+
const constant = constantResolver(constants);
|
|
462
518
|
function bound(expression) {
|
|
463
|
-
return integerExpression(expression, (name) => constant(name));
|
|
519
|
+
return integerExpression(expression, (name) => constant(name, null));
|
|
464
520
|
}
|
|
465
521
|
function dimensions(type) {
|
|
466
522
|
return type.dimensions.map(({ lower, upper }) => {
|
|
467
523
|
const start = bound(lower);
|
|
468
524
|
const end = bound(upper);
|
|
469
|
-
if (end < start || !Number.isSafeInteger(end - start + 1))
|
|
525
|
+
if (end < start || !Number.isSafeInteger(end - start + 1)) {
|
|
470
526
|
throw new Error(`invalid array bounds ${lower}..${upper}`);
|
|
527
|
+
}
|
|
471
528
|
return { start, end };
|
|
472
529
|
});
|
|
473
530
|
}
|
|
474
531
|
function declaration(name) {
|
|
475
532
|
const found = types.get(name.toUpperCase());
|
|
476
|
-
if (!found)
|
|
533
|
+
if (!found) {
|
|
477
534
|
throw new Error(`unknown IEC type ${name}`);
|
|
535
|
+
}
|
|
478
536
|
return found;
|
|
479
537
|
}
|
|
480
538
|
function tsType(type) {
|
|
@@ -484,49 +542,61 @@ function emit(declarations, globals, publishedGlobalsOnly, emitDeclarations) {
|
|
|
484
542
|
}
|
|
485
543
|
if (type.kind === "string") {
|
|
486
544
|
const length = bound(type.length);
|
|
487
|
-
if (length < 1)
|
|
545
|
+
if (length < 1) {
|
|
488
546
|
throw new Error(`invalid ${type.name} length ${length}`);
|
|
547
|
+
}
|
|
489
548
|
return "string";
|
|
490
549
|
}
|
|
491
550
|
return scalars[type.name.toUpperCase()] ?? declaration(type.name).name;
|
|
492
551
|
}
|
|
493
552
|
function resolved(type) {
|
|
494
|
-
if (type.kind !== "named" || scalars[type.name.toUpperCase()])
|
|
553
|
+
if (type.kind !== "named" || scalars[type.name.toUpperCase()]) {
|
|
495
554
|
return type;
|
|
555
|
+
}
|
|
496
556
|
const definition = declaration(type.name);
|
|
497
|
-
if (definition.kind === "alias")
|
|
557
|
+
if (definition.kind === "alias") {
|
|
498
558
|
return resolved(definition.type);
|
|
499
|
-
|
|
559
|
+
}
|
|
560
|
+
if (definition.kind === "enum") {
|
|
500
561
|
return { kind: "named", name: definition.base };
|
|
562
|
+
}
|
|
501
563
|
return type;
|
|
502
564
|
}
|
|
503
565
|
function iecType(type) {
|
|
504
566
|
const actual = resolved(type);
|
|
505
|
-
if (actual.kind === "string")
|
|
567
|
+
if (actual.kind === "string") {
|
|
506
568
|
return `${actual.name}(${bound(actual.length)})`;
|
|
507
|
-
|
|
569
|
+
}
|
|
570
|
+
if (actual.kind === "array") {
|
|
508
571
|
return `ARRAY[${dimensions(actual).map(({ start, end }) => `${start}..${end}`).join(", ")}] OF ${iecType(actual.element)}`;
|
|
572
|
+
}
|
|
509
573
|
return scalars[actual.name.toUpperCase()] ? actual.name.toUpperCase() : declaration(actual.name).name;
|
|
510
574
|
}
|
|
511
575
|
const ordered = [];
|
|
512
576
|
const visiting = new Set;
|
|
513
577
|
const visited = new Set;
|
|
514
578
|
function visitReference(type) {
|
|
515
|
-
if (type.kind === "array")
|
|
579
|
+
if (type.kind === "array") {
|
|
516
580
|
return visitReference(type.element);
|
|
517
|
-
|
|
581
|
+
}
|
|
582
|
+
if (type.kind === "named" && !scalars[type.name.toUpperCase()]) {
|
|
518
583
|
visit(declaration(type.name));
|
|
584
|
+
}
|
|
519
585
|
}
|
|
520
586
|
function visit(type) {
|
|
521
|
-
if (visited.has(type.name))
|
|
587
|
+
if (visited.has(type.name)) {
|
|
522
588
|
return;
|
|
523
|
-
|
|
589
|
+
}
|
|
590
|
+
if (visiting.has(type.name)) {
|
|
524
591
|
throw new Error(`${type.source}: cyclic type reference involving ${type.name}`);
|
|
592
|
+
}
|
|
525
593
|
visiting.add(type.name);
|
|
526
|
-
if (type.kind === "struct")
|
|
594
|
+
if (type.kind === "struct") {
|
|
527
595
|
type.members.forEach((member) => visitReference(member.type));
|
|
528
|
-
|
|
596
|
+
}
|
|
597
|
+
if (type.kind === "alias") {
|
|
529
598
|
visitReference(type.type);
|
|
599
|
+
}
|
|
530
600
|
visiting.delete(type.name);
|
|
531
601
|
visited.add(type.name);
|
|
532
602
|
ordered.push(type);
|
|
@@ -537,20 +607,23 @@ function emit(declarations, globals, publishedGlobalsOnly, emitDeclarations) {
|
|
|
537
607
|
...declarations.map((type) => type.name),
|
|
538
608
|
...constantLists.map((list) => list.name)
|
|
539
609
|
]) {
|
|
540
|
-
if (
|
|
610
|
+
if (!identifierPattern2.test(name) || reserved.has(name) || /^_fields\d+$/.test(name)) {
|
|
541
611
|
throw new Error(`name cannot be exported to TypeScript: ${name}`);
|
|
612
|
+
}
|
|
542
613
|
reserved.add(name);
|
|
543
614
|
}
|
|
544
615
|
const indexes = new Map(ordered.map((type, index) => [type.name, index]));
|
|
545
616
|
function complex(type) {
|
|
546
617
|
const actual = resolved(type);
|
|
547
|
-
if (actual.kind === "array")
|
|
618
|
+
if (actual.kind === "array") {
|
|
548
619
|
return complex(actual.element);
|
|
620
|
+
}
|
|
549
621
|
return actual.kind === "named" && !scalars[actual.name.toUpperCase()];
|
|
550
622
|
}
|
|
551
623
|
function keyed(type) {
|
|
552
|
-
if (type.kind !== "named" || scalars[type.name.toUpperCase()])
|
|
624
|
+
if (type.kind !== "named" || scalars[type.name.toUpperCase()]) {
|
|
553
625
|
return false;
|
|
626
|
+
}
|
|
554
627
|
const definition = declaration(type.name);
|
|
555
628
|
return definition.kind === "alias" && (!!definition.keyed || keyed(definition.type));
|
|
556
629
|
}
|
|
@@ -558,8 +631,9 @@ function emit(declarations, globals, publishedGlobalsOnly, emitDeclarations) {
|
|
|
558
631
|
const actual = resolved(type);
|
|
559
632
|
if (actual.kind === "named" && complex(actual)) {
|
|
560
633
|
const children = `_fields${indexes.get(declaration(actual.name).name)}`;
|
|
561
|
-
if (path === '""')
|
|
634
|
+
if (path === '""') {
|
|
562
635
|
return children;
|
|
636
|
+
}
|
|
563
637
|
return `${children}.map((member) => ({ ...member, field: ${path} + "." + member.field }))`;
|
|
564
638
|
}
|
|
565
639
|
if (actual.kind === "array" && (complex(actual.element) || keyed(type))) {
|
|
@@ -597,12 +671,13 @@ ${type.members.map((member) => `...${fields(member.type, quote(member.name), mem
|
|
|
597
671
|
output.push(`const _fields${indexes.get(type.name)}: PlcField[] = ${fields({ kind: "named", name: type.name }, '""', type.description)};
|
|
598
672
|
`);
|
|
599
673
|
} else {
|
|
600
|
-
if (!
|
|
674
|
+
if (!isNumberInteger(type.base)) {
|
|
601
675
|
throw new Error(`unsupported enum base ${type.base}`);
|
|
676
|
+
}
|
|
602
677
|
const entries = new Map;
|
|
603
678
|
for (const member of type.members) {
|
|
604
679
|
const previous = [...entries.values()].at(-1) ?? -1;
|
|
605
|
-
const value = member.value === undefined ? previous + 1 : integerExpression(member.value, (name) => entries.get(name.toUpperCase()) ?? constant(name));
|
|
680
|
+
const value = member.value === undefined ? previous + 1 : integerExpression(member.value, (name) => entries.get(name.toUpperCase()) ?? constant(name, null));
|
|
606
681
|
entries.set(member.name.toUpperCase(), value);
|
|
607
682
|
}
|
|
608
683
|
output.push(...declare(`${doc}export const ${type.name} = { ${type.members.map((member) => `${quote(member.name)}: ${entries.get(member.name.toUpperCase())}`).join(", ")} } as const;
|
|
@@ -622,7 +697,7 @@ ${ordered.map((type) => `${quote(type.name)}: _fields${indexes.get(type.name)},`
|
|
|
622
697
|
`);
|
|
623
698
|
for (const list of emitDeclarations ? constantLists : []) {
|
|
624
699
|
output.push(`${documentation(list.description)}export const ${list.name} = {
|
|
625
|
-
${list.members.map((member) => `${documentation(member.description)}${quote(member.name)}: ${constant(`${list.name}.${member.name}
|
|
700
|
+
${list.members.map((member) => `${documentation(member.description)}${quote(member.name)}: ${constant(`${list.name}.${member.name}`, null)},`).join(`
|
|
626
701
|
`)}
|
|
627
702
|
} as const;
|
|
628
703
|
`);
|
|
@@ -650,6 +725,8 @@ ${list.members.map((member) => `${documentation(member.description)}${quote(memb
|
|
|
650
725
|
// packages/typegen/src/hardware.ts
|
|
651
726
|
import { readdir as readdir2, readFile as readFile2 } from "node:fs/promises";
|
|
652
727
|
import { resolve } from "node:path";
|
|
728
|
+
|
|
729
|
+
// packages/typegen/src/hardware/eds.ts
|
|
653
730
|
var cipTypes = {
|
|
654
731
|
193: "BOOL",
|
|
655
732
|
194: "SINT",
|
|
@@ -667,24 +744,25 @@ var cipTypes = {
|
|
|
667
744
|
211: "DWORD",
|
|
668
745
|
212: "LWORD"
|
|
669
746
|
};
|
|
670
|
-
function
|
|
671
|
-
let clean = ""
|
|
747
|
+
function stripComments(text) {
|
|
748
|
+
let clean = "";
|
|
749
|
+
const offsets = [];
|
|
750
|
+
let quote = false;
|
|
751
|
+
let comment = false;
|
|
672
752
|
for (let i = 0;i < text.length; i++) {
|
|
673
|
-
const c = text
|
|
674
|
-
if (comment
|
|
675
|
-
if (c === `
|
|
753
|
+
const c = text.charAt(i);
|
|
754
|
+
if (comment && c !== `
|
|
676
755
|
`) {
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
756
|
+
continue;
|
|
757
|
+
}
|
|
758
|
+
comment = false;
|
|
759
|
+
if (c === '"' && quote && text.charAt(i + 1) === '"') {
|
|
760
|
+
clean += '""';
|
|
761
|
+
offsets.push(i, i + 1);
|
|
762
|
+
i++;
|
|
680
763
|
continue;
|
|
681
764
|
}
|
|
682
765
|
if (c === '"') {
|
|
683
|
-
if (quote && text[i + 1] === '"') {
|
|
684
|
-
clean += '""';
|
|
685
|
-
i++;
|
|
686
|
-
continue;
|
|
687
|
-
}
|
|
688
766
|
quote = !quote;
|
|
689
767
|
}
|
|
690
768
|
if (c === "$" && !quote) {
|
|
@@ -692,98 +770,137 @@ function readEdsRecords(text) {
|
|
|
692
770
|
continue;
|
|
693
771
|
}
|
|
694
772
|
clean += c;
|
|
773
|
+
offsets.push(i);
|
|
695
774
|
}
|
|
696
|
-
if (quote)
|
|
775
|
+
if (quote) {
|
|
697
776
|
throw new Error("Unterminated EDS string.");
|
|
698
|
-
|
|
777
|
+
}
|
|
778
|
+
return { clean, offsets };
|
|
779
|
+
}
|
|
780
|
+
function recordFields(body) {
|
|
781
|
+
const fields = [];
|
|
782
|
+
let field = "";
|
|
783
|
+
let quoted = false;
|
|
784
|
+
for (let i = 0;i < body.length; i++) {
|
|
785
|
+
const c = body.charAt(i);
|
|
786
|
+
if (c === '"') {
|
|
787
|
+
if (quoted && body.charAt(i + 1) === '"') {
|
|
788
|
+
field += '"';
|
|
789
|
+
i++;
|
|
790
|
+
} else {
|
|
791
|
+
quoted = !quoted;
|
|
792
|
+
}
|
|
793
|
+
} else if (c === "," && !quoted) {
|
|
794
|
+
fields.push(field.trim());
|
|
795
|
+
field = "";
|
|
796
|
+
} else {
|
|
797
|
+
field += c;
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
fields.push(field.trim());
|
|
801
|
+
return fields;
|
|
802
|
+
}
|
|
803
|
+
function edsSections(text) {
|
|
804
|
+
const { clean, offsets } = stripComments(text);
|
|
805
|
+
const sections = new Map;
|
|
699
806
|
let section;
|
|
700
|
-
const tokens = /\[([^\]\r\n]+)\]|([A-Za-z_][\w]*)\s*=\s*((?:"(?:[^"]|"")*"|[^;])*)\s*;/g;
|
|
701
807
|
let end = 0;
|
|
702
|
-
for (const match of clean.matchAll(
|
|
703
|
-
if (clean.slice(end, match.index).trim())
|
|
808
|
+
for (const match of clean.matchAll(/\[([^\]\r\n]+)\]|([A-Za-z_][\w]*)\s*=\s*((?:"(?:[^"]|"")*"|[^;])*)\s*;/g)) {
|
|
809
|
+
if (clean.slice(end, match.index).trim()) {
|
|
704
810
|
throw new Error("Malformed EDS record or section.");
|
|
811
|
+
}
|
|
705
812
|
end = match.index + match[0].length;
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
813
|
+
const [, header, key, body] = match;
|
|
814
|
+
if (header) {
|
|
815
|
+
const name = header.trim();
|
|
816
|
+
if (sections.has(name)) {
|
|
817
|
+
throw new Error(`Duplicate EDS section ${name}.`);
|
|
818
|
+
}
|
|
819
|
+
section = new Map;
|
|
820
|
+
sections.set(name, section);
|
|
711
821
|
continue;
|
|
712
822
|
}
|
|
713
|
-
if (!section)
|
|
823
|
+
if (!section) {
|
|
714
824
|
throw new Error("EDS record outside a section.");
|
|
715
|
-
|
|
716
|
-
if (section
|
|
825
|
+
}
|
|
826
|
+
if (section.has(key)) {
|
|
717
827
|
throw new Error(`Duplicate EDS record ${key}.`);
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
i++;
|
|
727
|
-
} else
|
|
728
|
-
quoted = !quoted;
|
|
729
|
-
} else if (c === "," && !quoted) {
|
|
730
|
-
fields.push(field.trim());
|
|
731
|
-
field = "";
|
|
732
|
-
} else
|
|
733
|
-
field += c;
|
|
734
|
-
}
|
|
735
|
-
fields.push(field.trim());
|
|
736
|
-
section[key] = fields;
|
|
737
|
-
}
|
|
738
|
-
if (clean.slice(end).trim())
|
|
828
|
+
}
|
|
829
|
+
section.set(key, {
|
|
830
|
+
fields: recordFields(body),
|
|
831
|
+
start: offsets[match.index],
|
|
832
|
+
end: offsets[end - 1] + 1
|
|
833
|
+
});
|
|
834
|
+
}
|
|
835
|
+
if (clean.slice(end).trim()) {
|
|
739
836
|
throw new Error("Unterminated EDS record.");
|
|
740
|
-
|
|
837
|
+
}
|
|
838
|
+
return sections;
|
|
839
|
+
}
|
|
840
|
+
function readEdsRecords(text) {
|
|
841
|
+
return Object.fromEntries([...edsSections(text)].map(([name, records]) => [
|
|
842
|
+
name,
|
|
843
|
+
Object.fromEntries([...records].map(([key, record]) => [key, record.fields]))
|
|
844
|
+
]));
|
|
741
845
|
}
|
|
742
|
-
function integer(value, label,
|
|
743
|
-
if (!value || !/^(?:\d+|0x[\da-f]+)$/i.test(value))
|
|
846
|
+
function integer(value, label, { minimum }) {
|
|
847
|
+
if (!value || !/^(?:\d+|0x[\da-f]+)$/i.test(value)) {
|
|
744
848
|
throw new Error(`Invalid EDS ${label}: ${value ?? "missing"}.`);
|
|
849
|
+
}
|
|
745
850
|
const n = Number(value);
|
|
746
|
-
if (!Number.isSafeInteger(n) || n <
|
|
851
|
+
if (!Number.isSafeInteger(n) || n < minimum || n > 16777216) {
|
|
747
852
|
throw new Error(`Unsupported EDS ${label}: ${value}.`);
|
|
853
|
+
}
|
|
748
854
|
return n;
|
|
749
855
|
}
|
|
856
|
+
function logicalSegments(bytes) {
|
|
857
|
+
const [segment, ...rest] = bytes;
|
|
858
|
+
if (segment === undefined) {
|
|
859
|
+
return [];
|
|
860
|
+
}
|
|
861
|
+
const width = segment & 3;
|
|
862
|
+
if ((segment & 224) !== 32 || width > 2) {
|
|
863
|
+
throw new Error(`Unsupported EDS logical path segment ${segment.toString(16)}.`);
|
|
864
|
+
}
|
|
865
|
+
if (width && rest[0] !== 0) {
|
|
866
|
+
throw new Error("Invalid EDS logical path padding.");
|
|
867
|
+
}
|
|
868
|
+
const data = width ? rest.slice(1) : rest;
|
|
869
|
+
const length = 1 << width;
|
|
870
|
+
if (length > data.length) {
|
|
871
|
+
throw new Error("Truncated EDS logical path.");
|
|
872
|
+
}
|
|
873
|
+
const value = data.slice(0, length).reduce((sum, byte, index) => sum + byte * 2 ** (index * 8), 0);
|
|
874
|
+
return [
|
|
875
|
+
{ type: segment & 252, value },
|
|
876
|
+
...logicalSegments(data.slice(length))
|
|
877
|
+
];
|
|
878
|
+
}
|
|
750
879
|
function logicalPath(path) {
|
|
751
880
|
const bytes = path.trim() ? path.trim().split(/\s+/).map((token) => {
|
|
752
|
-
if (!/^[0-9a-f]{2}$/i.test(token))
|
|
881
|
+
if (!/^[0-9a-f]{2}$/i.test(token)) {
|
|
753
882
|
throw new Error(`Unsupported EDS path token ${token}.`);
|
|
883
|
+
}
|
|
754
884
|
return parseInt(token, 16);
|
|
755
885
|
}) : [];
|
|
756
|
-
const
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
throw new Error(`Unsupported EDS logical path segment ${segment.toString(16)}.`);
|
|
762
|
-
if (width && bytes[offset++] !== 0)
|
|
763
|
-
throw new Error("Invalid EDS logical path padding.");
|
|
764
|
-
const length = 1 << width;
|
|
765
|
-
if (offset + length > bytes.length)
|
|
766
|
-
throw new Error("Truncated EDS logical path.");
|
|
767
|
-
let value = 0;
|
|
768
|
-
for (let index = 0;index < length; index++)
|
|
769
|
-
value += bytes[offset++] * 2 ** (index * 8);
|
|
770
|
-
if ((segment & 252) === 36)
|
|
771
|
-
result.instance = value;
|
|
772
|
-
if ((segment & 252) === 44)
|
|
773
|
-
result.points.push(value);
|
|
774
|
-
}
|
|
775
|
-
return result;
|
|
886
|
+
const segments = logicalSegments(bytes);
|
|
887
|
+
return {
|
|
888
|
+
instance: segments.filter(({ type }) => type === 36).at(-1)?.value,
|
|
889
|
+
points: segments.filter(({ type }) => type === 44).map(({ value }) => value)
|
|
890
|
+
};
|
|
776
891
|
}
|
|
777
892
|
var optionalNumber = (value) => value?.trim() && Number.isFinite(Number(value)) ? Number(value) : undefined;
|
|
778
893
|
function parseEds(text, file = "device.eds") {
|
|
779
|
-
const records = readEdsRecords(text)
|
|
780
|
-
|
|
894
|
+
const records = readEdsRecords(text);
|
|
895
|
+
const device = records.Device;
|
|
896
|
+
if (!device?.ProdName?.[0]) {
|
|
781
897
|
throw new Error(`${file}: missing EDS Device.ProdName.`);
|
|
898
|
+
}
|
|
782
899
|
const parameters = Object.entries(records.Params ?? {}).filter(([id]) => /^Param\d+$/.test(id)).map(([id, fields]) => ({
|
|
783
900
|
id,
|
|
784
901
|
name: fields[6] || id,
|
|
785
902
|
type: cipTypes[Number(fields[4])] ?? "opaque",
|
|
786
|
-
size: integer(fields[5], `${id} data size`,
|
|
903
|
+
size: integer(fields[5], `${id} data size`, { minimum: 1 }),
|
|
787
904
|
unit: fields[7] ?? "",
|
|
788
905
|
description: fields[8] ?? "",
|
|
789
906
|
minimum: optionalNumber(fields[9]),
|
|
@@ -793,13 +910,16 @@ function parseEds(text, file = "device.eds") {
|
|
|
793
910
|
const params = new Map(parameters.map((parameter) => [parameter.id, parameter]));
|
|
794
911
|
const instances = new Map;
|
|
795
912
|
const size = (value) => {
|
|
796
|
-
if (!value)
|
|
913
|
+
if (!value) {
|
|
797
914
|
return;
|
|
798
|
-
|
|
799
|
-
|
|
915
|
+
}
|
|
916
|
+
if (!value.startsWith("Param")) {
|
|
917
|
+
return { value: integer(value, "connection size", { minimum: 0 }) };
|
|
918
|
+
}
|
|
800
919
|
const parameter = params.get(value);
|
|
801
|
-
if (!parameter || parameter.default === undefined)
|
|
920
|
+
if (!parameter || parameter.default === undefined) {
|
|
802
921
|
throw new Error(`${file}: connection size ${value} has no numeric default.`);
|
|
922
|
+
}
|
|
803
923
|
return {
|
|
804
924
|
value: parameter.default,
|
|
805
925
|
parameter: value,
|
|
@@ -808,18 +928,24 @@ function parseEds(text, file = "device.eds") {
|
|
|
808
928
|
};
|
|
809
929
|
};
|
|
810
930
|
const connections = Object.entries(records["Connection Manager"] ?? {}).filter(([id]) => /^Connection\d+$/.test(id)).map(([id, fields]) => {
|
|
811
|
-
const path = fields[14] ?? ""
|
|
931
|
+
const path = fields[14] ?? "";
|
|
932
|
+
const points = logicalPath(path).points;
|
|
812
933
|
const assembly = (reference, point) => {
|
|
813
|
-
if (!reference)
|
|
934
|
+
if (!reference) {
|
|
814
935
|
return;
|
|
815
|
-
|
|
936
|
+
}
|
|
937
|
+
const record = records.Assembly?.[reference];
|
|
938
|
+
if (!/^Assem\d+$/.test(reference) || !record) {
|
|
816
939
|
throw new Error(`${file}: unknown connection assembly ${reference}.`);
|
|
817
|
-
|
|
818
|
-
|
|
940
|
+
}
|
|
941
|
+
const instance = point ?? logicalPath(record[1] ?? "").instance;
|
|
942
|
+
if (instance === undefined) {
|
|
819
943
|
throw new Error(`${file}: no runtime instance for ${reference}.`);
|
|
944
|
+
}
|
|
820
945
|
const previous = instances.get(reference);
|
|
821
|
-
if (previous !== undefined && previous !== instance)
|
|
946
|
+
if (previous !== undefined && previous !== instance) {
|
|
822
947
|
throw new Error(`${file}: ${reference} has conflicting runtime instances.`);
|
|
948
|
+
}
|
|
823
949
|
instances.set(reference, instance);
|
|
824
950
|
return instance;
|
|
825
951
|
};
|
|
@@ -838,12 +964,17 @@ function parseEds(text, file = "device.eds") {
|
|
|
838
964
|
const members = [];
|
|
839
965
|
let offsetBits = 0;
|
|
840
966
|
for (let index = 6;index < fields.length; index += 2) {
|
|
841
|
-
if (!fields[index] && !fields[index + 1])
|
|
967
|
+
if (!fields[index] && !fields[index + 1]) {
|
|
842
968
|
continue;
|
|
843
|
-
|
|
969
|
+
}
|
|
970
|
+
const bits = integer(fields[index], `${id} member bits`, {
|
|
971
|
+
minimum: 1
|
|
972
|
+
});
|
|
973
|
+
const reference = fields[index + 1];
|
|
844
974
|
const parameter = reference ? params.get(reference) : undefined;
|
|
845
|
-
if (reference && !parameter)
|
|
975
|
+
if (reference && !parameter) {
|
|
846
976
|
throw new Error(`${file}: ${id} references unknown parameter ${reference}.`);
|
|
977
|
+
}
|
|
847
978
|
members.push({
|
|
848
979
|
...reference ? { parameter: reference } : {},
|
|
849
980
|
name: parameter?.name ?? "Padding",
|
|
@@ -855,9 +986,10 @@ function parseEds(text, file = "device.eds") {
|
|
|
855
986
|
});
|
|
856
987
|
offsetBits += bits;
|
|
857
988
|
}
|
|
858
|
-
const size = fields[2] ? integer(fields[2], `${id} size
|
|
859
|
-
if (offsetBits > size * 8)
|
|
989
|
+
const size = fields[2] ? integer(fields[2], `${id} size`, { minimum: 0 }) : Math.ceil(offsetBits / 8);
|
|
990
|
+
if (offsetBits > size * 8) {
|
|
860
991
|
throw new Error(`${file}: ${id} members exceed its ${size} byte payload.`);
|
|
992
|
+
}
|
|
861
993
|
const instance = logicalPath(fields[1] ?? "").instance ?? instances.get(id);
|
|
862
994
|
return { id, instance, name: fields[0] || id, size, members };
|
|
863
995
|
});
|
|
@@ -871,94 +1003,80 @@ function parseEds(text, file = "device.eds") {
|
|
|
871
1003
|
connections
|
|
872
1004
|
};
|
|
873
1005
|
}
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
else if (entry.isFile() && /\.eds$/i.test(entry.name))
|
|
886
|
-
files.push(path);
|
|
1006
|
+
|
|
1007
|
+
// packages/typegen/src/hardware/channels.ts
|
|
1008
|
+
import { ioScalarBits } from "@tsplc/iec";
|
|
1009
|
+
|
|
1010
|
+
// packages/typegen/src/hardware/process-image.ts
|
|
1011
|
+
import { ioArray, ioScalar, sizePrefix } from "@tsplc/iec";
|
|
1012
|
+
function ioLayout(type) {
|
|
1013
|
+
const array = ioArray(type.trim());
|
|
1014
|
+
if (array) {
|
|
1015
|
+
const element = ioLayout(array.element);
|
|
1016
|
+
return element && element !== "BOOL" ? `${array.length}x${element}` : undefined;
|
|
887
1017
|
}
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
const compatible = descriptor.connections.filter((connection) => (settings.inputs?.assembly === undefined || connection.inputAssembly === settings.inputs.assembly) && (settings.outputs?.assembly === undefined || connection.outputAssembly === settings.outputs.assembly));
|
|
892
|
-
if (settings.connection) {
|
|
893
|
-
const connection = compatible.find((item) => item.id === settings.connection);
|
|
894
|
-
if (!connection)
|
|
895
|
-
throw new Error(`${id}: connection ${settings.connection} does not match the selected assemblies.`);
|
|
896
|
-
return connection;
|
|
1018
|
+
const scalar = ioScalar(type);
|
|
1019
|
+
if (scalar?.family === "integer" || scalar?.family === "bits") {
|
|
1020
|
+
return `INT${scalar.bits}`;
|
|
897
1021
|
}
|
|
898
|
-
|
|
899
|
-
return compatible[0];
|
|
900
|
-
const owners = compatible.filter((item) => item.owner && item.inputAssembly !== undefined && item.outputAssembly !== undefined);
|
|
901
|
-
if (owners.length === 1)
|
|
902
|
-
return owners[0];
|
|
903
|
-
const choices = compatible.map((item) => `${item.id} "${item.name}" (in ${item.inputAssembly ?? "-"}, out ${item.outputAssembly ?? "-"})`).join(", ");
|
|
904
|
-
throw new Error(`${id}: select connection; ${settings.file} offers ${choices}.`);
|
|
1022
|
+
return scalar?.name;
|
|
905
1023
|
}
|
|
906
|
-
|
|
907
|
-
const placed = regions.flatMap(({ region, size, address }) => address ? [{ region, start: Number(address.slice(3)), end: Number(address.slice(3)) + size }] : []);
|
|
908
|
-
const cursors = { I: 0, Q: 0 };
|
|
909
|
-
return regions.map((selection) => {
|
|
910
|
-
const { id, region, size, address } = selection;
|
|
911
|
-
if (address)
|
|
912
|
-
return { ...selection, address };
|
|
913
|
-
if (!generated)
|
|
914
|
-
throw new Error(`${id}: set the %${region}B address the template assigns to this assembly, or let codesys.deviceTree place it.`);
|
|
915
|
-
const aligned = (offset) => Math.ceil(offset / 4) * 4;
|
|
916
|
-
let start = aligned(cursors[region]);
|
|
917
|
-
for (let blocked = true;blocked; ) {
|
|
918
|
-
const overlap = placed.find((item) => item.region === region && item.start < start + size && start < item.end);
|
|
919
|
-
blocked = overlap !== undefined;
|
|
920
|
-
if (overlap)
|
|
921
|
-
start = aligned(overlap.end);
|
|
922
|
-
}
|
|
923
|
-
placed.push({ region, start, end: start + size });
|
|
924
|
-
cursors[region] = start + size;
|
|
925
|
-
return { ...selection, address: `%${region}B${start}` };
|
|
926
|
-
});
|
|
927
|
-
}
|
|
928
|
-
var addressWidths = { 1: "X", 8: "B", 16: "W", 32: "D" };
|
|
1024
|
+
var addressSize = (bits) => bits === 64 ? undefined : sizePrefix(bits);
|
|
929
1025
|
function directAddress(region, base, offsetBits, bits) {
|
|
930
|
-
const
|
|
931
|
-
if (!
|
|
1026
|
+
const size = addressSize(bits);
|
|
1027
|
+
if (!size) {
|
|
932
1028
|
return;
|
|
1029
|
+
}
|
|
933
1030
|
const byte = base + Math.floor(offsetBits / 8);
|
|
934
|
-
if (bits === 1)
|
|
1031
|
+
if (bits === 1) {
|
|
935
1032
|
return `%${region}X${byte}.${offsetBits % 8}`;
|
|
936
|
-
|
|
1033
|
+
}
|
|
1034
|
+
if ((base * 8 + offsetBits) % bits) {
|
|
937
1035
|
return;
|
|
938
|
-
|
|
1036
|
+
}
|
|
1037
|
+
return `%${region}${size}${byte / (bits / 8)}`;
|
|
939
1038
|
}
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
1039
|
+
var byteOffset = (address) => Number(address.slice(3));
|
|
1040
|
+
function regionPlacer(regions, { generatedTree }) {
|
|
1041
|
+
const taken = regions.flatMap(({ region, size, address }) => address ? [
|
|
1042
|
+
{
|
|
1043
|
+
region,
|
|
1044
|
+
start: byteOffset(address),
|
|
1045
|
+
end: byteOffset(address) + size
|
|
1046
|
+
}
|
|
1047
|
+
] : []);
|
|
1048
|
+
const cursors = { I: 0, Q: 0 };
|
|
1049
|
+
const aligned = (offset) => Math.ceil(offset / 4) * 4;
|
|
1050
|
+
return ({ id, region, size, address }) => {
|
|
1051
|
+
if (address) {
|
|
1052
|
+
return address;
|
|
1053
|
+
}
|
|
1054
|
+
if (!generatedTree) {
|
|
1055
|
+
throw new Error(`${id}: set the %${region}B address the template assigns to this assembly, or let codesys.deviceTree place it.`);
|
|
1056
|
+
}
|
|
1057
|
+
const clear = (start) => {
|
|
1058
|
+
const overlap = taken.find((item) => item.region === region && item.start < start + size && start < item.end);
|
|
1059
|
+
return overlap ? clear(aligned(overlap.end)) : start;
|
|
1060
|
+
};
|
|
1061
|
+
const start = clear(aligned(cursors[region]));
|
|
1062
|
+
taken.push({ region, start, end: start + size });
|
|
1063
|
+
cursors[region] = start + size;
|
|
1064
|
+
return `%${region}B${start}`;
|
|
1065
|
+
};
|
|
959
1066
|
}
|
|
960
|
-
|
|
961
|
-
|
|
1067
|
+
|
|
1068
|
+
// packages/typegen/src/hardware/channels.ts
|
|
1069
|
+
function assemblyChannels({
|
|
1070
|
+
device,
|
|
1071
|
+
direction,
|
|
1072
|
+
instance,
|
|
1073
|
+
members,
|
|
1074
|
+
base,
|
|
1075
|
+
payloadSize
|
|
1076
|
+
}) {
|
|
1077
|
+
const prefix = `${direction}s`;
|
|
1078
|
+
const region = direction === "input" ? "I" : "Q";
|
|
1079
|
+
const payloadBits = payloadSize * 8;
|
|
962
1080
|
const address = (offsetBits, bits) => directAddress(region, base, offsetBits, bits);
|
|
963
1081
|
const channels = [];
|
|
964
1082
|
for (let i = 0;i < payloadSize; i++) {
|
|
@@ -976,7 +1094,7 @@ function assemblyChannels(device, direction, instance, members, base, payloadSiz
|
|
|
976
1094
|
unit: "",
|
|
977
1095
|
description: "Assembly payload byte"
|
|
978
1096
|
});
|
|
979
|
-
for (let bit = 0;bit < 8; bit++)
|
|
1097
|
+
for (let bit = 0;bit < 8; bit++) {
|
|
980
1098
|
channels.push({
|
|
981
1099
|
device,
|
|
982
1100
|
id: `${key}.Bit${bit}`,
|
|
@@ -991,19 +1109,26 @@ function assemblyChannels(device, direction, instance, members, base, payloadSiz
|
|
|
991
1109
|
unit: "",
|
|
992
1110
|
description: "Assembly payload bit"
|
|
993
1111
|
});
|
|
1112
|
+
}
|
|
994
1113
|
}
|
|
995
1114
|
const named = members.filter((member) => member.parameter).map((member) => ({ member, name: member.name.replace(/[^\w]/g, "_") }));
|
|
996
|
-
const
|
|
997
|
-
|
|
998
|
-
|
|
1115
|
+
const seen = new Set;
|
|
1116
|
+
const repeated = new Set;
|
|
1117
|
+
for (const { name } of named) {
|
|
1118
|
+
if (seen.has(name)) {
|
|
1119
|
+
repeated.add(name);
|
|
1120
|
+
}
|
|
1121
|
+
seen.add(name);
|
|
1122
|
+
}
|
|
999
1123
|
const counts = new Map;
|
|
1000
1124
|
for (const { member, name } of named) {
|
|
1001
|
-
if (member.offsetBits >= payloadBits)
|
|
1125
|
+
if (member.offsetBits >= payloadBits) {
|
|
1002
1126
|
continue;
|
|
1127
|
+
}
|
|
1003
1128
|
const count = counts.get(name) ?? 0;
|
|
1004
1129
|
counts.set(name, count + 1);
|
|
1005
|
-
const key = `${prefix}.${name}${
|
|
1006
|
-
const scalarBits =
|
|
1130
|
+
const key = `${prefix}.${name}${repeated.has(name) ? `[${count}]` : ""}`;
|
|
1131
|
+
const scalarBits = ioScalarBits(member.type);
|
|
1007
1132
|
const channel = {
|
|
1008
1133
|
device,
|
|
1009
1134
|
id: key,
|
|
@@ -1017,21 +1142,25 @@ function assemblyChannels(device, direction, instance, members, base, payloadSiz
|
|
|
1017
1142
|
unit: member.unit,
|
|
1018
1143
|
description: member.description
|
|
1019
1144
|
};
|
|
1020
|
-
const
|
|
1021
|
-
if (!
|
|
1022
|
-
if (member.offsetBits + member.bits <= payloadBits)
|
|
1145
|
+
const spansScalars = scalarBits !== undefined && scalarBits >= 8 && member.bits > scalarBits && member.bits % scalarBits === 0 && member.offsetBits % scalarBits === 0;
|
|
1146
|
+
if (!spansScalars) {
|
|
1147
|
+
if (member.offsetBits + member.bits <= payloadBits) {
|
|
1023
1148
|
channels.push(channel);
|
|
1149
|
+
}
|
|
1024
1150
|
continue;
|
|
1025
1151
|
}
|
|
1026
1152
|
const length = Math.floor(Math.min(member.bits, payloadBits - member.offsetBits) / scalarBits);
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1153
|
+
const span = {
|
|
1154
|
+
...channel,
|
|
1155
|
+
bits: length * scalarBits,
|
|
1156
|
+
type: `ARRAY[0..${length - 1}] OF ${member.type}`,
|
|
1157
|
+
address: address(member.offsetBits, scalarBits)
|
|
1158
|
+
};
|
|
1159
|
+
channels.push(span);
|
|
1031
1160
|
for (let index = 0;index < length; index++) {
|
|
1032
1161
|
const offset = member.offsetBits + index * scalarBits;
|
|
1033
1162
|
channels.push({
|
|
1034
|
-
...
|
|
1163
|
+
...span,
|
|
1035
1164
|
id: `${key}[${index}]`,
|
|
1036
1165
|
parent: key,
|
|
1037
1166
|
name: `${member.name}[${index}]`,
|
|
@@ -1044,152 +1173,118 @@ function assemblyChannels(device, direction, instance, members, base, payloadSiz
|
|
|
1044
1173
|
}
|
|
1045
1174
|
return channels;
|
|
1046
1175
|
}
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
const
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
const
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
const region = direction === "input" ? "I" : "Q";
|
|
1070
|
-
if (selection?.address && !selection.address.startsWith(`%${region}B`))
|
|
1071
|
-
throw new Error(`${id}: ${direction} assembly needs a %${region}B address.`);
|
|
1072
|
-
const declaredSize = direction === "input" ? connection?.inputSize : connection?.outputSize;
|
|
1073
|
-
const payloadSize = selection?.size ?? declaredSize?.value ?? assembly.size;
|
|
1074
|
-
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)
|
|
1075
|
-
throw new Error(`${id}: ${direction} payload size ${payloadSize} is outside the selected EDS connection's bounds.`);
|
|
1076
|
-
return [
|
|
1077
|
-
{
|
|
1078
|
-
id,
|
|
1079
|
-
direction,
|
|
1080
|
-
region,
|
|
1081
|
-
instance,
|
|
1082
|
-
assembly,
|
|
1083
|
-
size: payloadSize,
|
|
1084
|
-
address: selection?.address
|
|
1085
|
-
}
|
|
1086
|
-
];
|
|
1087
|
-
});
|
|
1088
|
-
return { id, settings, descriptor, connection, selections };
|
|
1089
|
-
});
|
|
1090
|
-
const modbusBytes = { Q: 4, I: 8 };
|
|
1091
|
-
const modbusRegions = selected.flatMap(({ id, settings }) => {
|
|
1092
|
-
const count = Object.keys(settings.modbus?.registers ?? {}).length;
|
|
1093
|
-
return count ? ["Q", "I"].map((region) => ({
|
|
1094
|
-
id,
|
|
1095
|
-
region,
|
|
1096
|
-
size: count * modbusBytes[region],
|
|
1097
|
-
modbus: true
|
|
1098
|
-
})) : [];
|
|
1099
|
-
});
|
|
1100
|
-
const placed = placeAssemblies([...selected.flatMap((device) => device.selections), ...modbusRegions], config.codesys?.deviceTree !== undefined);
|
|
1101
|
-
const devices = selected.map(({ id, settings, descriptor, connection }) => {
|
|
1102
|
-
const assemblies = [];
|
|
1103
|
-
const channels = [];
|
|
1104
|
-
const modbusBase = (region) => Number(placed.find((item) => item.id === id && ("modbus" in item) && item.region === region).address.slice(3));
|
|
1105
|
-
const registers = Object.entries(settings.modbus?.registers ?? {}).map(([name, offset], index) => {
|
|
1106
|
-
const registerChannels = modbusChannels(id, name, modbusBase("Q") + index * modbusBytes.Q, modbusBase("I") + index * modbusBytes.I);
|
|
1107
|
-
channels.push(...registerChannels);
|
|
1108
|
-
const [value, write, status, requests] = registerChannels.map((channel) => channel.address);
|
|
1109
|
-
return { name, offset, value, write, status, requests };
|
|
1176
|
+
|
|
1177
|
+
// packages/typegen/src/hardware/modbus.ts
|
|
1178
|
+
var registerBytes = { Q: 4, I: 8 };
|
|
1179
|
+
function placeModbusRegisters(device, registers, place) {
|
|
1180
|
+
const entries = Object.entries(registers);
|
|
1181
|
+
if (!entries.length) {
|
|
1182
|
+
return [];
|
|
1183
|
+
}
|
|
1184
|
+
const outputBase = byteOffset(place({ id: device, region: "Q", size: entries.length * registerBytes.Q }));
|
|
1185
|
+
const inputBase = byteOffset(place({ id: device, region: "I", size: entries.length * registerBytes.I }));
|
|
1186
|
+
return entries.map(([name, offset], index) => {
|
|
1187
|
+
const channel = (field, direction, offsetBits, bits, type, description) => ({
|
|
1188
|
+
device,
|
|
1189
|
+
id: `modbus.${name}.${field}`,
|
|
1190
|
+
name: `${name} ${field}`,
|
|
1191
|
+
direction,
|
|
1192
|
+
offsetBits,
|
|
1193
|
+
bits,
|
|
1194
|
+
type,
|
|
1195
|
+
address: directAddress(direction === "input" ? "I" : "Q", direction === "input" ? inputBase + index * registerBytes.I : outputBase + index * registerBytes.Q, offsetBits, bits),
|
|
1196
|
+
unit: "",
|
|
1197
|
+
description
|
|
1110
1198
|
});
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
assemblies.push({
|
|
1116
|
-
direction,
|
|
1117
|
-
instance,
|
|
1118
|
-
name: assembly.name,
|
|
1119
|
-
address,
|
|
1120
|
-
size,
|
|
1121
|
-
capacity: assembly.size
|
|
1122
|
-
});
|
|
1123
|
-
channels.push(...assemblyChannels(id, direction, instance, assembly.members, Number(address.slice(3)), size));
|
|
1124
|
-
}
|
|
1199
|
+
const value = channel("value", "output", 0, 16, "WORD", "Value to write");
|
|
1200
|
+
const write = channel("write", "output", 16, 1, "BOOL", "Writes the value when it rises");
|
|
1201
|
+
const status = channel("status", "input", 0, 8, "BYTE", "The last answer: 0 accepted, otherwise the exception code");
|
|
1202
|
+
const requests = channel("requests", "input", 32, 32, "UDINT", "Requests the device answered");
|
|
1125
1203
|
return {
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1204
|
+
register: {
|
|
1205
|
+
name,
|
|
1206
|
+
offset,
|
|
1207
|
+
value: value.address,
|
|
1208
|
+
write: write.address,
|
|
1209
|
+
status: status.address,
|
|
1210
|
+
requests: requests.address
|
|
1211
|
+
},
|
|
1212
|
+
channels: [value, write, status, requests]
|
|
1133
1213
|
};
|
|
1134
1214
|
});
|
|
1135
|
-
return { descriptors, devices };
|
|
1136
1215
|
}
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
const
|
|
1143
|
-
if (!
|
|
1144
|
-
throw new Error(`${
|
|
1216
|
+
|
|
1217
|
+
// packages/typegen/src/hardware/selection.ts
|
|
1218
|
+
function selectConnection(id, settings, descriptor) {
|
|
1219
|
+
const compatible = descriptor.connections.filter((connection) => (settings.inputs?.assembly === undefined || connection.inputAssembly === settings.inputs.assembly) && (settings.outputs?.assembly === undefined || connection.outputAssembly === settings.outputs.assembly));
|
|
1220
|
+
if (settings.connection) {
|
|
1221
|
+
const connection = compatible.find((item) => item.id === settings.connection);
|
|
1222
|
+
if (!connection) {
|
|
1223
|
+
throw new Error(`${id}: connection ${settings.connection} does not match the selected assemblies.`);
|
|
1224
|
+
}
|
|
1225
|
+
return connection;
|
|
1226
|
+
}
|
|
1227
|
+
if (compatible.length <= 1) {
|
|
1228
|
+
return compatible[0];
|
|
1229
|
+
}
|
|
1230
|
+
const owners = compatible.filter((item) => item.owner && item.inputAssembly !== undefined && item.outputAssembly !== undefined);
|
|
1231
|
+
if (owners.length === 1) {
|
|
1232
|
+
return owners[0];
|
|
1233
|
+
}
|
|
1234
|
+
const choices = compatible.map((item) => `${item.id} "${item.name}" (in ${item.inputAssembly ?? "-"}, out ${item.outputAssembly ?? "-"})`).join(", ");
|
|
1235
|
+
throw new Error(`${id}: select connection; ${settings.file} offers ${choices}.`);
|
|
1236
|
+
}
|
|
1237
|
+
function selectAssemblies(id, settings, descriptor, connection) {
|
|
1238
|
+
return ["input", "output"].flatMap((direction) => {
|
|
1239
|
+
const selection = direction === "input" ? settings.inputs : settings.outputs;
|
|
1240
|
+
const instance = selection?.assembly ?? (direction === "input" ? connection?.inputAssembly : connection?.outputAssembly);
|
|
1241
|
+
if (instance === undefined) {
|
|
1242
|
+
if (selection) {
|
|
1243
|
+
throw new Error(`${id}: select its ${direction}s assembly.`);
|
|
1244
|
+
}
|
|
1245
|
+
return [];
|
|
1246
|
+
}
|
|
1247
|
+
const assembly = descriptor.assemblies.find((a) => a.instance === instance);
|
|
1248
|
+
if (!assembly) {
|
|
1249
|
+
throw new Error(`${id}: assembly ${instance} is not present in ${settings.file}.`);
|
|
1250
|
+
}
|
|
1251
|
+
const region = direction === "input" ? "I" : "Q";
|
|
1252
|
+
if (selection?.address && !selection.address.startsWith(`%${region}B`)) {
|
|
1253
|
+
throw new Error(`${id}: ${direction} assembly needs a %${region}B address.`);
|
|
1254
|
+
}
|
|
1255
|
+
const declaredSize = direction === "input" ? connection?.inputSize : connection?.outputSize;
|
|
1256
|
+
const payloadSize = selection?.size ?? declaredSize?.value ?? assembly.size;
|
|
1257
|
+
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) {
|
|
1258
|
+
throw new Error(`${id}: ${direction} payload size ${payloadSize} is outside the selected EDS connection's bounds.`);
|
|
1259
|
+
}
|
|
1145
1260
|
return [
|
|
1146
|
-
symbol,
|
|
1147
1261
|
{
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1262
|
+
id,
|
|
1263
|
+
direction,
|
|
1264
|
+
region,
|
|
1265
|
+
instance,
|
|
1266
|
+
assembly,
|
|
1267
|
+
size: payloadSize,
|
|
1268
|
+
address: selection?.address
|
|
1152
1269
|
}
|
|
1153
1270
|
];
|
|
1154
|
-
})
|
|
1155
|
-
}
|
|
1156
|
-
var timeLayouts = new Map([
|
|
1157
|
-
["TIME", "TIME"],
|
|
1158
|
-
["DATE", "DATE"],
|
|
1159
|
-
["TOD", "TIME_OF_DAY"],
|
|
1160
|
-
["TIME_OF_DAY", "TIME_OF_DAY"],
|
|
1161
|
-
["DT", "DATE_AND_TIME"],
|
|
1162
|
-
["DATE_AND_TIME", "DATE_AND_TIME"]
|
|
1163
|
-
]);
|
|
1164
|
-
function ioScalarBits(type) {
|
|
1165
|
-
const name = type.trim().toUpperCase();
|
|
1166
|
-
return timeLayouts.has(name) ? 32 : iecTypeBits[name];
|
|
1167
|
-
}
|
|
1168
|
-
function ioLayout(type) {
|
|
1169
|
-
const array = /^ARRAY\s*\[\s*(-?\d+)\s*\.\.\s*(-?\d+)\s*\]\s*OF\s+(\w+)$/i.exec(type.trim());
|
|
1170
|
-
if (array) {
|
|
1171
|
-
const element = ioLayout(array[3]);
|
|
1172
|
-
return element && element !== "BOOL" ? `${Number(array[2]) - Number(array[1]) + 1}x${element}` : undefined;
|
|
1173
|
-
}
|
|
1174
|
-
const name = type.trim().toUpperCase();
|
|
1175
|
-
if (name === "BOOL" || name === "REAL" || name === "LREAL")
|
|
1176
|
-
return name;
|
|
1177
|
-
const bits = ioScalarBits(name);
|
|
1178
|
-
return timeLayouts.get(name) ?? (bits ? `INT${bits}` : undefined);
|
|
1271
|
+
});
|
|
1179
1272
|
}
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
};
|
|
1273
|
+
|
|
1274
|
+
// packages/typegen/src/hardware.ts
|
|
1275
|
+
import { ioScalarBits as ioScalarBits3 } from "@tsplc/iec";
|
|
1276
|
+
|
|
1277
|
+
// packages/typegen/src/hardware/mapping-types.ts
|
|
1278
|
+
import { ioScalarBits as ioScalarBits2 } from "@tsplc/iec";
|
|
1187
1279
|
var directBinding = (layout) => {
|
|
1188
1280
|
const scalar = layout.replace(/^\d+x/, "");
|
|
1189
|
-
const
|
|
1190
|
-
|
|
1281
|
+
const integer = /^INT(\d+)$/.exec(scalar);
|
|
1282
|
+
const bits = integer ? Number(integer[1]) : ioScalarBits2(scalar);
|
|
1283
|
+
const size = bits === undefined ? undefined : addressSize(bits);
|
|
1284
|
+
if (!size) {
|
|
1191
1285
|
return;
|
|
1192
|
-
|
|
1286
|
+
}
|
|
1287
|
+
return size === "X" ? '{ address: `%${"I" | "Q"}X${number}.${0 | 1 | 2 | 3 | 4 | 5 | 6 | 7}`; type?: string }' : `{ address: \`%\${"I" | "Q"}${size}\${number}\`; type?: string }`;
|
|
1193
1288
|
};
|
|
1194
1289
|
function generateHardwareTypes(catalog, targets, publication, ioTypes = true) {
|
|
1195
1290
|
const selectors = publication?.map((selector) => JSON.stringify(selector)).join(" | ") ?? "string";
|
|
@@ -1197,8 +1292,9 @@ function generateHardwareTypes(catalog, targets, publication, ioTypes = true) {
|
|
|
1197
1292
|
export type PublicationSelector = ${selectors || "never"};
|
|
1198
1293
|
export type PlcPublication = { readonly production: readonly PublicationSelector[]; readonly development: readonly PublicationSelector[] };
|
|
1199
1294
|
`;
|
|
1200
|
-
if (!ioTypes)
|
|
1295
|
+
if (!ioTypes) {
|
|
1201
1296
|
return publicationTypes;
|
|
1297
|
+
}
|
|
1202
1298
|
const channel = (device, id, options) => `{ device: ${JSON.stringify(device)}; channel: ${JSON.stringify(id)}${options} }`;
|
|
1203
1299
|
const channels = catalog.devices.flatMap((device) => device.channels.filter((item) => item.address).map((item) => ({
|
|
1204
1300
|
binding: channel(device.id, item.id, item.direction === "input" && item.type === "BOOL" ? "; inverted?: boolean; shared?: boolean" : ""),
|
|
@@ -1222,48 +1318,130 @@ export type HardwareIoMapping = ${mapping};
|
|
|
1222
1318
|
export const hardware = ${JSON.stringify(catalog, null, 2)} as const;
|
|
1223
1319
|
`;
|
|
1224
1320
|
}
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
if (comment && c !== `
|
|
1232
|
-
`) {
|
|
1233
|
-
masked += " ".repeat(c.length);
|
|
1234
|
-
continue;
|
|
1321
|
+
|
|
1322
|
+
// packages/typegen/src/hardware.ts
|
|
1323
|
+
async function edsFiles(directory) {
|
|
1324
|
+
const entries = await readdir2(directory, { withFileTypes: true }).catch((cause) => {
|
|
1325
|
+
if (cause && typeof cause === "object" && "code" in cause && cause.code === "ENOENT") {
|
|
1326
|
+
return [];
|
|
1235
1327
|
}
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1328
|
+
throw cause;
|
|
1329
|
+
});
|
|
1330
|
+
const files = [];
|
|
1331
|
+
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
1332
|
+
const path = resolve(directory, entry.name);
|
|
1333
|
+
if (entry.isDirectory()) {
|
|
1334
|
+
files.push(...await edsFiles(path));
|
|
1335
|
+
} else if (entry.isFile() && /\.eds$/i.test(entry.name)) {
|
|
1336
|
+
files.push(path);
|
|
1243
1337
|
}
|
|
1244
|
-
masked += c;
|
|
1245
1338
|
}
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1339
|
+
return files;
|
|
1340
|
+
}
|
|
1341
|
+
async function readDescriptors(config, root) {
|
|
1342
|
+
const files = new Set;
|
|
1343
|
+
for (const directory of [config.eds].flat()) {
|
|
1344
|
+
for (const file of await edsFiles(resolve(root, directory))) {
|
|
1345
|
+
files.add(file);
|
|
1252
1346
|
}
|
|
1253
|
-
const start = match.index, end = start + match[0].length;
|
|
1254
|
-
const fields = readEdsRecords(`[R]
|
|
1255
|
-
${masked.slice(start, end)}`).R[match[2]];
|
|
1256
|
-
records.push({ section, key: match[2], start, end, fields });
|
|
1257
1347
|
}
|
|
1258
|
-
|
|
1348
|
+
for (const device of Object.values(config.devices)) {
|
|
1349
|
+
files.add(resolve(root, device.file));
|
|
1350
|
+
}
|
|
1351
|
+
return Promise.all([...files].map(async (file) => parseEds(await readFile2(file, "utf8"), file)));
|
|
1352
|
+
}
|
|
1353
|
+
async function loadHardware(config, root) {
|
|
1354
|
+
const descriptors = await readDescriptors(config, root);
|
|
1355
|
+
const selected = Object.entries(config.devices).map(([id, settings]) => {
|
|
1356
|
+
const descriptor = descriptors.find((d) => d.file === resolve(root, settings.file));
|
|
1357
|
+
const connection = selectConnection(id, settings, descriptor);
|
|
1358
|
+
const selections = selectAssemblies(id, settings, descriptor, connection);
|
|
1359
|
+
return { id, settings, descriptor, connection, selections };
|
|
1360
|
+
});
|
|
1361
|
+
const place = regionPlacer(selected.flatMap((device) => device.selections), { generatedTree: config.codesys?.deviceTree !== undefined });
|
|
1362
|
+
const placed = selected.map((device) => ({
|
|
1363
|
+
...device,
|
|
1364
|
+
assemblies: device.selections.map((selection) => ({
|
|
1365
|
+
...selection,
|
|
1366
|
+
address: place(selection)
|
|
1367
|
+
}))
|
|
1368
|
+
}));
|
|
1369
|
+
const devices = placed.map(({ id, settings, descriptor, connection, assemblies }) => {
|
|
1370
|
+
const registers = placeModbusRegisters(id, settings.modbus?.registers ?? {}, place);
|
|
1371
|
+
return {
|
|
1372
|
+
id,
|
|
1373
|
+
descriptor: descriptor.file,
|
|
1374
|
+
connection: connection && {
|
|
1375
|
+
id: connection.id,
|
|
1376
|
+
name: connection.name,
|
|
1377
|
+
path: connection.path
|
|
1378
|
+
},
|
|
1379
|
+
assemblies: assemblies.map(({ direction, instance, assembly, size, address }) => ({
|
|
1380
|
+
direction,
|
|
1381
|
+
instance,
|
|
1382
|
+
name: assembly.name,
|
|
1383
|
+
address,
|
|
1384
|
+
size,
|
|
1385
|
+
capacity: assembly.size
|
|
1386
|
+
})),
|
|
1387
|
+
channels: [
|
|
1388
|
+
...registers.flatMap((register) => register.channels),
|
|
1389
|
+
...assemblies.flatMap(({ direction, instance, assembly, size, address }) => assemblyChannels({
|
|
1390
|
+
device: id,
|
|
1391
|
+
direction,
|
|
1392
|
+
instance,
|
|
1393
|
+
members: assembly.members,
|
|
1394
|
+
base: byteOffset(address),
|
|
1395
|
+
payloadSize: size
|
|
1396
|
+
}))
|
|
1397
|
+
],
|
|
1398
|
+
statusSymbols: settings.statusSymbols ?? {},
|
|
1399
|
+
...settings.modbus && {
|
|
1400
|
+
modbus: {
|
|
1401
|
+
port: settings.modbus.port,
|
|
1402
|
+
registers: registers.map(({ register }) => register)
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
};
|
|
1406
|
+
});
|
|
1407
|
+
return { descriptors, devices };
|
|
1408
|
+
}
|
|
1409
|
+
function resolveIo(config, catalog) {
|
|
1410
|
+
return Object.fromEntries(Object.entries(config.io).map(([symbol, binding]) => {
|
|
1411
|
+
if ("address" in binding) {
|
|
1412
|
+
return [symbol, binding];
|
|
1413
|
+
}
|
|
1414
|
+
const device = catalog.devices.find((d) => d.id === binding.device);
|
|
1415
|
+
const channel = device?.channels.find((c) => c.id === binding.channel);
|
|
1416
|
+
if (!channel?.address) {
|
|
1417
|
+
throw new Error(`${symbol}: unknown or unaddressable channel ${binding.device}.${binding.channel}.`);
|
|
1418
|
+
}
|
|
1419
|
+
return [
|
|
1420
|
+
symbol,
|
|
1421
|
+
{
|
|
1422
|
+
address: channel.address,
|
|
1423
|
+
type: channel.type,
|
|
1424
|
+
...binding.inverted && { inverted: true },
|
|
1425
|
+
...binding.shared && { shared: true }
|
|
1426
|
+
}
|
|
1427
|
+
];
|
|
1428
|
+
}));
|
|
1259
1429
|
}
|
|
1430
|
+
|
|
1431
|
+
// packages/typegen/src/index.ts
|
|
1432
|
+
import { ioScalarBits as ioScalarBits4 } from "@tsplc/iec";
|
|
1433
|
+
|
|
1434
|
+
// packages/typegen/src/device-tree.ts
|
|
1435
|
+
import { readFile as readFile3 } from "node:fs/promises";
|
|
1436
|
+
import { iecName } from "@tsplc/config/build";
|
|
1260
1437
|
var quoted = (value) => `"${value.replaceAll('"', '""')}"`;
|
|
1261
1438
|
function normalizeEds(text, selection) {
|
|
1262
|
-
const
|
|
1263
|
-
const connections =
|
|
1264
|
-
const selected = connections.find((
|
|
1265
|
-
if (!selected)
|
|
1439
|
+
const sections = edsSections(text);
|
|
1440
|
+
const connections = [...sections.get("Connection Manager") ?? []].filter(([key]) => /^Connection\d+$/.test(key));
|
|
1441
|
+
const selected = connections.find(([key]) => key === selection.connection)?.[1];
|
|
1442
|
+
if (!selected) {
|
|
1266
1443
|
throw new Error(`EDS has no ${selection.connection}.`);
|
|
1444
|
+
}
|
|
1267
1445
|
const fields = [...selected.fields];
|
|
1268
1446
|
const resized = new Map;
|
|
1269
1447
|
for (const [sizeField, formatField, size] of [
|
|
@@ -1271,70 +1449,91 @@ function normalizeEds(text, selection) {
|
|
|
1271
1449
|
[6, 7, selection.inputSize]
|
|
1272
1450
|
]) {
|
|
1273
1451
|
const assembly = fields[formatField];
|
|
1274
|
-
if (!assembly)
|
|
1452
|
+
if (!assembly) {
|
|
1275
1453
|
continue;
|
|
1276
|
-
|
|
1454
|
+
}
|
|
1455
|
+
if (size === undefined) {
|
|
1277
1456
|
throw new Error(`Select a payload size for ${assembly}.`);
|
|
1457
|
+
}
|
|
1278
1458
|
fields[sizeField] = String(size);
|
|
1279
1459
|
resized.set(assembly, size);
|
|
1280
1460
|
}
|
|
1281
|
-
const edits = []
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
}
|
|
1286
|
-
for (const record of
|
|
1287
|
-
const size =
|
|
1288
|
-
if (size === undefined)
|
|
1461
|
+
const edits = connections.map(([, record]) => ({
|
|
1462
|
+
start: record.start,
|
|
1463
|
+
end: record.end,
|
|
1464
|
+
text: record === selected ? `Connection1 = ${fields.map((value, index) => index >= 12 ? quoted(value) : value).join(",")};` : ""
|
|
1465
|
+
}));
|
|
1466
|
+
for (const [key, record] of sections.get("Assembly") ?? []) {
|
|
1467
|
+
const size = resized.get(key);
|
|
1468
|
+
if (size === undefined) {
|
|
1289
1469
|
continue;
|
|
1470
|
+
}
|
|
1290
1471
|
const [name = "", path = "", , descriptor = ""] = record.fields;
|
|
1291
|
-
const
|
|
1472
|
+
const rawBytes = [
|
|
1473
|
+
quoted(name),
|
|
1474
|
+
path && quoted(path),
|
|
1475
|
+
size,
|
|
1476
|
+
descriptor,
|
|
1477
|
+
"",
|
|
1478
|
+
"",
|
|
1479
|
+
size * 8,
|
|
1480
|
+
""
|
|
1481
|
+
];
|
|
1292
1482
|
edits.push({
|
|
1293
1483
|
start: record.start,
|
|
1294
1484
|
end: record.end,
|
|
1295
|
-
text: `${
|
|
1485
|
+
text: `${key} = ${rawBytes.join(",")};`
|
|
1296
1486
|
});
|
|
1297
|
-
resized.delete(
|
|
1487
|
+
resized.delete(key);
|
|
1298
1488
|
}
|
|
1299
|
-
if (resized.size)
|
|
1489
|
+
if (resized.size) {
|
|
1300
1490
|
throw new Error(`EDS has no ${[...resized.keys()].join(", ")} assembly.`);
|
|
1491
|
+
}
|
|
1301
1492
|
return edits.sort((a, b) => b.start - a.start).reduce((result, edit) => result.slice(0, edit.start) + edit.text + result.slice(edit.end), text);
|
|
1302
1493
|
}
|
|
1303
1494
|
async function deviceTree(config, catalog) {
|
|
1304
1495
|
const settings = config.codesys?.deviceTree;
|
|
1305
|
-
if (!settings)
|
|
1496
|
+
if (!settings) {
|
|
1306
1497
|
return;
|
|
1498
|
+
}
|
|
1307
1499
|
const devices = await Promise.all(catalog.devices.map(async (device) => {
|
|
1308
|
-
if (
|
|
1500
|
+
if (!iecName.safeParse(device.id).success) {
|
|
1309
1501
|
throw new Error(`${device.id}: a device tree adapter needs an IEC identifier name.`);
|
|
1310
|
-
|
|
1311
|
-
const connection =
|
|
1312
|
-
if (!connection)
|
|
1502
|
+
}
|
|
1503
|
+
const connection = device.connection;
|
|
1504
|
+
if (!connection) {
|
|
1313
1505
|
throw new Error(`${device.id}: select the connection to configure.`);
|
|
1506
|
+
}
|
|
1314
1507
|
const region = (direction) => {
|
|
1315
1508
|
const assembly = device.assemblies.find((item) => item.direction === direction);
|
|
1316
1509
|
return assembly && { address: assembly.address, size: assembly.size };
|
|
1317
1510
|
};
|
|
1318
|
-
const inputs = region("input")
|
|
1511
|
+
const inputs = region("input");
|
|
1512
|
+
const outputs = region("output");
|
|
1319
1513
|
const comments = Object.entries(config.io).flatMap(([key, binding]) => {
|
|
1320
|
-
if (!("device" in binding) || binding.device !== device.id)
|
|
1514
|
+
if (!("device" in binding) || binding.device !== device.id) {
|
|
1321
1515
|
return [];
|
|
1516
|
+
}
|
|
1322
1517
|
const channel = device.channels.find((item) => item.id === binding.channel);
|
|
1323
|
-
if (channel.assembly === undefined)
|
|
1518
|
+
if (channel.assembly === undefined) {
|
|
1324
1519
|
return [];
|
|
1325
|
-
|
|
1520
|
+
}
|
|
1521
|
+
if (channel.bits === 1) {
|
|
1326
1522
|
return [{ address: channel.address, text: key }];
|
|
1327
|
-
|
|
1523
|
+
}
|
|
1524
|
+
const area = channel.direction === "input" ? inputs : outputs;
|
|
1525
|
+
const bytes = channel.bits / 8;
|
|
1328
1526
|
return [
|
|
1329
1527
|
{
|
|
1330
|
-
address: `${area.address.slice(0, 3)}${
|
|
1528
|
+
address: `${area.address.slice(0, 3)}${byteOffset(area.address) + channel.offsetBits / 8}`,
|
|
1331
1529
|
text: bytes > 1 ? `${key} (${bytes} bytes)` : key
|
|
1332
1530
|
}
|
|
1333
1531
|
];
|
|
1334
1532
|
});
|
|
1335
1533
|
const network = config.devices[device.id]?.network;
|
|
1336
|
-
if (device.modbus && !network?.address)
|
|
1534
|
+
if (device.modbus && !network?.address) {
|
|
1337
1535
|
throw new Error(`${device.id}: Modbus registers need its network address.`);
|
|
1536
|
+
}
|
|
1338
1537
|
return {
|
|
1339
1538
|
name: device.id,
|
|
1340
1539
|
eds: normalizeEds(await readFile3(device.descriptor, "utf8"), {
|
|
@@ -1343,16 +1542,20 @@ async function deviceTree(config, catalog) {
|
|
|
1343
1542
|
outputSize: outputs?.size
|
|
1344
1543
|
}),
|
|
1345
1544
|
...network?.address && { address: network.address },
|
|
1346
|
-
...network?.rpi && {
|
|
1545
|
+
...network?.rpi && {
|
|
1546
|
+
rpiMicroseconds: Number(BigInt(network.rpi.nanoseconds) / 1000n)
|
|
1547
|
+
},
|
|
1347
1548
|
...inputs && { inputs },
|
|
1348
1549
|
...outputs && { outputs },
|
|
1349
1550
|
...device.modbus && { modbus: device.modbus },
|
|
1350
1551
|
comments
|
|
1351
1552
|
};
|
|
1352
1553
|
}));
|
|
1353
|
-
|
|
1554
|
+
const [first, ...rest] = devices;
|
|
1555
|
+
if (!first) {
|
|
1354
1556
|
throw new Error("A generated device tree needs at least one device.");
|
|
1355
|
-
|
|
1557
|
+
}
|
|
1558
|
+
return { ethernet: settings.ethernet ?? {}, devices: [first, ...rest] };
|
|
1356
1559
|
}
|
|
1357
1560
|
// packages/typegen/src/project.ts
|
|
1358
1561
|
import { mkdir, readFile as readFile4, rename, writeFile } from "node:fs/promises";
|
|
@@ -1363,55 +1566,112 @@ import {
|
|
|
1363
1566
|
publicationSchema,
|
|
1364
1567
|
typegenSchema
|
|
1365
1568
|
} from "@tsplc/config";
|
|
1569
|
+
import { blockCommentEnd as blockCommentEnd2, lineCommentEnd as lineCommentEnd2 } from "@tsplc/iec/st";
|
|
1570
|
+
var emittedSt = ".tsplc/artifacts/st";
|
|
1571
|
+
var formatTypeScript = (source) => format(source, { parser: "typescript" });
|
|
1572
|
+
var readPublication = async (root) => publicationSchema.parse(JSON.parse(await readFile4(resolve2(root, emittedSt, "publication.json"), "utf8")));
|
|
1366
1573
|
async function contractSources(config, root, settings) {
|
|
1367
1574
|
const directories = (setting) => setting ? [setting].flat().map((path) => resolve2(root, path)) : [];
|
|
1368
|
-
const types = directories(settings.types)
|
|
1575
|
+
const types = directories(settings.types);
|
|
1576
|
+
const globals = directories(settings.globals);
|
|
1369
1577
|
if (types.length || globals.length) {
|
|
1370
|
-
const sources = {
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
if (!sources.types.length && !sources.globals.length)
|
|
1578
|
+
const sources = {
|
|
1579
|
+
types: await filesIn(types),
|
|
1580
|
+
globals: await filesIn(globals),
|
|
1581
|
+
explicit: true
|
|
1582
|
+
};
|
|
1583
|
+
if (!sources.types.length && !sources.globals.length) {
|
|
1376
1584
|
throw new Error("no .st declarations found in the configured typegen directories");
|
|
1585
|
+
}
|
|
1377
1586
|
return sources;
|
|
1378
1587
|
}
|
|
1379
|
-
const source = config.compiler ?
|
|
1588
|
+
const source = config.compiler ? emittedSt : config.build?.sourceDir;
|
|
1380
1589
|
if (!source) {
|
|
1381
|
-
if (config.typegen)
|
|
1590
|
+
if (config.typegen) {
|
|
1382
1591
|
throw new Error("Configure build.sourceDir or typegen.types/globals to generate PLC types.");
|
|
1592
|
+
}
|
|
1383
1593
|
return;
|
|
1384
1594
|
}
|
|
1385
1595
|
const sourceRoot = resolve2(root, source);
|
|
1386
1596
|
const files = await stFiles(sourceRoot);
|
|
1387
|
-
if (!files.length)
|
|
1597
|
+
if (!files.length) {
|
|
1388
1598
|
throw new Error(`no .st declarations found in ${sourceRoot}`);
|
|
1599
|
+
}
|
|
1389
1600
|
const sources = { types: [], globals: [], explicit: false };
|
|
1390
1601
|
for (const file of files) {
|
|
1391
|
-
const
|
|
1392
|
-
|
|
1602
|
+
const text = await readFile4(file, "utf8");
|
|
1603
|
+
const code = text.slice(codeStart(text, 0));
|
|
1604
|
+
if (/^TYPE\b/i.test(code)) {
|
|
1393
1605
|
sources.types.push(file);
|
|
1394
|
-
else if (/^VAR_GLOBAL\b/i.test(
|
|
1606
|
+
} else if (/^VAR_GLOBAL\b/i.test(code)) {
|
|
1395
1607
|
sources.globals.push(file);
|
|
1608
|
+
}
|
|
1396
1609
|
}
|
|
1397
1610
|
return sources;
|
|
1398
1611
|
}
|
|
1612
|
+
function codeStart(text, offset) {
|
|
1613
|
+
const start = offset + text.slice(offset).search(/\S|$/);
|
|
1614
|
+
if (text.startsWith("(*", start)) {
|
|
1615
|
+
const end = blockCommentEnd2(text, start);
|
|
1616
|
+
return end === null ? start : codeStart(text, end);
|
|
1617
|
+
}
|
|
1618
|
+
if (text.startsWith("//", start)) {
|
|
1619
|
+
return codeStart(text, lineCommentEnd2(text, start));
|
|
1620
|
+
}
|
|
1621
|
+
if (text.startsWith("{", start)) {
|
|
1622
|
+
const end = text.indexOf("}", start);
|
|
1623
|
+
return end < 0 ? start : codeStart(text, end + 1);
|
|
1624
|
+
}
|
|
1625
|
+
return start;
|
|
1626
|
+
}
|
|
1627
|
+
async function filesIn(directories) {
|
|
1628
|
+
const files = [];
|
|
1629
|
+
for (const directory of directories) {
|
|
1630
|
+
files.push(...await stFiles(directory));
|
|
1631
|
+
}
|
|
1632
|
+
return files;
|
|
1633
|
+
}
|
|
1634
|
+
function checkHmiTargets(controls, published) {
|
|
1635
|
+
for (const { target } of controls) {
|
|
1636
|
+
if (!published.some((symbol) => target === symbol || target.startsWith(`${symbol}.`) || target.startsWith(`${symbol}[`))) {
|
|
1637
|
+
throw new Error(`HMI control ${target} is not in the production publication.`);
|
|
1638
|
+
}
|
|
1639
|
+
}
|
|
1640
|
+
}
|
|
1641
|
+
async function writeOutputs(outputs) {
|
|
1642
|
+
for (const output of outputs) {
|
|
1643
|
+
await mkdir(dirname(output.path), { recursive: true });
|
|
1644
|
+
const temp = `${output.path}.${process.pid}.tmp`;
|
|
1645
|
+
await writeFile(temp, output.content);
|
|
1646
|
+
await rename(temp, output.path);
|
|
1647
|
+
}
|
|
1648
|
+
}
|
|
1649
|
+
async function checkOutputs(outputs) {
|
|
1650
|
+
for (const output of outputs) {
|
|
1651
|
+
const actual = await readFile4(output.path, "utf8").catch(() => {
|
|
1652
|
+
return;
|
|
1653
|
+
});
|
|
1654
|
+
const normalized = actual !== undefined && /\.ts$/i.test(output.path) ? await formatTypeScript(actual) : actual;
|
|
1655
|
+
if (normalized !== output.content) {
|
|
1656
|
+
throw new Error(`Generated file is missing or stale: ${output.path}`);
|
|
1657
|
+
}
|
|
1658
|
+
}
|
|
1659
|
+
}
|
|
1399
1660
|
async function generateProject(file = "tsplc.config.ts", options = {}) {
|
|
1400
1661
|
const { config, root, configFile } = options.loaded ?? await loadTsplcConfig(file);
|
|
1401
1662
|
const settings = typegenSchema.parse(config.typegen ?? {});
|
|
1402
|
-
const catalog = await loadHardware(config, root)
|
|
1663
|
+
const catalog = await loadHardware(config, root);
|
|
1664
|
+
const io = resolveIo(config, catalog);
|
|
1403
1665
|
const project = {
|
|
1404
1666
|
version: 1,
|
|
1405
1667
|
configFile,
|
|
1406
1668
|
config,
|
|
1407
|
-
symbols: config.compiler ? JSON.parse(await readFile4(resolve2(root, "
|
|
1669
|
+
symbols: config.compiler ? JSON.parse(await readFile4(resolve2(root, emittedSt, "io-symbols.json"), "utf8").catch(() => "{}")) : Object.fromEntries(Object.keys(io).filter((symbol) => symbol.includes(".")).map((symbol) => [symbol, symbol]))
|
|
1408
1670
|
};
|
|
1409
1671
|
const outputs = [
|
|
1410
1672
|
{
|
|
1411
1673
|
path: resolve2(root, settings.dir, "hardware.ts"),
|
|
1412
|
-
content: await
|
|
1413
|
-
parser: "typescript"
|
|
1414
|
-
})
|
|
1674
|
+
content: await formatTypeScript(generateHardwareTypes(catalog, options.targets?.io, options.targets?.publication, settings.ioTypes))
|
|
1415
1675
|
},
|
|
1416
1676
|
{
|
|
1417
1677
|
path: resolve2(root, ".tsplc/project.json"),
|
|
@@ -1420,49 +1680,35 @@ async function generateProject(file = "tsplc.config.ts", options = {}) {
|
|
|
1420
1680
|
}
|
|
1421
1681
|
];
|
|
1422
1682
|
const sources = options.hardwareOnly ? undefined : await contractSources(config, root, settings);
|
|
1423
|
-
if (sources)
|
|
1683
|
+
if (sources) {
|
|
1684
|
+
const inferred = !!config.compiler && !sources.explicit;
|
|
1424
1685
|
outputs.push({
|
|
1425
1686
|
path: resolve2(root, settings.dir, "plc.ts"),
|
|
1426
|
-
content: await
|
|
1687
|
+
content: await formatTypeScript(await generateTypes({
|
|
1427
1688
|
types: sources.types,
|
|
1428
1689
|
globals: sources.globals,
|
|
1429
|
-
publishedGlobalsOnly:
|
|
1690
|
+
publishedGlobalsOnly: inferred,
|
|
1430
1691
|
declarations: settings.declarations,
|
|
1431
|
-
publication:
|
|
1432
|
-
})
|
|
1692
|
+
publication: inferred ? await readPublication(root) : undefined
|
|
1693
|
+
}))
|
|
1433
1694
|
});
|
|
1695
|
+
}
|
|
1434
1696
|
if (config.hmi && config.publish && config.compiler && !options.hardwareOnly) {
|
|
1435
|
-
|
|
1436
|
-
for (const { target } of config.hmi.controls)
|
|
1437
|
-
if (!published.some((symbol) => target === symbol || target.startsWith(`${symbol}.`) || target.startsWith(`${symbol}[`)))
|
|
1438
|
-
throw new Error(`HMI control ${target} is not in the production publication.`);
|
|
1697
|
+
checkHmiTargets(config.hmi.controls, (await readPublication(root)).production);
|
|
1439
1698
|
}
|
|
1440
1699
|
if (config.compiler && !options.hardwareOnly) {
|
|
1441
|
-
const machine = await readFile4(resolve2(root, "
|
|
1700
|
+
const machine = await readFile4(resolve2(root, emittedSt, "machines.ts"), "utf8").catch(() => {
|
|
1442
1701
|
return;
|
|
1443
1702
|
});
|
|
1444
|
-
if (machine)
|
|
1703
|
+
if (machine) {
|
|
1445
1704
|
outputs.push({
|
|
1446
1705
|
path: resolve2(root, settings.dir, "machines.ts"),
|
|
1447
|
-
content: await
|
|
1448
|
-
});
|
|
1449
|
-
}
|
|
1450
|
-
for (const output of outputs) {
|
|
1451
|
-
if (options.check) {
|
|
1452
|
-
const actual = await readFile4(output.path, "utf8").catch(() => {
|
|
1453
|
-
return;
|
|
1706
|
+
content: await formatTypeScript(machine)
|
|
1454
1707
|
});
|
|
1455
|
-
const normalized = actual !== undefined && /\.ts$/i.test(output.path) ? await format(actual, { parser: "typescript" }) : actual;
|
|
1456
|
-
if (normalized !== output.content)
|
|
1457
|
-
throw new Error(`Generated file is missing or stale: ${output.path}`);
|
|
1458
|
-
} else {
|
|
1459
|
-
await mkdir(dirname(output.path), { recursive: true });
|
|
1460
|
-
const temp = `${output.path}.${process.pid}.tmp`;
|
|
1461
|
-
await writeFile(temp, output.content);
|
|
1462
|
-
await rename(temp, output.path);
|
|
1463
1708
|
}
|
|
1464
1709
|
}
|
|
1465
|
-
|
|
1710
|
+
await (options.check ? checkOutputs(outputs) : writeOutputs(outputs));
|
|
1711
|
+
return { catalog, io, files: outputs.map((output) => output.path) };
|
|
1466
1712
|
}
|
|
1467
1713
|
export {
|
|
1468
1714
|
deviceTree,
|
|
@@ -1470,7 +1716,7 @@ export {
|
|
|
1470
1716
|
generateProject,
|
|
1471
1717
|
generateTypes,
|
|
1472
1718
|
ioLayout,
|
|
1473
|
-
ioScalarBits,
|
|
1719
|
+
ioScalarBits4 as ioScalarBits,
|
|
1474
1720
|
loadHardware,
|
|
1475
1721
|
normalizeEds,
|
|
1476
1722
|
parseEds,
|
|
@@ -1478,5 +1724,5 @@ export {
|
|
|
1478
1724
|
resolveIo
|
|
1479
1725
|
};
|
|
1480
1726
|
|
|
1481
|
-
//# debugId=
|
|
1727
|
+
//# debugId=0A50DD1C1E5BA48A64756E2164756E21
|
|
1482
1728
|
//# sourceMappingURL=index.js.map
|