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