@tsplc/build 0.5.8 → 0.5.9

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.
@@ -0,0 +1,207 @@
1
+ import type { CyclicTask } from "@tsplc/config/build";
2
+ import { elementaryType } from "@tsplc/iec";
3
+ import { z } from "zod";
4
+ import { type StoredVariable, storedVariables } from "./st/declarations";
5
+ import { StSyntaxError } from "./st/lexer";
6
+
7
+ /** An object as the sources load it and the committed baseline keeps it; other fields pass through. */
8
+ export interface CommittedObject {
9
+ kind: string;
10
+ name: string;
11
+ declaration: string;
12
+ children?: CommittedObject[];
13
+ }
14
+ export const committedObjectSchema: z.ZodType<CommittedObject> = z.lazy(() =>
15
+ z.looseObject({
16
+ kind: z.string(),
17
+ name: z.string(),
18
+ declaration: z.string(),
19
+ children: z.array(committedObjectSchema).optional(),
20
+ }),
21
+ );
22
+
23
+ /**
24
+ * What the check found about an online change from the committed download to these sources. A
25
+ * refusal is what CODESYS would refuse or apply wrongly, so the deploy offers a download before
26
+ * CODESYS runs; anything else is a warning about state the change restarts.
27
+ */
28
+ export interface OnlineChangeFinding {
29
+ kind: "type" | "tasks" | "restart";
30
+ refuses: boolean;
31
+ object: string;
32
+ variable: string | null;
33
+ before: string | null;
34
+ after: string | null;
35
+ advice: string;
36
+ }
37
+
38
+ /** Objects whose variables keep their values across scans; a routine's own variables don't. */
39
+ const keepsState = (kind: string) =>
40
+ ["program", "function_block", "gvl", "dut"].includes(kind);
41
+
42
+ const compact = (type: string) => type.replace(/\s+/g, "").toUpperCase();
43
+
44
+ /** The type an array, pointer or string is made of: what CODESYS compares across a change. */
45
+ const base = (type: string): string => {
46
+ const prefix = /^(ARRAY\[[^\]]*\]OF|POINTERTO|REFERENCETO|REF_TO)/.exec(type);
47
+ if (prefix) {
48
+ return base(type.slice(prefix[0].length));
49
+ }
50
+ return type.replace(/^(W?STRING)[([].*$/, "$1");
51
+ };
52
+
53
+ const userDefined = (type: string) =>
54
+ !elementaryType(type) && type !== "STRING" && type !== "WSTRING";
55
+
56
+ /** How CODESYS takes a stored variable's type change: refused, converted, or a new layout. */
57
+ const typeChange = (before: string, after: string) => {
58
+ const [from, to] = [compact(before), compact(after)];
59
+ if (from === to || base(from) === base(to)) {
60
+ return undefined;
61
+ }
62
+ return userDefined(base(from)) || userDefined(base(to))
63
+ ? "refused"
64
+ : "converted";
65
+ };
66
+
67
+ const flatten = (objects: readonly CommittedObject[]): CommittedObject[] =>
68
+ objects.flatMap((object) => [object, ...flatten(object.children ?? [])]);
69
+
70
+ /** An object's stored variables by name; undefined for a declaration the reader can't follow. */
71
+ const variablesOf = (
72
+ object: CommittedObject,
73
+ ): Map<string, StoredVariable> | undefined => {
74
+ try {
75
+ return new Map(
76
+ storedVariables(object.declaration, object.name).map((variable) => [
77
+ variable.name.toLowerCase(),
78
+ variable,
79
+ ]),
80
+ );
81
+ } catch (error) {
82
+ if (error instanceof StSyntaxError) {
83
+ return undefined;
84
+ }
85
+ throw error;
86
+ }
87
+ };
88
+
89
+ /**
90
+ * Compares the stored variables of every object the committed download and the sources share, and
91
+ * the task plans, as CODESYS will. It finds a subset of what CODESYS refuses, never more, and says
92
+ * which variable or task is the cause and how to avoid it.
93
+ */
94
+ export const onlineChangeFindings = ({
95
+ before,
96
+ after,
97
+ tasks,
98
+ }: {
99
+ before: readonly CommittedObject[];
100
+ after: readonly CommittedObject[];
101
+ tasks: {
102
+ before: readonly CyclicTask[] | null;
103
+ after: readonly CyclicTask[] | null;
104
+ };
105
+ }): OnlineChangeFinding[] => {
106
+ const findings: OnlineChangeFinding[] = [];
107
+ if (
108
+ tasks.before &&
109
+ tasks.after &&
110
+ JSON.stringify(tasks.before) !== JSON.stringify(tasks.after)
111
+ ) {
112
+ findings.push({
113
+ kind: "tasks",
114
+ refuses: true,
115
+ object: "Task configuration",
116
+ variable: null,
117
+ before: JSON.stringify(tasks.before.map((task) => task.name)),
118
+ after: JSON.stringify(tasks.after.map((task) => task.name)),
119
+ advice:
120
+ "CODESYS can't change tasks online: a new task, interval, priority or configured program needs a download.",
121
+ });
122
+ }
123
+ const current = new Map(
124
+ flatten(after)
125
+ .filter((object) => keepsState(object.kind))
126
+ .map((object) => [object.name.toLowerCase(), object]),
127
+ );
128
+ for (const object of flatten(before).filter((item) =>
129
+ keepsState(item.kind),
130
+ )) {
131
+ const now = current.get(object.name.toLowerCase());
132
+ const old = variablesOf(object);
133
+ if (!old) {
134
+ continue;
135
+ }
136
+ if (!now) {
137
+ if (old.size) {
138
+ findings.push({
139
+ kind: "restart",
140
+ refuses: false,
141
+ object: object.name,
142
+ variable: null,
143
+ before: null,
144
+ after: null,
145
+ advice: `${object.name} is gone, so the values it held are dropped.`,
146
+ });
147
+ }
148
+ continue;
149
+ }
150
+ const updated = variablesOf(now);
151
+ if (!updated) {
152
+ continue;
153
+ }
154
+ for (const [key, variable] of old) {
155
+ const next = updated.get(key);
156
+ if (!next) {
157
+ findings.push({
158
+ kind: "restart",
159
+ refuses: false,
160
+ object: object.name,
161
+ variable: variable.name,
162
+ before: variable.type,
163
+ after: null,
164
+ advice: `${object.name}.${variable.name} is renamed or removed, so its value is dropped.`,
165
+ });
166
+ continue;
167
+ }
168
+ const change = typeChange(variable.type, next.type);
169
+ if (change === "refused") {
170
+ findings.push({
171
+ kind: "type",
172
+ refuses: true,
173
+ object: object.name,
174
+ variable: variable.name,
175
+ before: variable.type,
176
+ after: next.type,
177
+ advice:
178
+ "CODESYS refuses an online change that gives a variable another user-defined type; rename the variable so it starts afresh, or download.",
179
+ });
180
+ }
181
+ if (change === "converted") {
182
+ findings.push({
183
+ kind: "restart",
184
+ refuses: false,
185
+ object: object.name,
186
+ variable: variable.name,
187
+ before: variable.type,
188
+ after: next.type,
189
+ advice: `CODESYS converts ${object.name}.${variable.name} to its new type or resets it.`,
190
+ });
191
+ }
192
+ }
193
+ }
194
+ return findings;
195
+ };
196
+
197
+ /** One line for a finding, as the deploy reports it. */
198
+ export const describeFinding = (finding: OnlineChangeFinding) => {
199
+ const where = finding.variable
200
+ ? `${finding.object}.${finding.variable}`
201
+ : finding.object;
202
+ const change =
203
+ finding.before !== null && finding.after !== null
204
+ ? ` (${finding.before} → ${finding.after})`
205
+ : "";
206
+ return `${where}${change}: ${finding.advice}`;
207
+ };
@@ -2,10 +2,11 @@ import {
2
2
  conditionalDirective,
3
3
  modifiers,
4
4
  type ObjectKeyword,
5
+ qualifiers,
5
6
  variableSections,
6
7
  } from "@tsplc/iec/st";
7
8
  import type { Token } from "./lexer";
8
- import type { TokenReader } from "./reader";
9
+ import { createTokenReader, type TokenReader } from "./reader";
9
10
 
10
11
  export const objectKinds = {
11
12
  PROGRAM: "program",
@@ -215,3 +216,108 @@ export const readDeclarationSections = (reader: TokenReader) => {
215
216
  }
216
217
  }
217
218
  };
219
+
220
+ /** A variable an object keeps across scans, as an online change finds it. */
221
+ export interface StoredVariable {
222
+ /** The variable section, or `STRUCT` for a member of a structure. */
223
+ section: string;
224
+ name: string;
225
+ /** The type as declared. */
226
+ type: string;
227
+ /** The names of the attribute pragmas on its declaration. */
228
+ attributes: string[];
229
+ }
230
+
231
+ /** Sections whose variables keep their values from one scan to the next. */
232
+ const keptSections = new Set([
233
+ "VAR",
234
+ "VAR_INPUT",
235
+ "VAR_OUTPUT",
236
+ "VAR_IN_OUT",
237
+ "VAR_STAT",
238
+ "VAR_INST",
239
+ "VAR_GLOBAL",
240
+ ]);
241
+
242
+ const attributeName = (pragma: string) =>
243
+ /^\{\s*attribute\s+'([^']+)'/i.exec(pragma)?.[1];
244
+
245
+ /** Skips an initializer up to its declaration's `;`, past any nested brackets. */
246
+ const skipToSemicolon = (reader: TokenReader) => {
247
+ const closings: string[] = [];
248
+ while (reader.peek()) {
249
+ const token = reader.take();
250
+ if (token.value === "(" || token.value === "[") {
251
+ closings.push(token.value === "(" ? ")" : "]");
252
+ } else if (token.value === closings.at(-1)) {
253
+ closings.pop();
254
+ } else if (token.value === ";" && !closings.length) {
255
+ return;
256
+ }
257
+ }
258
+ };
259
+
260
+ /** The declarations up to `end`: names, then `AT` and an address, then the type and an initializer. */
261
+ const readMembers = (
262
+ reader: TokenReader,
263
+ end: string,
264
+ section: string,
265
+ found: StoredVariable[] | null,
266
+ ) => {
267
+ while (reader.peek() && reader.peek()?.value !== end) {
268
+ const attributes: string[] = [];
269
+ while (reader.peek()?.kind === "pragma") {
270
+ const name = attributeName(reader.take().value);
271
+ if (name) {
272
+ attributes.push(name);
273
+ }
274
+ }
275
+ if (!reader.peek() || reader.peek()?.value === end) {
276
+ break;
277
+ }
278
+ const names = [readIdentifier(reader)];
279
+ while (reader.consume(",")) {
280
+ names.push(readIdentifier(reader));
281
+ }
282
+ if (reader.consume("AT")) {
283
+ reader.take();
284
+ }
285
+ reader.expect(":");
286
+ const type = readType(reader);
287
+ skipToSemicolon(reader);
288
+ for (const name of names) {
289
+ found?.push({ section, name, type, attributes });
290
+ }
291
+ }
292
+ reader.consume(end);
293
+ };
294
+
295
+ /**
296
+ * The variables a declaration keeps across scans: its variable sections other than constants and
297
+ * temporaries, and a structure's members. It reads past anything else, so an object it can't
298
+ * classify yields nothing; whoever compares two of them leaves that to CODESYS.
299
+ */
300
+ export const storedVariables = (
301
+ declaration: string,
302
+ filename: string,
303
+ ): StoredVariable[] => {
304
+ const reader = createTokenReader(declaration, filename);
305
+ const found: StoredVariable[] = [];
306
+ while (reader.peek()) {
307
+ const token = reader.take();
308
+ if (token.value === "STRUCT") {
309
+ readMembers(reader, "END_STRUCT", "STRUCT", found);
310
+ continue;
311
+ }
312
+ if (!variableSections.has(token.value)) {
313
+ continue;
314
+ }
315
+ const written: string[] = [];
316
+ while (qualifiers.has(reader.peek()?.value ?? "")) {
317
+ written.push(reader.take().value);
318
+ }
319
+ const kept = keptSections.has(token.value) && !written.includes("CONSTANT");
320
+ readMembers(reader, "END_VAR", token.value, kept ? found : null);
321
+ }
322
+ return found;
323
+ };