@tsplc/compiler 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.
package/dist/codesys.js CHANGED
@@ -17,58 +17,14 @@ import {
17
17
  } from "@tsplc/build";
18
18
  import { engineeringBuildSchema, resolveConfig } from "@tsplc/config/build";
19
19
  import { z } from "zod";
20
- var engineeringSchema = z.strictObject({
21
- kind: z.literal("v3.5"),
22
- build: engineeringBuildSchema.optional()
23
- });
24
- function codesysBuildConfig(plan, bundle, paths) {
25
- const settings = plan.options.engineering.build;
26
- if (!settings) {
27
- throw new Error("CODESYS build requires engineering.build settings (codesys installation and template). Configure them or use --emit-only.");
28
- }
29
- const programs = new Map(plan.core.programs.map((program) => {
30
- const matches = bundle.objects.filter((object) => object.id === program.id && object.kind === "program");
31
- const generated = matches[0];
32
- if (matches.length !== 1 || !generated) {
33
- throw new Error(`Generated bundle must contain one PROGRAM object for ${program.name}.`);
34
- }
35
- return [program.name, generated];
36
- }));
37
- const tasks = plan.deployment.tasks.map((task) => ({
38
- ...task,
39
- programs: task.programs.map((name) => {
40
- const program = programs.get(name);
41
- if (!program) {
42
- throw new Error(`Task ${task.name} references a missing generated PROGRAM ${name}.`);
43
- }
44
- return program.name;
45
- })
46
- }));
47
- const first = plan.core.programs[0];
48
- const entry = first && programs.get(first.name);
49
- if (!entry) {
50
- throw new Error("CODESYS build requires a generated PROGRAM entry.");
51
- }
52
- const sourceDir = resolve(paths.sourceDir);
53
- return resolveConfig({
54
- ...settings,
55
- libraryReferences: [
56
- ...settings.libraryReferences ?? [],
57
- ...Object.values(plan.http).some((endpoint) => endpoint.transport !== "opcua") ? ["Net Base Services, 4.0.0.0 (CODESYS)"] : [],
58
- ...Object.values(plan.http).some((endpoint) => endpoint.tls) ? ["CmpX509Cert Implementation, 3.5.22.0 (System)"] : []
59
- ],
60
- ...paths.libraries ? { libraries: paths.libraries } : {},
61
- ...paths.deviceTree ? { deviceTree: paths.deviceTree } : {},
62
- ...paths.controller ? { controller: paths.controller } : {},
63
- sourceDir,
64
- entry: resolve(sourceDir, entry.sourcePath ?? `${entry.name}/declaration.st`),
65
- outDir: resolve(paths.outDir),
66
- tasks
67
- }, paths.configFile);
68
- }
69
- async function buildCodesys(plan, bundle, paths, options = {}) {
70
- return buildProject(codesysBuildConfig(plan, bundle, paths), options);
71
- }
20
+
21
+ // packages/compiler/src/codesys/symbols.ts
22
+ import {
23
+ standardBlocks as standardBlocks2
24
+ } from "@tsplc/compiler/ir";
25
+
26
+ // packages/compiler/src/codesys/global-names.ts
27
+ import { standardBlocks } from "@tsplc/compiler/ir";
72
28
 
73
29
  // packages/compiler/src/codesys/names.ts
74
30
  import { elementaryTypesByName } from "@tsplc/iec";
@@ -119,44 +75,6 @@ class Names {
119
75
  }
120
76
  }
121
77
 
122
- // packages/compiler/src/codesys/config.ts
123
- var addressSchema = directIoBindingSchema.extend({
124
- kind: z2.literal("direct"),
125
- mapped: z2.boolean().optional()
126
- });
127
- var iecNames = z2.record(z2.string().min(1), z2.string().refine(isIecIdentifier, "Use a valid, non-reserved IEC identifier.")).optional();
128
- var optionsSchema = z2.object({
129
- engineering: engineeringSchema,
130
- http: httpOptionsSchema,
131
- io: z2.record(z2.string().min(1), addressSchema),
132
- publish: publicationSchema.default({ production: [], development: [] }),
133
- buildTarget: buildTargetSchema.default("production"),
134
- programNames: iecNames
135
- }).strict();
136
- function codesys(options) {
137
- return { kind: "codesys", options };
138
- }
139
- function direct(address) {
140
- return { kind: "direct", address };
141
- }
142
- // packages/compiler/src/codesys/emit.ts
143
- import { createHash as createHash2 } from "node:crypto";
144
-
145
- // packages/compiler/src/codesys/explain.ts
146
- import {
147
- instancedBlock as instancedBlock7,
148
- nestedBodies as nestedBodies6,
149
- pathConditions,
150
- projectReconstruction,
151
- standardBlocks as standardBlocks4
152
- } from "@tsplc/compiler/ir";
153
- import { createExplainer } from "@tsplc/debug/explain";
154
- import { createPaths } from "@tsplc/debug/paths";
155
- import { serviceOfPath as serviceOfPath2 } from "@tsplc/server";
156
-
157
- // packages/compiler/src/codesys/debug.ts
158
- import { directWrites, instancedBlock as instancedBlock3, nestedBodies as nestedBodies2 } from "@tsplc/compiler/ir";
159
-
160
78
  // packages/compiler/src/codesys/storage.ts
161
79
  import { basename } from "node:path";
162
80
  import {
@@ -236,1546 +154,1729 @@ function storageLayout(core) {
236
154
  };
237
155
  }
238
156
 
239
- // packages/compiler/src/codesys/task-access.ts
157
+ // packages/compiler/src/codesys/types.ts
158
+ import { instancedBlock as instancedBlock2, nanosecondsPerMillisecond } from "@tsplc/compiler/ir";
159
+ import { escapeString } from "@tsplc/iec/st";
160
+
161
+ // packages/compiler/src/codesys/numeric.ts
240
162
  import {
241
- instancedBlock as instancedBlock2,
242
- nanosecondsPerMillisecond,
163
+ integerRange,
164
+ integerType,
243
165
  nestedBodies,
166
+ pathIndexes,
244
167
  statementExpressions,
245
168
  subexpressions
246
169
  } from "@tsplc/compiler/ir";
247
- var variablesById = (core) => new Map([
248
- ...core.variables,
249
- ...core.functions.flatMap((fn) => [...fn.parameters, ...fn.locals]),
250
- ...core.blocks.flatMap((block) => [
251
- ...block.inputs,
252
- ...block.outputs,
253
- ...block.state,
254
- ...block.locals
255
- ])
256
- ].map((variable) => [variable.id, variable]));
257
- function routineTasks(core, deployment) {
258
- const tasks = new Map;
259
- const types = new Map(core.types.map((type) => [type.id, type]));
260
- const routines = new Map([...core.functions, ...core.blocks].map((routine) => [routine.id, routine]));
261
- const variables = variablesById(core);
262
- const programs = new Map(core.programs.map((program) => [program.name, program]));
263
- for (const task of deployment.tasks) {
264
- for (const name of task.programs) {
265
- const seen = new Set;
266
- const visit = (id) => {
267
- if (seen.has(id)) {
268
- return;
269
- }
270
- seen.add(id);
271
- tasks.set(id, tasks.has(id) && tasks.get(id) !== task.name ? undefined : task.name);
272
- const inspect = (items) => {
273
- for (const item of items) {
274
- if (item.kind === "invoke") {
275
- visit(item.function);
276
- }
277
- if (item.kind === "blockUpdate") {
278
- const block = instancedBlock2(variables.get(item.instance).type, types);
279
- if (block) {
280
- visit(block.block);
281
- }
282
- }
283
- for (const body of nestedBodies(item)) {
284
- inspect(body);
285
- }
286
- }
287
- };
288
- inspect(routines.get(id)?.body ?? []);
289
- };
290
- visit(programs.get(name).entry);
291
- }
170
+ import {
171
+ floatMaximum,
172
+ isElementary
173
+ } from "@tsplc/iec/arithmetic";
174
+ var elementaryNames = {
175
+ sqrt: "SQRT",
176
+ ln: "LN",
177
+ log10: "LOG",
178
+ exp: "EXP",
179
+ sin: "SIN",
180
+ cos: "COS",
181
+ tan: "TAN",
182
+ asin: "ASIN",
183
+ acos: "ACOS",
184
+ atan: "ATAN"
185
+ };
186
+ var operatorTokens = {
187
+ add: "+",
188
+ subtract: "-",
189
+ multiply: "*",
190
+ divide: "/",
191
+ remainder: "MOD",
192
+ equal: "=",
193
+ notEqual: "<>",
194
+ less: "<",
195
+ lessEqual: "<=",
196
+ greater: ">",
197
+ greaterEqual: ">=",
198
+ bitAnd: "AND",
199
+ bitOr: "OR",
200
+ bitXor: "XOR"
201
+ };
202
+ function scalarLiteral(value, type) {
203
+ if (value.kind === "bool") {
204
+ return value.value ? "TRUE" : "FALSE";
292
205
  }
293
- return tasks;
206
+ if (value.kind === "integer") {
207
+ return `${type}#${value.value}`;
208
+ }
209
+ if (value.kind === "float") {
210
+ const text = Object.is(value.value, -0) ? "-0.0" : String(value.value).replace(/e/i, "E");
211
+ return `${type}#${text}`;
212
+ }
213
+ throw new Error("Expected verified scalar constant");
294
214
  }
295
- function schedulePrograms(core, tasks, report) {
296
- const background = new Map;
297
- for (const program of core.programs) {
298
- if (!program.background) {
299
- continue;
215
+
216
+ class NumericLowering {
217
+ types;
218
+ allocate;
219
+ objects = [];
220
+ helpers = new Map;
221
+ constructor(types, allocate) {
222
+ this.types = types;
223
+ this.allocate = allocate;
224
+ }
225
+ prepare(value) {
226
+ for (const operand of subexpressions(value)) {
227
+ this.prepare(operand);
300
228
  }
301
- const { priority, intervalNanoseconds } = program.background;
302
- const name = `TsplcBackground_${priority}_${BigInt(intervalNanoseconds) / nanosecondsPerMillisecond}`;
303
- const existing = background.get(name);
304
- if (existing) {
305
- existing.programs.push(program.name);
306
- continue;
229
+ if (value.kind === "binary" && value.policy) {
230
+ this.arithmetic(value.type, value.operator, value.policy);
307
231
  }
308
- background.set(name, {
309
- name,
310
- priority,
311
- intervalNanoseconds,
312
- programs: [program.name]
313
- });
314
- }
315
- return appendContinuations(core, [...tasks, ...background.values()], report);
316
- }
317
- function taskStorageOwnership(core, report) {
318
- const owners = new Map;
319
- const globals = new Map(core.variables.map((item) => [item.id, item]));
320
- const functions = new Map(core.functions.map((item) => [item.id, item]));
321
- const blocks = new Map(core.blocks.map((block) => [block.id, block.runtime?.kind]));
322
- const runtimes = new Map(core.types.flatMap((type) => type.kind === "block" ? [[type.id, blocks.get(type.block)]] : []));
323
- return (task, program) => {
324
- const fn = functions.get(program.entry);
325
- if (!fn) {
326
- throw new Error("Verified core has a missing entry.");
232
+ if (value.kind === "convert" && value.policy === "saturate") {
233
+ this.saturation(value.operand.type, value.type);
327
234
  }
328
- const worker = program.background?.worker;
329
- const host = worker && core.variables.find((item) => item.name === worker && item.span.file === fn.span.file && runtimes.get(item.type) === "backgroundHost");
330
- for (const id of accessedStorage(fn, core, host ? host.id : undefined)) {
331
- const item = globals.get(id);
332
- if (!item || item.storage === "constant" || runtimes.get(item.type) === "mailbox") {
333
- continue;
334
- }
335
- const ownsWorker = worker === item.name && item.span.file === fn.span.file;
336
- if (program.background && (!ownsWorker || host && item.id === host.id)) {
337
- report(`Background task ${program.name} accesses scan-owned storage ${item.name}; pass value snapshots through the mailbox.`, item.span);
235
+ if (value.kind === "unary" && value.operator === "truncate") {
236
+ this.truncation(value.type);
237
+ }
238
+ }
239
+ prepareStatements(items) {
240
+ for (const item of items) {
241
+ const values = item.kind === "assign" ? [item.value, ...pathIndexes(item.path)] : statementExpressions(item);
242
+ for (const value of values) {
243
+ this.prepare(value);
338
244
  }
339
- const owner = owners.get(id);
340
- if (owner && owner !== task) {
341
- report(`Storage ${item.name} is shared across cyclic tasks ${owner} and ${task}.`, item.span);
245
+ for (const body of nestedBodies(item)) {
246
+ this.prepareStatements(body);
342
247
  }
343
- owners.set(id, task);
344
248
  }
345
- };
346
- }
347
- var buildModuleTables = (core) => ({
348
- functions: new Map(core.functions.map((item) => [item.id, item])),
349
- blocks: new Map(core.blocks.map((item) => [item.id, item])),
350
- types: new Map(core.types.map((item) => [item.id, item])),
351
- variables: variablesById(core)
352
- });
353
- var builtTables = new WeakMap;
354
- var moduleTables = (core) => {
355
- const known = builtTables.get(core);
356
- if (known) {
357
- return known;
358
249
  }
359
- const tables = buildModuleTables(core);
360
- builtTables.set(core, tables);
361
- return tables;
362
- };
363
- function accessedStorage(fn, core, scheduledHost) {
364
- const scheduledCall = fn.body.find((item) => item.kind === "invoke" && item.instance === scheduledHost);
365
- const result = new Set;
366
- const seen = new Set;
367
- const { functions, blocks, types, variables } = moduleTables(core);
368
- const expression = (value) => {
369
- if (value.kind === "load") {
370
- result.add(value.root);
371
- }
372
- if (value.kind === "borrow") {
373
- result.add(value.place.root);
250
+ render(value, operands) {
251
+ if (value.kind === "convert") {
252
+ return value.policy === "saturate" ? `${this.saturation(value.operand.type, value.type)}(${operands[0]})` : `TO_${value.type}(${operands[0]})`;
374
253
  }
375
- subexpressions(value).forEach(expression);
376
- };
377
- const body = (items) => {
378
- for (const item of items) {
379
- if (item.kind === "assign") {
380
- result.add(item.root);
381
- }
382
- if (item.kind === "invoke" && item.instance && item !== scheduledCall) {
383
- result.add(item.instance);
384
- }
385
- if (item.kind === "blockUpdate") {
386
- result.add(item.instance);
254
+ if (value.kind === "unary") {
255
+ if (value.operator === "timeToMilliseconds") {
256
+ return `TIME_TO_UDINT(${operands[0]})`;
387
257
  }
388
- statementExpressions(item).forEach(expression);
389
- if (item.kind === "for") {
390
- result.add(item.counter);
258
+ if (value.operator === "clock") {
259
+ return "TO_DINT(TIME_TO_UDINT(TIME()))";
391
260
  }
392
- if (item.kind === "invoke") {
393
- if (item.destination) {
394
- result.add(item.destination);
395
- }
396
- const called = functions.get(item.function);
397
- if (called && !seen.has(called.id)) {
398
- seen.add(called.id);
399
- body(called.body);
400
- }
261
+ if (isElementary(value.operator)) {
262
+ return `${elementaryNames[value.operator]}(${operands[0]})`;
401
263
  }
402
- if (item.kind === "blockUpdate") {
403
- const variable = variables.get(item.instance);
404
- if (!variable) {
405
- throw new Error("Missing verified instance during task planning.");
406
- }
407
- const type = instancedBlock2(variable.type, types);
408
- const block = type && blocks.get(type.block);
409
- if (block && !seen.has(block.id)) {
410
- seen.add(block.id);
411
- body(block.body);
412
- }
264
+ if (value.operator === "truncate") {
265
+ return `${this.truncation(value.type)}(${operands[0]})`;
413
266
  }
414
- nestedBodies(item).forEach(body);
267
+ return value.operator === "not" ? `(NOT ${operands[0]})` : `TO_${value.type}(${value.operator === "negate" ? "-" : "NOT "}${operands[0]})`;
415
268
  }
416
- };
417
- seen.add(fn.id);
418
- body(fn.body);
419
- return result;
420
- }
421
- function appendContinuations(core, tasks, report) {
422
- const continuations = core.programs.flatMap((program) => program.continuation ? [{ name: program.name, scope: program.continuation }] : []);
423
- if (!continuations.length) {
424
- return tasks;
425
- }
426
- const programs = new Map(core.programs.map((program) => [program.name, program]));
427
- const functions = new Map(core.functions.map((routine) => [routine.id, routine]));
428
- const placements = tasks.map((task) => {
429
- const roots = new Set;
430
- for (const name of task.programs) {
431
- const program = programs.get(name);
432
- if (!program || program.background) {
433
- continue;
434
- }
435
- const entry = functions.get(program.entry);
436
- if (entry) {
437
- for (const id of accessedStorage(entry, core)) {
438
- roots.add(id);
439
- }
440
- }
269
+ if (value.kind !== "binary") {
270
+ throw new Error("Expected numeric operation");
441
271
  }
442
- return { task, roots, additions: [] };
443
- });
444
- for (const { name, scope } of continuations) {
445
- const root = core.variables.find((variable) => variable.name === scope.instance && variable.span.file === scope.file);
446
- if (!root) {
447
- report(`Missing continuation owner ${scope.instance}.`);
448
- continue;
272
+ if (value.policy) {
273
+ return `${this.arithmetic(value.type, value.operator, value.policy)}(${operands.join(", ")})`;
449
274
  }
450
- const owners = placements.filter(({ roots }) => roots.has(root.id));
451
- const [owner] = owners;
452
- if (!owner || owners.length !== 1) {
453
- report(`Continuation owner ${scope.instance} must belong to exactly one caller task.`, root.span);
454
- continue;
275
+ if (value.operator === "power") {
276
+ return `EXPT(${operands.join(", ")})`;
455
277
  }
456
- owner.additions.push(name);
457
- }
458
- return placements.map(({ task, additions }) => ({
459
- ...task,
460
- programs: task.programs.concat(additions)
461
- }));
462
- }
463
-
464
- // packages/compiler/src/codesys/debug.ts
465
- var temporary = (id) => id.includes(":temporary:");
466
- var constantIndex = (value) => value.kind === "constant" && value.value.kind === "integer" ? Number(value.value.value) : undefined;
467
- var writtenPlace = (item) => {
468
- if (item.kind === "assign") {
469
- return { root: item.root, path: item.path ?? [] };
470
- }
471
- return item.kind === "invoke" && item.destination ? { root: item.destination, path: [] } : undefined;
472
- };
473
- var wholeTarget = (item) => {
474
- if (item.kind === "assign" && !item.path?.length) {
475
- return item.root;
476
- }
477
- return item.kind === "invoke" ? item.destination : undefined;
478
- };
479
- function blockInstances(core) {
480
- const types = new Map(core.types.map((type) => [type.id, type]));
481
- const blocks = new Map(core.blocks.map((block) => [block.id, block]));
482
- const instances = new Map(core.blocks.map((block) => [block.id, []]));
483
- const visit = (variable, block, path) => {
484
- const type = types.get(variable.type);
485
- const declared = type?.kind === "array" ? Array.from({ length: type.length }, (_, offset) => [
486
- ...path,
487
- { variable, index: type.lowerBound + offset }
488
- ]) : [[...path, { variable }]];
489
- for (const instance of declared) {
490
- instances.get(block).push(instance);
491
- for (const child of blocks.get(block).state) {
492
- const instanced = instancedBlock3(child.type, types);
493
- if (instanced) {
494
- visit(child, instanced.block, instance);
495
- }
496
- }
278
+ if (value.operator === "shiftLeft" || value.operator === "shiftRight") {
279
+ const shift = value.operator === "shiftLeft" ? "SHL" : "SHR";
280
+ return `TO_${value.type}(${shift}(${operands.join(", ")}))`;
497
281
  }
498
- };
499
- for (const variable of core.variables) {
500
- const instanced = instancedBlock3(variable.type, types);
501
- if (instanced) {
502
- visit(variable, instanced.block, []);
282
+ const token = operatorTokens[value.operator];
283
+ if (!token) {
284
+ throw new Error("Boolean short-circuit operation was not normalized");
503
285
  }
286
+ const text = value.operator === "remainder" ? `(${operands[0]} - (${operands[0]} / ${operands[1]}) * ${operands[1]})` : `(${operands[0]} ${token} ${operands[1]})`;
287
+ return value.type === "BOOL" ? text : `TO_${value.type}(${text})`;
504
288
  }
505
- return instances;
506
- }
507
- function storagePath(root, path = []) {
508
- const logical = root.storage === "input" || root.storage === "output";
509
- if (!logical && root.storage !== "module" && root.storage !== "instance") {
510
- return;
289
+ helper(key, type, inputs, body, locals = "") {
290
+ const existing = this.helpers.get(key);
291
+ if (existing) {
292
+ return existing;
293
+ }
294
+ const name = this.allocate(`numeric_${key}`);
295
+ this.helpers.set(key, name);
296
+ const parameters = inputs.map(([input, inputType]) => ` ${input} : ${inputType};`).join(`
297
+ `);
298
+ const variables = locals ? `VAR
299
+ ${locals}
300
+ END_VAR
301
+ ` : "";
302
+ const declaration = `FUNCTION ${name} : ${type}
303
+ VAR_INPUT
304
+ ${parameters}
305
+ END_VAR
306
+ ${variables}`;
307
+ this.objects.push({
308
+ id: `numeric:${key}`,
309
+ kind: "function",
310
+ name,
311
+ declaration,
312
+ implementation: body(name)
313
+ });
314
+ return name;
511
315
  }
512
- let text = logical ? root.name : `${moduleName(root)}.${root.name}`;
513
- for (const segment of path) {
514
- if (segment.kind === "field") {
515
- text += `.${segment.name}`;
516
- continue;
316
+ add64() {
317
+ return this.helper("add64", "LWORD", [
318
+ ["a", "LWORD"],
319
+ ["b", "LWORD"]
320
+ ], (name) => `x := a;
321
+ y := b;
322
+ FOR i := 1 TO 64 DO
323
+ carry := SHL(x AND y, 1);
324
+ x := x XOR y;
325
+ y := carry;
326
+ END_FOR;
327
+ ${name} := x;
328
+ `, ` x, y, carry : LWORD;
329
+ i : UINT;`);
330
+ }
331
+ wrap64(operator) {
332
+ const add = this.add64();
333
+ if (operator === "add") {
334
+ return add;
517
335
  }
518
- const index = constantIndex(segment.value);
519
- if (index === undefined) {
520
- return;
336
+ if (operator === "subtract") {
337
+ return this.helper("subtract64", "LWORD", [
338
+ ["a", "LWORD"],
339
+ ["b", "LWORD"]
340
+ ], (name) => `${name} := ${add}(a, ${add}(NOT b, LWORD#1));
341
+ `);
521
342
  }
522
- text += `[${index}]`;
343
+ if (operator !== "multiply") {
344
+ throw new Error("Unsupported verified wrapping operation");
345
+ }
346
+ return this.helper("multiply64", "LWORD", [
347
+ ["a", "LWORD"],
348
+ ["b", "LWORD"]
349
+ ], (name) => `x := a;
350
+ y := b;
351
+ result := LWORD#0;
352
+ FOR i := 1 TO 64 DO
353
+ IF (y AND LWORD#1) <> LWORD#0 THEN
354
+ result := ${add}(result, x);
355
+ END_IF;
356
+ x := SHL(x, 1);
357
+ y := SHR(y, 1);
358
+ END_FOR;
359
+ ${name} := result;
360
+ `, ` x, y, result : LWORD;
361
+ i : UINT;`);
523
362
  }
524
- return text;
525
- }
526
-
527
- class DebugAnalysis {
528
- core;
529
- outputs;
530
- tasks;
531
- instances;
532
- probes = new Map;
533
- events = [];
534
- writers;
535
- jobSites = new Map;
536
- decisions = new Map;
537
- callSites = new Map;
538
- carriers = new Set;
539
- variables;
540
- types;
541
- routines;
542
- blocks;
543
- routineWrites = new Map;
544
- temporaries = new Map;
545
- writerSites = 0;
546
- constructor(core, deployment, settings, outputs) {
547
- this.core = core;
548
- this.outputs = outputs;
549
- this.types = new Map(core.types.map((type) => [type.id, type]));
550
- this.blocks = new Map(core.blocks.map((block) => [block.id, block]));
551
- this.routines = new Map([...core.functions, ...core.blocks].map((routine) => [
552
- routine.id,
553
- routine
554
- ]));
555
- this.variables = variablesById(core);
556
- this.writers = outputs.map(() => []);
557
- this.tasks = routineTasks(core, deployment);
558
- this.instances = blockInstances(core);
559
- this.findCarriers();
560
- if (!settings) {
561
- return;
562
- }
563
- const routines = [
564
- ...core.functions,
565
- ...core.blocks.filter((block) => !block.standard)
566
- ];
567
- for (const routine of routines) {
568
- this.countCalls(routine.body, 1);
363
+ arithmetic(typeId, operator, policy) {
364
+ const type = this.types.get(typeId);
365
+ if (type?.kind !== "integer") {
366
+ throw new Error("Expected verified integer arithmetic");
569
367
  }
570
- for (const routine of routines) {
571
- this.walk(settings, routine, routine.body, [], []);
368
+ const token = operatorTokens[operator];
369
+ if (!token) {
370
+ throw new Error("Expected verified integer arithmetic");
572
371
  }
573
- if (settings.trace) {
574
- for (const block of core.blocks) {
575
- const { job } = block;
576
- const task = this.tasks.get(block.id);
577
- if (!job || !task || this.instances.get(block.id)?.length !== 1) {
578
- continue;
579
- }
580
- const site = (type, phase) => this.site({
581
- kind: "job",
582
- job: { block: block.id, phase },
583
- path: job.name,
584
- type,
585
- span: job.span,
586
- text: `${job.name}: ${phase}`,
587
- task
588
- });
589
- this.jobSites.set(block.id, {
590
- start: site("UINT", "started"),
591
- completion: site("DINT", "finished")
592
- });
372
+ const key = `${policy}_${operator}_${typeId}`;
373
+ if (policy === "wrap") {
374
+ if (type.bits === 64) {
375
+ const operation = this.wrap64(operator);
376
+ return this.helper(key, typeId, [
377
+ ["a", typeId],
378
+ ["b", typeId]
379
+ ], (name) => `${name} := LWORD_TO_${typeId}(${operation}(${typeId}_TO_LWORD(a), ${typeId}_TO_LWORD(b)));
380
+ `);
593
381
  }
382
+ const wide = !type.signed && operator !== "subtract" ? "ULINT" : "LINT";
383
+ return this.helper(key, typeId, [
384
+ ["a", typeId],
385
+ ["b", typeId]
386
+ ], (name) => `${name} := ${wide}_TO_${typeId}(${typeId}_TO_${wide}(a) ${token} ${typeId}_TO_${wide}(b));
387
+ `);
594
388
  }
389
+ const [minimum, maximum] = integerRange(type);
390
+ const min = `${typeId}#${minimum}`;
391
+ const max = `${typeId}#${maximum}`;
392
+ const zero = `${typeId}#0`;
393
+ return this.helper(key, typeId, [
394
+ ["a", typeId],
395
+ ["b", typeId]
396
+ ], (name) => {
397
+ const clamp = (condition, endpoint, depth = "") => `${depth}IF ${condition} THEN
398
+ ${depth} ${name} := ${endpoint};
399
+ ${depth} RETURN;
400
+ ${depth}END_IF;
401
+ `;
402
+ const guard = () => {
403
+ if (!type.signed) {
404
+ if (operator === "add") {
405
+ return clamp(`a > ${max} - b`, max);
406
+ }
407
+ if (operator === "subtract") {
408
+ return clamp("a < b", zero);
409
+ }
410
+ return `IF b <> ${zero} THEN
411
+ ${clamp(`a > ${max} / b`, max, " ")}END_IF;
412
+ `;
413
+ }
414
+ if (operator === "add") {
415
+ return `IF b > ${zero} THEN
416
+ ${clamp(`a > ${max} - b`, max, " ")}ELSIF b < ${zero} THEN
417
+ ${clamp(`a < ${min} - b`, min, " ")}END_IF;
418
+ `;
419
+ }
420
+ if (operator === "subtract") {
421
+ return `IF b < ${zero} THEN
422
+ ${clamp(`a > ${max} + b`, max, " ")}ELSIF b > ${zero} THEN
423
+ ${clamp(`a < ${min} + b`, min, " ")}END_IF;
424
+ `;
425
+ }
426
+ return clamp(`a = ${zero}`, zero) + clamp(`b = ${zero}`, zero) + `IF a > ${zero} THEN
427
+ IF b > ${zero} THEN
428
+ ${clamp(`a > ${max} / b`, max, " ")} ELSE
429
+ ${clamp(`b < ${min} / a`, min, " ")} END_IF;
430
+ ELSE
431
+ IF b > ${zero} THEN
432
+ ${clamp(`a < ${min} / b`, min, " ")} ELSE
433
+ ${clamp(`a < ${max} / b`, max, " ")} END_IF;
434
+ END_IF;
435
+ `;
436
+ };
437
+ return `${guard()}${name} := a ${token} b;
438
+ `;
439
+ });
595
440
  }
596
- owningPath(variable) {
597
- const type = this.types.get(variable.type);
598
- const block = type?.kind === "block" ? this.blocks.get(type.block) : undefined;
599
- if (!block?.job) {
600
- return;
441
+ truncation(typeId) {
442
+ const type = this.types.get(typeId);
443
+ if (type?.kind !== "float") {
444
+ throw new Error("Expected verified float truncation");
601
445
  }
602
- const paths = this.instances.get(block.id).filter((path) => path.at(-1).variable.id === variable.id);
603
- return paths.length === 1 ? paths[0] : undefined;
604
- }
605
- site(site) {
606
- const id = this.events.length + 1;
607
- this.events.push({ ...site, id, operands: site.operands ?? [] });
608
- return id;
446
+ const whole = scalarLiteral({ kind: "float", value: 2 ** (type.bits === 32 ? 23 : 52) }, typeId);
447
+ return this.helper(`truncate_${typeId}`, typeId, [["value", typeId]], (name) => `IF ABS(value) >= ${whole} THEN
448
+ ${name} := value;
449
+ RETURN;
450
+ END_IF;
451
+ nearest := TO_LINT(value);
452
+ IF value >= 0 AND TO_${typeId}(nearest) > value THEN
453
+ nearest := nearest - 1;
454
+ ELSIF value < 0 AND TO_${typeId}(nearest) < value THEN
455
+ nearest := nearest + 1;
456
+ END_IF;
457
+ ${name} := TO_${typeId}(nearest);
458
+ `, " nearest : LINT;");
609
459
  }
610
- findCarriers() {
611
- const carries = (id) => {
612
- const block = this.blocks.get(id);
613
- if (block.runtime?.kind === "http") {
614
- return true;
615
- }
616
- return block.state.some((child) => {
617
- const type = instancedBlock3(child.type, this.types);
618
- return type !== undefined && carries(type.block);
619
- });
620
- };
621
- for (const block of this.core.blocks) {
622
- if (carries(block.id)) {
623
- this.carriers.add(block.id);
460
+ saturation(sourceId, targetId) {
461
+ const source = this.types.get(sourceId);
462
+ const target = this.types.get(targetId);
463
+ if (source?.kind === "float" && target?.kind === "float") {
464
+ if (source.bits <= target.bits) {
465
+ return `TO_${targetId}`;
624
466
  }
467
+ const maximum = floatMaximum(target);
468
+ const literal = (value, type) => scalarLiteral({ kind: "float", value }, type);
469
+ return this.helper(`saturate_${sourceId}_${targetId}`, targetId, [["value", sourceId]], (name) => `IF value < ${literal(-maximum, sourceId)} THEN
470
+ ${name} := ${literal(-maximum, targetId)};
471
+ RETURN;
472
+ END_IF;
473
+ IF value > ${literal(maximum, sourceId)} THEN
474
+ ${name} := ${literal(maximum, targetId)};
475
+ RETURN;
476
+ END_IF;
477
+ ${name} := TO_${targetId}(value);
478
+ `);
625
479
  }
626
- }
627
- placeType(root, path = []) {
628
- let type = this.types.get(root.type);
629
- for (const segment of path) {
630
- if (segment.kind === "field" && type?.kind === "record") {
631
- type = this.types.get(type.fields.find((field) => field.name === segment.name).type);
632
- } else if (segment.kind === "index" && type?.kind === "array") {
633
- type = this.types.get(type.element);
634
- } else {
635
- return;
636
- }
480
+ if (!source || !target || !integerType(source) || !integerType(target)) {
481
+ throw new Error("Expected verified integer saturation");
637
482
  }
638
- return type;
639
- }
640
- countCalls(items, weight) {
641
- for (const item of items) {
642
- if (item.kind === "invoke") {
643
- this.callSites.set(item.function, (this.callSites.get(item.function) ?? 0) + weight);
483
+ const [fromMin, fromMax] = integerRange(source);
484
+ const [toMin, toMax] = integerRange(target);
485
+ return this.helper(`saturate_${sourceId}_${targetId}`, targetId, [["value", sourceId]], (name) => {
486
+ let body = "";
487
+ if (fromMin < toMin) {
488
+ body += `IF value < ${sourceId}#${toMin} THEN
489
+ ${name} := ${targetId}#${toMin};
490
+ RETURN;
491
+ END_IF;
492
+ `;
644
493
  }
645
- for (const body of nestedBodies2(item)) {
646
- this.countCalls(body, item.kind === "for" ? 2 : weight);
494
+ if (fromMax > toMax) {
495
+ body += `IF value > ${sourceId}#${toMax} THEN
496
+ ${name} := ${targetId}#${toMax};
497
+ RETURN;
498
+ END_IF;
499
+ `;
647
500
  }
648
- }
649
- }
650
- writes(id) {
651
- const cached = this.routineWrites.get(id);
652
- if (cached) {
653
- return cached;
654
- }
655
- const result = new Set;
656
- this.routineWrites.set(id, result);
657
- for (const root of this.statementWrites(this.routines.get(id)?.body ?? [])) {
658
- result.add(root);
659
- }
660
- return result;
501
+ return `${body}${name} := TO_${targetId}(value);
502
+ `;
503
+ });
661
504
  }
662
- statementWrites(items) {
663
- const result = new Set;
664
- for (const item of items) {
665
- for (const root of directWrites(item)) {
666
- result.add(root);
667
- }
668
- if (item.kind === "invoke") {
669
- for (const root of this.writes(item.function)) {
670
- result.add(root);
505
+ }
506
+
507
+ // packages/compiler/src/codesys/types.ts
508
+ var sourceTypeName = (id) => id.slice(id.lastIndexOf(":") + 1);
509
+ var stringTypeName = (type) => type.encoding === "utf8" ? "STRING" : "WSTRING";
510
+ var stEscapes = new Map([
511
+ ["$", "$$"],
512
+ ["'", "$'"],
513
+ ["\r", "$R"],
514
+ [`
515
+ `, "$N"]
516
+ ]);
517
+ var stStringLiteral = (text) => `'${[...text].map((character) => stEscapes.get(character) ?? character).join("")}'`;
518
+ var anonymousRecordId = /:\d+:record(<.*>)?$/;
519
+ var required = (value) => {
520
+ if (value === undefined) {
521
+ throw new Error("Missing verified type name");
522
+ }
523
+ return value;
524
+ };
525
+
526
+ class CodesysTypes {
527
+ types;
528
+ objects = [];
529
+ names = new Map;
530
+ fields = new Map;
531
+ aliases = new Set;
532
+ shapes = new Map;
533
+ constructor(types, names, blockNames) {
534
+ this.types = types;
535
+ const anonymous = new Map;
536
+ for (const type of types.values()) {
537
+ const shape = this.anonymousShape(type);
538
+ const shared = shape === null ? undefined : anonymous.get(shape);
539
+ if (shared !== undefined) {
540
+ this.names.set(type.id, required(this.names.get(shared)));
541
+ this.fields.set(type.id, required(this.fields.get(shared)));
542
+ this.aliases.add(type.id);
543
+ continue;
544
+ }
545
+ if (shape !== null) {
546
+ anonymous.set(shape, type.id);
547
+ }
548
+ if (type.kind === "block") {
549
+ const name = blockNames.get(type.block);
550
+ if (!name) {
551
+ throw new Error("Missing verified block name");
671
552
  }
553
+ this.names.set(type.id, name);
672
554
  }
673
- if (item.kind === "blockUpdate") {
674
- const block = instancedBlock3(this.variables.get(item.instance).type, this.types);
675
- if (block) {
676
- for (const root of this.writes(block.block)) {
677
- result.add(root);
678
- }
555
+ if (["record", "array", "enum", "string"].includes(type.kind)) {
556
+ const label = sourceTypeName(type.id);
557
+ if (type.kind === "record" || type.kind === "enum") {
558
+ const prefix = type.kind === "record" ? "ST" : "E";
559
+ this.names.set(type.id, names.allocateObject(prefix, label));
560
+ } else if (!this.inline(type)) {
561
+ this.names.set(type.id, names.allocate(`T_${label}`));
679
562
  }
680
563
  }
681
- for (const body of nestedBodies2(item)) {
682
- for (const root of this.statementWrites(body)) {
683
- result.add(root);
564
+ if (type.kind === "record" || type.kind === "enum") {
565
+ const names = new Names;
566
+ const fields = new Map;
567
+ for (const member of type.kind === "record" ? type.fields : type.members) {
568
+ fields.set(member.name, names.allocate(member.name));
684
569
  }
570
+ this.fields.set(type.id, fields);
685
571
  }
686
572
  }
687
- return result;
688
- }
689
- walk(settings, routine, items, prefixes, guards) {
690
- for (const [index, item] of items.entries()) {
691
- const here = [...prefixes, items.slice(0, index)];
692
- this.probe(settings, routine, item, here, guards);
693
- const guard = (conditions) => [
694
- ...guards,
695
- { conditions, depth: here.length }
696
- ];
697
- if (item.kind === "if") {
698
- this.walk(settings, routine, item.then, here, guard([item.condition]));
699
- this.walk(settings, routine, item.else, here, guard([item.condition]));
700
- }
701
- if (item.kind === "switch") {
702
- for (const body of nestedBodies2(item)) {
703
- this.walk(settings, routine, body, here, guard([item.value]));
704
- }
573
+ const emitted = new Set;
574
+ const emit = (type) => {
575
+ if (type.kind === "array" && this.inline(type)) {
576
+ emit(this.type(type.element));
577
+ return;
705
578
  }
706
- if (item.kind === "for") {
707
- this.walk(settings, routine, item.body, here, guards);
579
+ if (instancedBlock2(type.id, types) || !this.names.has(type.id) || this.aliases.has(type.id) || emitted.has(type.id)) {
580
+ return;
708
581
  }
709
- }
710
- }
711
- probe(settings, routine, item, prefixes, guards) {
712
- const task = this.tasks.get(routine.id);
713
- const probes = [];
714
- const written = writtenPlace(item);
715
- if (written && settings.writers) {
716
- let site;
717
- this.outputs.forEach((output, index) => {
718
- const when = this.reaches(written.root, written.path, output);
719
- if (!when) {
720
- return;
721
- }
722
- site ??= ++this.writerSites;
723
- this.writers[index].push({
724
- id: site,
725
- routine: routine.id,
726
- span: item.span,
727
- statement: item
728
- });
729
- probes.push({ kind: "writer", site, output: index, when });
730
- });
731
- }
732
- if (settings.trace && task) {
733
- if (item.kind === "assign") {
734
- const root = this.variables.get(item.root);
735
- const type = this.placeType(root, item.path);
736
- const path = root.storage === "module" ? storagePath(root, item.path) : undefined;
737
- if (type?.kind === "enum" && path) {
738
- const operands = this.operands(routine, prefixes, guards, settings.trace);
739
- const site = this.site({
740
- kind: "state",
741
- path,
742
- routine: routine.id,
743
- type: type.id,
744
- span: item.span,
745
- task,
746
- operands
747
- });
748
- probes.push({ kind: "state", value: item.value, site, operands });
749
- }
582
+ if (type.kind === "array") {
583
+ emit(this.type(type.element));
750
584
  }
751
- if (item.kind === "return" && item.value && "parameters" in routine && routine.result && this.callSites.get(routine.id) === 1) {
752
- const type = this.types.get(routine.result);
753
- if (type?.kind === "enum") {
754
- const slot = this.decisions.get(routine.id) ?? this.decisions.size;
755
- this.decisions.set(routine.id, slot);
756
- const path = routine.origin?.instance ? `${routine.origin.instance}.${routine.origin.name.split(".").at(-1)}` : routine.origin?.name ?? routine.name;
757
- const operands = this.operands(routine, prefixes, guards, settings.trace);
758
- const site = this.site({
759
- kind: "decision",
760
- path,
761
- routine: routine.id,
762
- type: type.id,
763
- span: item.span,
764
- task,
765
- operands
766
- });
767
- probes.push({
768
- kind: "decision",
769
- value: item.value,
770
- site,
771
- slot,
772
- operands
773
- });
585
+ if (type.kind === "record") {
586
+ for (const field of type.fields) {
587
+ emit(this.type(field.type));
774
588
  }
775
589
  }
590
+ emitted.add(type.id);
591
+ const name = this.name(type.id);
592
+ const declaration = this.dutDeclaration(type, name);
593
+ this.objects.push({ id: type.id, kind: "dataType", name, declaration });
594
+ };
595
+ for (const type of types.values()) {
596
+ emit(type);
776
597
  }
777
- if (probes.length) {
778
- this.probes.set(item, probes);
598
+ }
599
+ anonymousShape(type) {
600
+ if (type.kind !== "record" || !anonymousRecordId.test(type.id)) {
601
+ return null;
602
+ }
603
+ const known = this.shapes.get(type.id);
604
+ if (known !== undefined) {
605
+ return known;
779
606
  }
607
+ const shape = JSON.stringify(type.fields.map((field) => [
608
+ field.name,
609
+ this.anonymousShape(this.type(field.type)) ?? field.type
610
+ ]));
611
+ this.shapes.set(type.id, shape);
612
+ return shape;
780
613
  }
781
- reaches(root, path, output) {
782
- if (root !== output.root.id) {
783
- return;
614
+ dutDeclaration(type, name) {
615
+ if (type.kind === "record") {
616
+ const fields = type.fields.map((field) => ` ${this.field(type.id, field.name)} : ${this.name(field.type)};`).join(`
617
+ `);
618
+ return `TYPE ${name} :
619
+ STRUCT
620
+ ${fields}
621
+ END_STRUCT
622
+ END_TYPE
623
+ `;
784
624
  }
785
- const when = [];
786
- for (const [index, written] of path.entries()) {
787
- const bound = output.segments[index];
788
- if (!bound) {
789
- break;
790
- }
791
- if (written.kind === "field") {
792
- if (bound.kind !== "field" || bound.name !== written.name) {
793
- return;
794
- }
795
- continue;
796
- }
797
- if (bound.kind !== "index") {
798
- return;
799
- }
800
- const value = constantIndex(written.value);
801
- if (value === undefined) {
802
- when.push({ index: written.value, value: bound.value });
803
- } else if (value !== bound.value) {
804
- return;
805
- }
625
+ if (type.kind === "array") {
626
+ return `${type.index ? `{attribute 'tsplc_keyed'}
627
+ ` : ""}TYPE ${name} : ARRAY[${type.lowerBound}..${type.lowerBound + type.length - 1}] OF ${this.name(type.element)};
628
+ END_TYPE
629
+ `;
806
630
  }
807
- return when;
631
+ if (type.kind === "string") {
632
+ return `TYPE ${name} : ${stringTypeName(type)}(${type.capacity});
633
+ END_TYPE
634
+ `;
635
+ }
636
+ if (type.kind === "enum") {
637
+ const members = type.members.map((member) => ` ${this.field(type.id, member.name)} := ${member.value}`).join(`,
638
+ `);
639
+ return `{attribute 'qualified_only'}
640
+ {attribute 'strict'}
641
+ TYPE ${name} : (
642
+ ${members}
643
+ ) DINT;
644
+ END_TYPE
645
+ `;
646
+ }
647
+ throw new Error("Unsupported verified data type");
808
648
  }
809
- definitions(routine) {
810
- const cached = this.temporaries.get(routine.id);
811
- if (cached) {
812
- return cached;
649
+ type(id) {
650
+ const type = this.types.get(id);
651
+ if (!type) {
652
+ throw new Error("Missing verified type");
813
653
  }
814
- const definitions = new Map;
815
- const define = (items) => {
816
- for (const item of items) {
817
- const target = wholeTarget(item);
818
- if (target && temporary(target)) {
819
- definitions.set(target, [...definitions.get(target) ?? [], item]);
820
- }
821
- for (const body of nestedBodies2(item)) {
822
- define(body);
823
- }
824
- }
825
- };
826
- define(routine.body);
827
- this.temporaries.set(routine.id, definitions);
828
- return definitions;
654
+ return type;
829
655
  }
830
- operands(routine, prefixes, guards, trace) {
831
- const definitions = this.definitions(routine);
832
- const result = [];
833
- const seen = new Set;
834
- for (const guard of [...guards].reverse()) {
835
- const executed = new Set(prefixes.slice(0, guard.depth).flat());
836
- const between = this.statementWrites(prefixes.slice(guard.depth).flat());
837
- const add = (span, capture, read) => {
838
- const kind = this.types.get(capture.type)?.kind;
839
- const key = `${span.file}:${span.start}:${span.end}`;
840
- if (seen.has(key) || !["bool", "enum", "integer", "bits"].includes(kind ?? "")) {
841
- return;
842
- }
843
- seen.add(key);
844
- const path = read && storagePath(this.variables.get(read.root), read.path);
845
- result.push({
846
- capture,
847
- span,
848
- ...path && { path },
849
- stable: !read || !between.has(read.root)
850
- });
851
- };
852
- const direct = (value) => (value.path ?? []).every((segment) => segment.kind === "field" || constantIndex(segment.value) !== undefined);
853
- const visit = (value, evaluated) => {
854
- if (value.kind === "unary" || value.kind === "convert") {
855
- visit(value.operand, evaluated);
856
- }
857
- if (value.kind === "binary") {
858
- visit(value.left, evaluated);
859
- visit(value.right, evaluated);
860
- }
861
- if (value.kind !== "load") {
862
- return;
863
- }
864
- if (!temporary(value.root)) {
865
- if (evaluated || direct(value)) {
866
- add(value.span, value, value);
867
- }
868
- return;
869
- }
870
- const defined = definitions.get(value.root) ?? [];
871
- const [item] = defined;
872
- if (!item || defined.length !== 1) {
873
- for (const definition of defined) {
874
- if (definition.kind === "assign") {
875
- visit(definition.value, evaluated && executed.has(definition));
876
- }
877
- }
878
- return;
879
- }
880
- const reached = evaluated && executed.has(item);
881
- if (item.kind === "invoke") {
882
- if (reached) {
883
- add(item.span, value);
884
- }
885
- return;
886
- }
887
- if (item.kind !== "assign") {
888
- return;
889
- }
890
- const source = item.value;
891
- if (source.kind === "load" && !temporary(source.root)) {
892
- const read = {
893
- ...source,
894
- type: value.type,
895
- path: [...source.path ?? [], ...value.path ?? []]
896
- };
897
- if (reached) {
898
- add(source.span, value, read);
899
- } else if (direct(read)) {
900
- add(source.span, read, read);
901
- }
902
- return;
903
- }
904
- visit(source, reached);
905
- };
906
- for (const condition of guard.conditions) {
907
- visit(condition, true);
908
- }
656
+ name(id) {
657
+ const named = this.names.get(id);
658
+ if (named !== undefined) {
659
+ return named;
909
660
  }
910
- return result.slice(0, trace.operands);
661
+ const type = this.types.get(id);
662
+ if (type?.kind === "string" && this.inline(type)) {
663
+ return `${stringTypeName(type)}(${type.capacity})`;
664
+ }
665
+ if (type?.kind === "array" && this.inline(type)) {
666
+ return `ARRAY[${type.lowerBound}..${type.lowerBound + type.length - 1}] OF ${this.name(type.element)}`;
667
+ }
668
+ return id;
911
669
  }
912
- }
913
-
914
- // packages/compiler/src/codesys/global-lists.ts
915
- import {
916
- defaultValue,
917
- instancedBlock as instancedBlock5
918
- } from "@tsplc/compiler/ir";
919
-
920
- // packages/compiler/src/codesys/io-paths.ts
921
- import { ioLayout } from "@tsplc/typegen/hardware";
922
- var pathPattern = /^([\w$-]+)\.([A-Za-z_$][\w$]*)((?:\.[A-Za-z_$][\w$]*|\[-?\d+\])*)$/;
923
- var isStoragePath = (key) => key.includes(".") || key.includes("[");
924
- function resolveStoragePath(core, key) {
925
- const match = pathPattern.exec(key);
926
- if (!match) {
927
- return {
928
- error: `${key}: expected Module.variable followed by .field or [index].`
929
- };
670
+ inline(type) {
671
+ if (type.kind === "string") {
672
+ return true;
673
+ }
674
+ return type.kind === "array" && (!type.index || instancedBlock2(type.id, this.types) !== undefined);
930
675
  }
931
- const [, module, name, rest] = match;
932
- const roots = core.variables.filter((item) => item.storage === "module" && item.name === name && moduleName(item) === module);
933
- const [root] = roots;
934
- if (!root || roots.length !== 1) {
935
- return {
936
- error: root ? `${key}: ${module}.${name} is declared by more than one module named ${module}.` : `${key}: no mutable module variable ${module}.${name}.`
937
- };
676
+ field(id, name) {
677
+ const field = this.fields.get(id)?.get(name);
678
+ if (!field) {
679
+ throw new Error("Missing verified field");
680
+ }
681
+ return field;
938
682
  }
939
- const types = new Map(core.types.map((type) => [type.id, type]));
940
- let type = types.get(root.type);
941
- const segments = [];
942
- for (const [, field, index] of rest.matchAll(/\.([A-Za-z_$][\w$]*)|\[(-?\d+)\]/g)) {
943
- if (field !== undefined) {
944
- const member = type.kind === "record" ? type.fields.find((f) => f.name === field) : undefined;
683
+ declarationInitializer(value, id) {
684
+ const type = this.type(id);
685
+ if ((type.kind === "record" || type.kind === "array") && this.isZero(value)) {
686
+ return "";
687
+ }
688
+ return ` := ${this.initializer(value, id)}`;
689
+ }
690
+ initializer(value, id) {
691
+ const type = this.type(id);
692
+ if (type.kind === "array" && value.kind === "array") {
693
+ return `[${value.items.map((item) => this.initializer(item, type.element)).join(", ")}]`;
694
+ }
695
+ if (type.kind !== "record" || value.kind !== "record") {
696
+ return this.literal(value, id);
697
+ }
698
+ const fields = type.fields.flatMap((field) => {
699
+ const initial = value.fields[field.name];
700
+ if (!initial) {
701
+ throw new Error("Missing verified record initializer");
702
+ }
703
+ return this.type(field.type).kind !== "enum" && this.isZero(initial) ? [] : [
704
+ `${this.field(id, field.name)} := ${this.initializer(initial, field.type)}`
705
+ ];
706
+ });
707
+ return fields.length ? `(${fields.join(", ")})` : this.literal(value, id);
708
+ }
709
+ isZero(value) {
710
+ if (value.kind === "bool") {
711
+ return !value.value;
712
+ }
713
+ if (value.kind === "integer") {
714
+ return value.value === "0";
715
+ }
716
+ if (value.kind === "float") {
717
+ return Object.is(value.value, 0);
718
+ }
719
+ if (value.kind === "string") {
720
+ return value.value === "";
721
+ }
722
+ if (value.kind === "array") {
723
+ return value.items.every((item) => this.isZero(item));
724
+ }
725
+ if (value.kind === "record") {
726
+ return Object.values(value.fields).every((item) => this.isZero(item));
727
+ }
728
+ return false;
729
+ }
730
+ literal(value, id) {
731
+ const type = this.type(id);
732
+ if (type.kind === "enum" && value.kind === "integer") {
733
+ const member = type.members.find((member) => member.value === value.value);
945
734
  if (!member) {
946
- return { error: `${key}: no field ${field}.` };
735
+ throw new Error("Missing verified enum member");
947
736
  }
948
- segments.push({ kind: "field", record: type.id, name: field });
949
- type = types.get(member.type);
950
- } else {
951
- const value = Number(index);
952
- if (type.kind !== "array") {
953
- return { error: `${key}: ${index} indexes a non-array value.` };
737
+ return `${this.name(id)}.${this.field(id, member.name)}`;
738
+ }
739
+ if (type.kind === "string" && value.kind === "string") {
740
+ const delimiter = type.encoding === "utf16" ? '"' : "'";
741
+ return `${delimiter}${escapeString(value.value, delimiter)}${delimiter}`;
742
+ }
743
+ if (type.kind === "array" && value.kind === "array") {
744
+ return `[${value.items.map((item) => this.literal(item, type.element)).join(", ")}]`;
745
+ }
746
+ if (type.kind === "record" && value.kind === "record") {
747
+ const fields = type.fields.map((field) => {
748
+ const initial = value.fields[field.name];
749
+ if (!initial) {
750
+ throw new Error("Missing verified record initializer");
751
+ }
752
+ return `${this.field(id, field.name)} := ${this.literal(initial, field.type)}`;
753
+ });
754
+ return `(${fields.join(", ")})`;
755
+ }
756
+ if (type.kind === "duration" && value.kind === "duration") {
757
+ return `T#${BigInt(value.nanoseconds) / nanosecondsPerMillisecond}ms`;
758
+ }
759
+ if (type.kind === "calendar" && value.kind === "calendar") {
760
+ if (type.domain === "date") {
761
+ return `D#${value.value}`;
954
762
  }
955
- if (value < type.lowerBound || value >= type.lowerBound + type.length) {
956
- return {
957
- error: `${key}: index ${value} is outside ${type.lowerBound}..${type.lowerBound + type.length - 1}.`
958
- };
763
+ if (type.domain === "timeOfDay") {
764
+ return `TOD#${value.value}`;
959
765
  }
960
- segments.push({ kind: "index", value });
961
- type = types.get(type.element);
766
+ return `DT#${value.value.replace("T", "-")}`;
962
767
  }
768
+ return scalarLiteral(value, id);
963
769
  }
964
- return { key, root, segments, type };
965
770
  }
966
- function iecSpelling(type, types) {
967
- if (type.kind === "bool" || type.kind === "integer" || type.kind === "bits" || type.kind === "float" || type.kind === "duration" || type.kind === "calendar") {
968
- return type.id;
771
+
772
+ // packages/compiler/src/codesys/global-names.ts
773
+ var planGlobalNames = (core, programNames = {}) => {
774
+ const names = new Names;
775
+ for (const name of Object.values(programNames)) {
776
+ names.reserve(name);
969
777
  }
970
- if (type.kind !== "array") {
971
- return;
778
+ const typeMap = new Map(core.types.map((type) => [type.id, type]));
779
+ const blockNames = new Map(core.blocks.map((block) => [
780
+ block.id,
781
+ block.standard ? standardBlocks[block.standard].native : names.allocateObject("FB", block.name)
782
+ ]));
783
+ for (const name of blockNames.values()) {
784
+ names.reserve(name);
972
785
  }
973
- const element = iecSpelling(types.get(type.element), types);
974
- const upper = type.lowerBound + type.length - 1;
975
- return element && !element.startsWith("ARRAY") ? `ARRAY[${type.lowerBound}..${upper}] OF ${element}` : undefined;
976
- }
977
- function ioTargets(core) {
978
- const types = new Map(core.types.map((type) => [type.id, type]));
979
- const targets = [];
980
- const add = (key, type) => {
981
- const layout = ioLayout(iecSpelling(type, types) ?? "");
982
- if (layout) {
983
- targets.push({ key, layout });
984
- }
985
- };
986
- const visit = (key, type) => {
987
- add(key, type);
988
- if (type.kind === "record") {
989
- for (const field of type.fields) {
990
- visit(`${key}.${field.name}`, types.get(field.type));
991
- }
992
- }
993
- if (type.kind === "array") {
994
- visit(`${key}[\${number}]`, types.get(type.element));
786
+ const targetTypes = new CodesysTypes(typeMap, names, blockNames);
787
+ const { globalLists, retainedVariables } = storageLayout(core);
788
+ const hasExports = (group) => group.variables.some((variable) => variable.exported && !variable.exposure);
789
+ const globals = globalLists.map((group) => {
790
+ const splitByStorage = globalLists.some((other) => other.module === group.module && other.kind !== group.kind && hasExports(other));
791
+ const name = hasExports(group) ? names.allocate(pascalCase(splitByStorage ? `${group.module}-${group.kind}` : group.module)) : names.allocateObject("GVL", `${group.module}_${group.kind}`);
792
+ const fields = new Names;
793
+ for (const name of blockNames.values()) {
794
+ fields.reserve(name);
995
795
  }
796
+ return {
797
+ ...group,
798
+ name,
799
+ fields: new Map(group.variables.map((item) => [item.id, fields.allocate(item.name)]))
800
+ };
801
+ });
802
+ return {
803
+ names,
804
+ typeMap,
805
+ blockNames,
806
+ targetTypes,
807
+ globals,
808
+ retainedVariables
996
809
  };
997
- for (const variable of core.variables) {
998
- if (variable.storage === "input" || variable.storage === "output") {
999
- add(variable.name, types.get(variable.type));
1000
- } else if (variable.storage === "module") {
1001
- visit(`${moduleName(variable)}.${variable.name}`, types.get(variable.type));
1002
- }
1003
- }
1004
- return targets;
1005
- }
1006
-
1007
- // packages/compiler/src/codesys/symbols.ts
1008
- import {
1009
- standardBlocks as standardBlocks2
1010
- } from "@tsplc/compiler/ir";
1011
-
1012
- // packages/compiler/src/codesys/global-names.ts
1013
- import { standardBlocks } from "@tsplc/compiler/ir";
1014
-
1015
- // packages/compiler/src/codesys/types.ts
1016
- import { instancedBlock as instancedBlock4, nanosecondsPerMillisecond as nanosecondsPerMillisecond2 } from "@tsplc/compiler/ir";
1017
- import { escapeString } from "@tsplc/iec/st";
810
+ };
1018
811
 
1019
- // packages/compiler/src/codesys/numeric.ts
812
+ // packages/compiler/src/codesys/task-access.ts
1020
813
  import {
1021
- integerRange,
1022
- integerType,
1023
- nestedBodies as nestedBodies3,
1024
- pathIndexes,
814
+ instancedBlock as instancedBlock3,
815
+ nanosecondsPerMillisecond as nanosecondsPerMillisecond2,
816
+ nestedBodies as nestedBodies2,
1025
817
  statementExpressions as statementExpressions2,
1026
818
  subexpressions as subexpressions2
1027
819
  } from "@tsplc/compiler/ir";
1028
- import {
1029
- floatMaximum,
1030
- isElementary
1031
- } from "@tsplc/iec/arithmetic";
1032
- var elementaryNames = {
1033
- sqrt: "SQRT",
1034
- ln: "LN",
1035
- log10: "LOG",
1036
- exp: "EXP",
1037
- sin: "SIN",
1038
- cos: "COS",
1039
- tan: "TAN",
1040
- asin: "ASIN",
1041
- acos: "ACOS",
1042
- atan: "ATAN"
1043
- };
1044
- var operatorTokens = {
1045
- add: "+",
1046
- subtract: "-",
1047
- multiply: "*",
1048
- divide: "/",
1049
- remainder: "MOD",
1050
- equal: "=",
1051
- notEqual: "<>",
1052
- less: "<",
1053
- lessEqual: "<=",
1054
- greater: ">",
1055
- greaterEqual: ">=",
1056
- bitAnd: "AND",
1057
- bitOr: "OR",
1058
- bitXor: "XOR"
1059
- };
1060
- function scalarLiteral(value, type) {
1061
- if (value.kind === "bool") {
1062
- return value.value ? "TRUE" : "FALSE";
1063
- }
1064
- if (value.kind === "integer") {
1065
- return `${type}#${value.value}`;
1066
- }
1067
- if (value.kind === "float") {
1068
- const text = Object.is(value.value, -0) ? "-0.0" : String(value.value).replace(/e/i, "E");
1069
- return `${type}#${text}`;
820
+ var variablesById = (core) => new Map([
821
+ ...core.variables,
822
+ ...core.functions.flatMap((fn) => [...fn.parameters, ...fn.locals]),
823
+ ...core.blocks.flatMap((block) => [
824
+ ...block.inputs,
825
+ ...block.outputs,
826
+ ...block.state,
827
+ ...block.locals
828
+ ])
829
+ ].map((variable) => [variable.id, variable]));
830
+ function routineTasks(core, deployment) {
831
+ const tasks = new Map;
832
+ const types = new Map(core.types.map((type) => [type.id, type]));
833
+ const routines = new Map([...core.functions, ...core.blocks].map((routine) => [routine.id, routine]));
834
+ const variables = variablesById(core);
835
+ const programs = new Map(core.programs.map((program) => [program.name, program]));
836
+ for (const task of deployment.tasks) {
837
+ for (const name of task.programs) {
838
+ const seen = new Set;
839
+ const visit = (id) => {
840
+ if (seen.has(id)) {
841
+ return;
842
+ }
843
+ seen.add(id);
844
+ tasks.set(id, tasks.has(id) && tasks.get(id) !== task.name ? undefined : task.name);
845
+ const inspect = (items) => {
846
+ for (const item of items) {
847
+ if (item.kind === "invoke") {
848
+ visit(item.function);
849
+ }
850
+ if (item.kind === "blockUpdate") {
851
+ const block = instancedBlock3(variables.get(item.instance).type, types);
852
+ if (block) {
853
+ visit(block.block);
854
+ }
855
+ }
856
+ for (const body of nestedBodies2(item)) {
857
+ inspect(body);
858
+ }
859
+ }
860
+ };
861
+ inspect(routines.get(id)?.body ?? []);
862
+ };
863
+ visit(programs.get(name).entry);
864
+ }
1070
865
  }
1071
- throw new Error("Expected verified scalar constant");
866
+ return tasks;
1072
867
  }
1073
-
1074
- class NumericLowering {
1075
- types;
1076
- allocate;
1077
- objects = [];
1078
- helpers = new Map;
1079
- constructor(types, allocate) {
1080
- this.types = types;
1081
- this.allocate = allocate;
1082
- }
1083
- prepare(value) {
1084
- for (const operand of subexpressions2(value)) {
1085
- this.prepare(operand);
1086
- }
1087
- if (value.kind === "binary" && value.policy) {
1088
- this.arithmetic(value.type, value.operator, value.policy);
1089
- }
1090
- if (value.kind === "convert" && value.policy === "saturate") {
1091
- this.saturation(value.operand.type, value.type);
868
+ function schedulePrograms(core, tasks, report) {
869
+ const background = new Map;
870
+ for (const program of core.programs) {
871
+ if (!program.background) {
872
+ continue;
1092
873
  }
1093
- if (value.kind === "unary" && value.operator === "truncate") {
1094
- this.truncation(value.type);
874
+ const { priority, intervalNanoseconds } = program.background;
875
+ const name = `TsplcBackground_${priority}_${BigInt(intervalNanoseconds) / nanosecondsPerMillisecond2}`;
876
+ const existing = background.get(name);
877
+ if (existing) {
878
+ existing.programs.push(program.name);
879
+ continue;
1095
880
  }
881
+ background.set(name, {
882
+ name,
883
+ priority,
884
+ intervalNanoseconds,
885
+ programs: [program.name]
886
+ });
1096
887
  }
1097
- prepareStatements(items) {
1098
- for (const item of items) {
1099
- const values = item.kind === "assign" ? [item.value, ...pathIndexes(item.path)] : statementExpressions2(item);
1100
- for (const value of values) {
1101
- this.prepare(value);
888
+ return appendContinuations(core, [...tasks, ...background.values()], report);
889
+ }
890
+ function taskStorageOwnership(core, report) {
891
+ const owners = new Map;
892
+ const globals = new Map(core.variables.map((item) => [item.id, item]));
893
+ const functions = new Map(core.functions.map((item) => [item.id, item]));
894
+ const blocks = new Map(core.blocks.map((block) => [block.id, block.runtime?.kind]));
895
+ const runtimes = new Map(core.types.flatMap((type) => type.kind === "block" ? [[type.id, blocks.get(type.block)]] : []));
896
+ return (task, program) => {
897
+ const fn = functions.get(program.entry);
898
+ if (!fn) {
899
+ throw new Error("Verified core has a missing entry.");
900
+ }
901
+ const worker = program.background?.worker;
902
+ const host = worker && core.variables.find((item) => item.name === worker && item.span.file === fn.span.file && runtimes.get(item.type) === "backgroundHost");
903
+ for (const id of accessedStorage(fn, core, host ? host.id : undefined)) {
904
+ const item = globals.get(id);
905
+ if (!item || item.storage === "constant" || runtimes.get(item.type) === "mailbox") {
906
+ continue;
1102
907
  }
1103
- for (const body of nestedBodies3(item)) {
1104
- this.prepareStatements(body);
908
+ const ownsWorker = worker === item.name && item.span.file === fn.span.file;
909
+ if (program.background && (!ownsWorker || host && item.id === host.id)) {
910
+ report(`Background task ${program.name} accesses scan-owned storage ${item.name}; pass value snapshots through the mailbox.`, item.span);
911
+ }
912
+ const owner = owners.get(id);
913
+ if (owner && owner !== task) {
914
+ report(`Storage ${item.name} is shared across cyclic tasks ${owner} and ${task}.`, item.span);
1105
915
  }
916
+ owners.set(id, task);
1106
917
  }
918
+ };
919
+ }
920
+ var buildModuleTables = (core) => ({
921
+ functions: new Map(core.functions.map((item) => [item.id, item])),
922
+ blocks: new Map(core.blocks.map((item) => [item.id, item])),
923
+ types: new Map(core.types.map((item) => [item.id, item])),
924
+ variables: variablesById(core)
925
+ });
926
+ var builtTables = new WeakMap;
927
+ var moduleTables = (core) => {
928
+ const known = builtTables.get(core);
929
+ if (known) {
930
+ return known;
1107
931
  }
1108
- render(value, operands) {
1109
- if (value.kind === "convert") {
1110
- return value.policy === "saturate" ? `${this.saturation(value.operand.type, value.type)}(${operands[0]})` : `TO_${value.type}(${operands[0]})`;
932
+ const tables = buildModuleTables(core);
933
+ builtTables.set(core, tables);
934
+ return tables;
935
+ };
936
+ function accessedStorage(fn, core, scheduledHost) {
937
+ const scheduledCall = fn.body.find((item) => item.kind === "invoke" && item.instance === scheduledHost);
938
+ const result = new Set;
939
+ const seen = new Set;
940
+ const { functions, blocks, types, variables } = moduleTables(core);
941
+ const expression = (value) => {
942
+ if (value.kind === "load") {
943
+ result.add(value.root);
1111
944
  }
1112
- if (value.kind === "unary") {
1113
- if (value.operator === "timeToMilliseconds") {
1114
- return `TIME_TO_UDINT(${operands[0]})`;
945
+ if (value.kind === "borrow") {
946
+ result.add(value.place.root);
947
+ }
948
+ subexpressions2(value).forEach(expression);
949
+ };
950
+ const body = (items) => {
951
+ for (const item of items) {
952
+ if (item.kind === "assign") {
953
+ result.add(item.root);
1115
954
  }
1116
- if (value.operator === "clock") {
1117
- return "TO_DINT(TIME_TO_UDINT(TIME()))";
955
+ if (item.kind === "invoke" && item.instance && item !== scheduledCall) {
956
+ result.add(item.instance);
1118
957
  }
1119
- if (isElementary(value.operator)) {
1120
- return `${elementaryNames[value.operator]}(${operands[0]})`;
958
+ if (item.kind === "blockUpdate") {
959
+ result.add(item.instance);
1121
960
  }
1122
- if (value.operator === "truncate") {
1123
- return `${this.truncation(value.type)}(${operands[0]})`;
961
+ statementExpressions2(item).forEach(expression);
962
+ if (item.kind === "for") {
963
+ result.add(item.counter);
1124
964
  }
1125
- return value.operator === "not" ? `(NOT ${operands[0]})` : `TO_${value.type}(${value.operator === "negate" ? "-" : "NOT "}${operands[0]})`;
1126
- }
1127
- if (value.kind !== "binary") {
1128
- throw new Error("Expected numeric operation");
1129
- }
1130
- if (value.policy) {
1131
- return `${this.arithmetic(value.type, value.operator, value.policy)}(${operands.join(", ")})`;
965
+ if (item.kind === "invoke") {
966
+ if (item.destination) {
967
+ result.add(item.destination);
968
+ }
969
+ const called = functions.get(item.function);
970
+ if (called && !seen.has(called.id)) {
971
+ seen.add(called.id);
972
+ body(called.body);
973
+ }
974
+ }
975
+ if (item.kind === "blockUpdate") {
976
+ const variable = variables.get(item.instance);
977
+ if (!variable) {
978
+ throw new Error("Missing verified instance during task planning.");
979
+ }
980
+ const type = instancedBlock3(variable.type, types);
981
+ const block = type && blocks.get(type.block);
982
+ if (block && !seen.has(block.id)) {
983
+ seen.add(block.id);
984
+ body(block.body);
985
+ }
986
+ }
987
+ nestedBodies2(item).forEach(body);
1132
988
  }
1133
- if (value.operator === "power") {
1134
- return `EXPT(${operands.join(", ")})`;
989
+ };
990
+ seen.add(fn.id);
991
+ body(fn.body);
992
+ return result;
993
+ }
994
+ function appendContinuations(core, tasks, report) {
995
+ const continuations = core.programs.flatMap((program) => program.continuation ? [{ name: program.name, scope: program.continuation }] : []);
996
+ if (!continuations.length) {
997
+ return tasks;
998
+ }
999
+ const programs = new Map(core.programs.map((program) => [program.name, program]));
1000
+ const functions = new Map(core.functions.map((routine) => [routine.id, routine]));
1001
+ const placements = tasks.map((task) => {
1002
+ const roots = new Set;
1003
+ for (const name of task.programs) {
1004
+ const program = programs.get(name);
1005
+ if (!program || program.background) {
1006
+ continue;
1007
+ }
1008
+ const entry = functions.get(program.entry);
1009
+ if (entry) {
1010
+ for (const id of accessedStorage(entry, core)) {
1011
+ roots.add(id);
1012
+ }
1013
+ }
1135
1014
  }
1136
- if (value.operator === "shiftLeft" || value.operator === "shiftRight") {
1137
- const shift = value.operator === "shiftLeft" ? "SHL" : "SHR";
1138
- return `TO_${value.type}(${shift}(${operands.join(", ")}))`;
1015
+ return { task, roots, additions: [] };
1016
+ });
1017
+ for (const { name, scope } of continuations) {
1018
+ const root = core.variables.find((variable) => variable.name === scope.instance && variable.span.file === scope.file);
1019
+ if (!root) {
1020
+ report(`Missing continuation owner ${scope.instance}.`);
1021
+ continue;
1139
1022
  }
1140
- const token = operatorTokens[value.operator];
1141
- if (!token) {
1142
- throw new Error("Boolean short-circuit operation was not normalized");
1023
+ const owners = placements.filter(({ roots }) => roots.has(root.id));
1024
+ const [owner] = owners;
1025
+ if (!owner || owners.length !== 1) {
1026
+ report(`Continuation owner ${scope.instance} must belong to exactly one caller task.`, root.span);
1027
+ continue;
1143
1028
  }
1144
- const text = value.operator === "remainder" ? `(${operands[0]} - (${operands[0]} / ${operands[1]}) * ${operands[1]})` : `(${operands[0]} ${token} ${operands[1]})`;
1145
- return value.type === "BOOL" ? text : `TO_${value.type}(${text})`;
1029
+ owner.additions.push(name);
1146
1030
  }
1147
- helper(key, type, inputs, body, locals = "") {
1148
- const existing = this.helpers.get(key);
1149
- if (existing) {
1150
- return existing;
1031
+ return placements.map(({ task, additions }) => ({
1032
+ ...task,
1033
+ programs: task.programs.concat(additions)
1034
+ }));
1035
+ }
1036
+
1037
+ // packages/compiler/src/codesys/symbols.ts
1038
+ function required2(value) {
1039
+ if (value === undefined) {
1040
+ throw new Error("Missing verified CODESYS symbol.");
1041
+ }
1042
+ return value;
1043
+ }
1044
+ function createSymbols({ core, options }) {
1045
+ const persistent = new Set(core.variables.filter((item) => item.storage !== "constant").map((item) => item.id));
1046
+ const programRoutines = new Set;
1047
+ for (const fn of core.functions) {
1048
+ if (!fn.owner && [...accessedStorage(fn, core)].some((id) => persistent.has(id))) {
1049
+ programRoutines.add(fn.id);
1151
1050
  }
1152
- const name = this.allocate(`numeric_${key}`);
1153
- this.helpers.set(key, name);
1154
- const parameters = inputs.map(([input, inputType]) => ` ${input} : ${inputType};`).join(`
1155
- `);
1156
- const variables = locals ? `VAR
1157
- ${locals}
1158
- END_VAR
1159
- ` : "";
1160
- const declaration = `FUNCTION ${name} : ${type}
1161
- VAR_INPUT
1162
- ${parameters}
1163
- END_VAR
1164
- ${variables}`;
1165
- this.objects.push({
1166
- id: `numeric:${key}`,
1167
- kind: "function",
1168
- name,
1169
- declaration,
1170
- implementation: body(name)
1171
- });
1172
- return name;
1173
1051
  }
1174
- add64() {
1175
- return this.helper("add64", "LWORD", [
1176
- ["a", "LWORD"],
1177
- ["b", "LWORD"]
1178
- ], (name) => `x := a;
1179
- y := b;
1180
- FOR i := 1 TO 64 DO
1181
- carry := SHL(x AND y, 1);
1182
- x := x XOR y;
1183
- y := carry;
1184
- END_FOR;
1185
- ${name} := x;
1186
- `, ` x, y, carry : LWORD;
1187
- i : UINT;`);
1052
+ const globalNames = planGlobalNames(core, options.programNames);
1053
+ return {
1054
+ ...globalNames,
1055
+ blocks: new Map(core.blocks.map((block) => [block.id, block])),
1056
+ numeric: new NumericLowering(globalNames.typeMap, (label) => globalNames.names.allocate(label)),
1057
+ programRoutines,
1058
+ references: new Map,
1059
+ functionNames: new Map,
1060
+ programResults: new Map,
1061
+ mailboxLocks: new Map,
1062
+ blockFields: new Map,
1063
+ routineScopes: new Map
1064
+ };
1065
+ }
1066
+ function allocateFunctionNames(symbols, { core }) {
1067
+ const entries = new Set(core.programs.map((program) => program.entry));
1068
+ for (const fn of core.functions.filter((fn) => !fn.owner)) {
1069
+ const program = symbols.programRoutines.has(fn.id);
1070
+ const label = program && entries.has(fn.id) ? `${fn.name}_body` : fn.name;
1071
+ symbols.functionNames.set(fn.id, symbols.names.allocateObject(program ? "PRG" : "F", label));
1188
1072
  }
1189
- wrap64(operator) {
1190
- const add = this.add64();
1191
- if (operator === "add") {
1192
- return add;
1193
- }
1194
- if (operator === "subtract") {
1195
- return this.helper("subtract64", "LWORD", [
1196
- ["a", "LWORD"],
1197
- ["b", "LWORD"]
1198
- ], (name) => `${name} := ${add}(a, ${add}(NOT b, LWORD#1));
1199
- `);
1073
+ }
1074
+ var instrumentationFieldTypes = {
1075
+ busy: "BOOL",
1076
+ step: "UINT",
1077
+ startedAt: "UDINT",
1078
+ job: "UDINT",
1079
+ sequence: "UDINT"
1080
+ };
1081
+ function allocateBlockFields(symbols, instrumentation, plan, objects) {
1082
+ const { core } = plan;
1083
+ const { functionNames, blockNames, blockFields } = symbols;
1084
+ for (const block of core.blocks) {
1085
+ const fields = new Names;
1086
+ const mapped = new Map;
1087
+ for (const object of objects) {
1088
+ fields.reserve(object.name);
1200
1089
  }
1201
- if (operator !== "multiply") {
1202
- throw new Error("Unsupported verified wrapping operation");
1090
+ fields.reserve(instrumentation.global);
1091
+ for (const objectName of [
1092
+ ...core.functions.filter((fn) => !fn.owner).map((fn) => required2(functionNames.get(fn.id))),
1093
+ ...blockNames.values()
1094
+ ]) {
1095
+ fields.reserve(objectName);
1203
1096
  }
1204
- return this.helper("multiply64", "LWORD", [
1205
- ["a", "LWORD"],
1206
- ["b", "LWORD"]
1207
- ], (name) => `x := a;
1208
- y := b;
1209
- result := LWORD#0;
1210
- FOR i := 1 TO 64 DO
1211
- IF (y AND LWORD#1) <> LWORD#0 THEN
1212
- result := ${add}(result, x);
1213
- END_IF;
1214
- x := SHL(x, 1);
1215
- y := SHR(y, 1);
1216
- END_FOR;
1217
- ${name} := result;
1218
- `, ` x, y, result : LWORD;
1219
- i : UINT;`);
1220
- }
1221
- arithmetic(typeId, operator, policy) {
1222
- const type = this.types.get(typeId);
1223
- if (type?.kind !== "integer") {
1224
- throw new Error("Expected verified integer arithmetic");
1097
+ for (const method of core.functions.filter((fn) => fn.owner?.block === block.id)) {
1098
+ functionNames.set(method.id, fields.allocate(method.name));
1225
1099
  }
1226
- const token = operatorTokens[operator];
1227
- if (!token) {
1228
- throw new Error("Expected verified integer arithmetic");
1100
+ const native = block.standard && standardBlocks2[block.standard];
1101
+ for (const item of [...block.inputs, ...block.outputs, ...block.state]) {
1102
+ mapped.set(item.id, native ? required2([...native.inputs, ...native.outputs].find(([name]) => name === item.name))[1] : fields.allocate(item.name));
1229
1103
  }
1230
- const key = `${policy}_${operator}_${typeId}`;
1231
- if (policy === "wrap") {
1232
- if (type.bits === 64) {
1233
- const operation = this.wrap64(operator);
1234
- return this.helper(key, typeId, [
1235
- ["a", typeId],
1236
- ["b", typeId]
1237
- ], (name) => `${name} := LWORD_TO_${typeId}(${operation}(${typeId}_TO_LWORD(a), ${typeId}_TO_LWORD(b)));
1238
- `);
1239
- }
1240
- const wide = !type.signed && operator !== "subtract" ? "ULINT" : "LINT";
1241
- return this.helper(key, typeId, [
1242
- ["a", typeId],
1243
- ["b", typeId]
1244
- ], (name) => `${name} := ${wide}_TO_${typeId}(${typeId}_TO_${wide}(a) ${token} ${typeId}_TO_${wide}(b));
1245
- `);
1104
+ if (block.runtime?.kind === "mailbox") {
1105
+ symbols.mailboxLocks.set(block.id, fields.allocate("plc_mailbox_lock"));
1246
1106
  }
1247
- const [minimum, maximum] = integerRange(type);
1248
- const min = `${typeId}#${minimum}`;
1249
- const max = `${typeId}#${maximum}`;
1250
- const zero = `${typeId}#0`;
1251
- return this.helper(key, typeId, [
1252
- ["a", typeId],
1253
- ["b", typeId]
1254
- ], (name) => {
1255
- const clamp = (condition, endpoint, depth = "") => `${depth}IF ${condition} THEN
1256
- ${depth} ${name} := ${endpoint};
1257
- ${depth} RETURN;
1258
- ${depth}END_IF;
1259
- `;
1260
- const guard = () => {
1261
- if (!type.signed) {
1262
- if (operator === "add") {
1263
- return clamp(`a > ${max} - b`, max);
1264
- }
1265
- if (operator === "subtract") {
1266
- return clamp("a < b", zero);
1267
- }
1268
- return `IF b <> ${zero} THEN
1269
- ${clamp(`a > ${max} / b`, max, " ")}END_IF;
1270
- `;
1271
- }
1272
- if (operator === "add") {
1273
- return `IF b > ${zero} THEN
1274
- ${clamp(`a > ${max} - b`, max, " ")}ELSIF b < ${zero} THEN
1275
- ${clamp(`a < ${min} - b`, min, " ")}END_IF;
1276
- `;
1277
- }
1278
- if (operator === "subtract") {
1279
- return `IF b < ${zero} THEN
1280
- ${clamp(`a > ${max} + b`, max, " ")}ELSIF b > ${zero} THEN
1281
- ${clamp(`a < ${min} + b`, min, " ")}END_IF;
1282
- `;
1107
+ blockFields.set(block.id, mapped);
1108
+ const settings = plan.project.debug;
1109
+ const stepped = instrumentation.analysis.jobSites.has(block.id) || plan.telemetry?.failures.has(block.id);
1110
+ const tracked = Boolean(block.job && (settings?.jobs || stepped));
1111
+ const carries = settings?.jobs && instrumentation.analysis.carriers.has(block.id);
1112
+ if (tracked || carries) {
1113
+ instrumentation.fields.set(block.id, {
1114
+ ...tracked && {
1115
+ busy: fields.allocate("tsplcBusy"),
1116
+ track: fields.allocate("TsplcTrack")
1117
+ },
1118
+ ...tracked && settings?.jobs && { startedAt: fields.allocate("startedAt") },
1119
+ ...stepped && { step: fields.allocate("tsplcStep") },
1120
+ ...carries && { job: fields.allocate("requestJob") },
1121
+ ...carries && block.runtime?.kind === "http" && {
1122
+ sequence: fields.allocate("sequence")
1283
1123
  }
1284
- return clamp(`a = ${zero}`, zero) + clamp(`b = ${zero}`, zero) + `IF a > ${zero} THEN
1285
- IF b > ${zero} THEN
1286
- ${clamp(`a > ${max} / b`, max, " ")} ELSE
1287
- ${clamp(`b < ${min} / a`, min, " ")} END_IF;
1288
- ELSE
1289
- IF b > ${zero} THEN
1290
- ${clamp(`a < ${min} / b`, min, " ")} ELSE
1291
- ${clamp(`a < ${max} / b`, max, " ")} END_IF;
1292
- END_IF;
1293
- `;
1294
- };
1295
- return `${guard()}${name} := a ${token} b;
1296
- `;
1297
- });
1124
+ });
1125
+ }
1298
1126
  }
1299
- truncation(typeId) {
1300
- const type = this.types.get(typeId);
1301
- if (type?.kind !== "float") {
1302
- throw new Error("Expected verified float truncation");
1127
+ }
1128
+ function allocateRoutineScope(symbols, instrumentation, objects, fn) {
1129
+ const block = "inputs" in fn ? fn : undefined;
1130
+ const owner = block ?? ("owner" in fn && fn.owner ? symbols.blocks.get(fn.owner.block) : undefined);
1131
+ const names = new Names;
1132
+ const references = new Map;
1133
+ for (const object of objects) {
1134
+ names.reserve(object.name);
1135
+ }
1136
+ names.reserve(instrumentation.global);
1137
+ for (const name of [
1138
+ ...symbols.functionNames.values(),
1139
+ ...symbols.blockNames.values()
1140
+ ]) {
1141
+ names.reserve(name);
1142
+ }
1143
+ if (symbols.programRoutines.has(fn.id) && "parameters" in fn && fn.result) {
1144
+ symbols.programResults.set(fn.id, names.allocate("plc_result"));
1145
+ }
1146
+ if (owner) {
1147
+ for (const item of [...owner.outputs, ...owner.state]) {
1148
+ const name = required2(required2(symbols.blockFields.get(owner.id)).get(item.id));
1149
+ names.reserve(name);
1150
+ references.set(item.id, name);
1303
1151
  }
1304
- const whole = scalarLiteral({ kind: "float", value: 2 ** (type.bits === 32 ? 23 : 52) }, typeId);
1305
- return this.helper(`truncate_${typeId}`, typeId, [["value", typeId]], (name) => `IF ABS(value) >= ${whole} THEN
1306
- ${name} := value;
1307
- RETURN;
1308
- END_IF;
1309
- nearest := TO_LINT(value);
1310
- IF value >= 0 AND TO_${typeId}(nearest) > value THEN
1311
- nearest := nearest - 1;
1312
- ELSIF value < 0 AND TO_${typeId}(nearest) < value THEN
1313
- nearest := nearest + 1;
1314
- END_IF;
1315
- ${name} := TO_${typeId}(nearest);
1316
- `, " nearest : LINT;");
1317
1152
  }
1318
- saturation(sourceId, targetId) {
1319
- const source = this.types.get(sourceId);
1320
- const target = this.types.get(targetId);
1321
- if (source?.kind === "float" && target?.kind === "float") {
1322
- if (source.bits <= target.bits) {
1323
- return `TO_${targetId}`;
1324
- }
1325
- const maximum = floatMaximum(target);
1326
- const literal = (value, type) => scalarLiteral({ kind: "float", value }, type);
1327
- return this.helper(`saturate_${sourceId}_${targetId}`, targetId, [["value", sourceId]], (name) => `IF value < ${literal(-maximum, sourceId)} THEN
1328
- ${name} := ${literal(-maximum, targetId)};
1329
- RETURN;
1330
- END_IF;
1331
- IF value > ${literal(maximum, sourceId)} THEN
1332
- ${name} := ${literal(maximum, targetId)};
1333
- RETURN;
1334
- END_IF;
1335
- ${name} := TO_${targetId}(value);
1336
- `);
1153
+ for (const item of "parameters" in fn ? fn.parameters : fn.inputs) {
1154
+ const name = block ? required2(required2(symbols.blockFields.get(block.id)).get(item.id)) : names.allocate(item.name);
1155
+ names.reserve(name);
1156
+ references.set(item.id, name);
1157
+ }
1158
+ for (const item of fn.locals) {
1159
+ references.set(item.id, names.allocate(item.name));
1160
+ }
1161
+ symbols.routineScopes.set(fn.id, { names, references });
1162
+ }
1163
+
1164
+ // packages/compiler/src/codesys/programs.ts
1165
+ function emitScanProgram({ plan, symbols, instrumentation }, ioChannels, program) {
1166
+ const { core, options } = plan;
1167
+ const { names, functionNames } = symbols;
1168
+ const explicit = options.programNames && Object.hasOwn(options.programNames, program.name) ? options.programNames[program.name] : undefined;
1169
+ const name = explicit ?? names.allocateObject("PRG", program.name);
1170
+ const fn = required2(core.functions.find((item) => item.id === program.entry));
1171
+ const used = accessedStorage(fn, core);
1172
+ const channels = ioChannels.filter((channel) => used.has(channel.root));
1173
+ const stateful = symbols.programRoutines.has(program.entry);
1174
+ const call = `${functionNames.get(program.entry)}();`;
1175
+ const task = plan.deployment.tasks.find((item) => item.programs[0] === program.name);
1176
+ const ring = task && instrumentation.rings.get(task.name);
1177
+ const clock = task && instrumentation.scanClocks.get(task.name);
1178
+ const lines = [
1179
+ ...ring ? [`${instrumentation.global}.${ring}();`] : [],
1180
+ ...clock ? [`${clock} := TO_DINT(TIME_TO_UDINT(TIME()));`] : [],
1181
+ ...channels.filter((channel) => channel.input).map(({ target, wire, inverted }) => `${target} := ${inverted ? "NOT " : ""}${wire};`),
1182
+ stateful ? call : `plc_discard := ${call}`,
1183
+ ...channels.filter((channel) => !channel.input).map(({ target, wire }) => `${wire} := ${target};`)
1184
+ ];
1185
+ return {
1186
+ id: program.id,
1187
+ kind: "program",
1188
+ name,
1189
+ declaration: stateful ? `PROGRAM ${name}
1190
+ ` : `PROGRAM ${name}
1191
+ VAR
1192
+ plc_discard : BOOL;
1193
+ END_VAR
1194
+ `,
1195
+ implementation: `${lines.join(`
1196
+ `)}
1197
+ `
1198
+ };
1199
+ }
1200
+ var taskPrograms = (plan, task) => {
1201
+ const programs = new Map(plan.core.programs.map((program) => [program.name, program]));
1202
+ const generated = (name) => {
1203
+ const program = programs.get(name);
1204
+ return Boolean(program?.continuation || program?.background);
1205
+ };
1206
+ const background = task.programs.every((name) => programs.get(name)?.background);
1207
+ return {
1208
+ configured: task.programs.filter((name) => !generated(name)),
1209
+ wrapped: task.programs.filter(generated),
1210
+ wrapper: {
1211
+ id: `tsplc:task:${task.name}`,
1212
+ label: background ? task.name : `TsplcContinuations_${task.name}`
1337
1213
  }
1338
- if (!source || !target || !integerType(source) || !integerType(target)) {
1339
- throw new Error("Expected verified integer saturation");
1214
+ };
1215
+ };
1216
+ function emitTaskWrappers({ plan, symbols }, objects) {
1217
+ const programObjects = new Map(plan.core.programs.map((program) => [
1218
+ program.name,
1219
+ required2(objects.find((object) => object.id === program.id && object.kind === "program"))
1220
+ ]));
1221
+ return plan.deployment.tasks.map((task) => {
1222
+ const { wrapped, wrapper } = taskPrograms(plan, task);
1223
+ const name = symbols.names.allocateObject("PRG", wrapper.label);
1224
+ const calls = wrapped.map((program) => `${required2(programObjects.get(program)).name}();`);
1225
+ return {
1226
+ id: wrapper.id,
1227
+ kind: "program",
1228
+ name,
1229
+ declaration: `PROGRAM ${name}
1230
+ `,
1231
+ implementation: calls.length ? `${calls.join(`
1232
+ `)}
1233
+ ` : `;
1234
+ `
1235
+ };
1236
+ });
1237
+ }
1238
+
1239
+ // packages/compiler/src/codesys/engineering.ts
1240
+ var engineeringSchema = z.strictObject({
1241
+ kind: z.literal("v3.5"),
1242
+ build: engineeringBuildSchema.optional()
1243
+ });
1244
+ function codesysBuildConfig(plan, bundle, paths) {
1245
+ const settings = plan.options.engineering.build;
1246
+ if (!settings) {
1247
+ throw new Error("CODESYS build requires engineering.build settings (codesys installation and template). Configure them or use --emit-only.");
1248
+ }
1249
+ const programs = new Map(plan.core.programs.map((program) => {
1250
+ const matches = bundle.objects.filter((object) => object.id === program.id && object.kind === "program");
1251
+ const generated = matches[0];
1252
+ if (matches.length !== 1 || !generated) {
1253
+ throw new Error(`Generated bundle must contain one PROGRAM object for ${program.name}.`);
1340
1254
  }
1341
- const [fromMin, fromMax] = integerRange(source);
1342
- const [toMin, toMax] = integerRange(target);
1343
- return this.helper(`saturate_${sourceId}_${targetId}`, targetId, [["value", sourceId]], (name) => {
1344
- let body = "";
1345
- if (fromMin < toMin) {
1346
- body += `IF value < ${sourceId}#${toMin} THEN
1347
- ${name} := ${targetId}#${toMin};
1348
- RETURN;
1349
- END_IF;
1350
- `;
1351
- }
1352
- if (fromMax > toMax) {
1353
- body += `IF value > ${sourceId}#${toMax} THEN
1354
- ${name} := ${targetId}#${toMax};
1355
- RETURN;
1356
- END_IF;
1357
- `;
1358
- }
1359
- return `${body}${name} := TO_${targetId}(value);
1360
- `;
1361
- });
1255
+ return [program.name, generated];
1256
+ }));
1257
+ const tasks = plan.deployment.tasks.map((task) => {
1258
+ const { configured, wrapper } = taskPrograms(plan, task);
1259
+ const wrapperObject = bundle.objects.find((object) => object.id === wrapper.id && object.kind === "program");
1260
+ if (!wrapperObject) {
1261
+ throw new Error(`Generated bundle has no wrapper PROGRAM for ${task.name}.`);
1262
+ }
1263
+ return {
1264
+ ...task,
1265
+ programs: [
1266
+ ...configured.map((name) => {
1267
+ const program = programs.get(name);
1268
+ if (!program) {
1269
+ throw new Error(`Task ${task.name} references a missing generated PROGRAM ${name}.`);
1270
+ }
1271
+ return program.name;
1272
+ }),
1273
+ wrapperObject.name
1274
+ ]
1275
+ };
1276
+ });
1277
+ const first = plan.core.programs[0];
1278
+ const entry = first && programs.get(first.name);
1279
+ if (!entry) {
1280
+ throw new Error("CODESYS build requires a generated PROGRAM entry.");
1362
1281
  }
1282
+ const sourceDir = resolve(paths.sourceDir);
1283
+ return resolveConfig({
1284
+ ...settings,
1285
+ libraryReferences: [
1286
+ ...settings.libraryReferences ?? [],
1287
+ ...Object.values(plan.http).some((endpoint) => endpoint.transport !== "opcua") ? ["Net Base Services, 4.0.0.0 (CODESYS)"] : [],
1288
+ ...Object.values(plan.http).some((endpoint) => endpoint.tls) ? ["CmpX509Cert Implementation, 3.5.22.0 (System)"] : []
1289
+ ],
1290
+ ...paths.libraries ? { libraries: paths.libraries } : {},
1291
+ ...paths.deviceTree ? { deviceTree: paths.deviceTree } : {},
1292
+ ...paths.controller ? { controller: paths.controller } : {},
1293
+ sourceDir,
1294
+ entry: resolve(sourceDir, entry.sourcePath ?? `${entry.name}/declaration.st`),
1295
+ outDir: resolve(paths.outDir),
1296
+ tasks
1297
+ }, paths.configFile);
1298
+ }
1299
+ async function buildCodesys(plan, bundle, paths, options = {}) {
1300
+ return buildProject(codesysBuildConfig(plan, bundle, paths), options);
1363
1301
  }
1364
1302
 
1365
- // packages/compiler/src/codesys/types.ts
1366
- var sourceTypeName = (id) => id.slice(id.lastIndexOf(":") + 1);
1367
- var stringTypeName = (type) => type.encoding === "utf8" ? "STRING" : "WSTRING";
1368
- var stEscapes = new Map([
1369
- ["$", "$$"],
1370
- ["'", "$'"],
1371
- ["\r", "$R"],
1372
- [`
1373
- `, "$N"]
1374
- ]);
1375
- var stStringLiteral = (text) => `'${[...text].map((character) => stEscapes.get(character) ?? character).join("")}'`;
1376
- var anonymousRecordId = /:\d+:record(<.*>)?$/;
1377
- var required = (value) => {
1378
- if (value === undefined) {
1379
- throw new Error("Missing verified type name");
1303
+ // packages/compiler/src/codesys/config.ts
1304
+ var addressSchema = directIoBindingSchema.extend({
1305
+ kind: z2.literal("direct"),
1306
+ mapped: z2.boolean().optional()
1307
+ });
1308
+ var iecNames = z2.record(z2.string().min(1), z2.string().refine(isIecIdentifier, "Use a valid, non-reserved IEC identifier.")).optional();
1309
+ var optionsSchema = z2.object({
1310
+ engineering: engineeringSchema,
1311
+ http: httpOptionsSchema,
1312
+ io: z2.record(z2.string().min(1), addressSchema),
1313
+ publish: publicationSchema.default({ production: [], development: [] }),
1314
+ buildTarget: buildTargetSchema.default("production"),
1315
+ programNames: iecNames
1316
+ }).strict();
1317
+ function codesys(options) {
1318
+ return { kind: "codesys", options };
1319
+ }
1320
+ function direct(address) {
1321
+ return { kind: "direct", address };
1322
+ }
1323
+ // packages/compiler/src/codesys/emit.ts
1324
+ import { createHash as createHash2 } from "node:crypto";
1325
+
1326
+ // packages/compiler/src/codesys/explain.ts
1327
+ import {
1328
+ instancedBlock as instancedBlock7,
1329
+ nestedBodies as nestedBodies6,
1330
+ pathConditions,
1331
+ projectReconstruction,
1332
+ standardBlocks as standardBlocks4
1333
+ } from "@tsplc/compiler/ir";
1334
+ import { createExplainer } from "@tsplc/debug/explain";
1335
+ import { createPaths } from "@tsplc/debug/paths";
1336
+ import { serviceOfPath as serviceOfPath2 } from "@tsplc/server";
1337
+
1338
+ // packages/compiler/src/codesys/debug.ts
1339
+ import { directWrites, instancedBlock as instancedBlock4, nestedBodies as nestedBodies3 } from "@tsplc/compiler/ir";
1340
+ var temporary = (id) => id.includes(":temporary:");
1341
+ var constantIndex = (value) => value.kind === "constant" && value.value.kind === "integer" ? Number(value.value.value) : undefined;
1342
+ var writtenPlace = (item) => {
1343
+ if (item.kind === "assign") {
1344
+ return { root: item.root, path: item.path ?? [] };
1380
1345
  }
1381
- return value;
1346
+ return item.kind === "invoke" && item.destination ? { root: item.destination, path: [] } : undefined;
1382
1347
  };
1383
-
1384
- class CodesysTypes {
1385
- types;
1386
- objects = [];
1387
- names = new Map;
1388
- fields = new Map;
1389
- aliases = new Set;
1390
- shapes = new Map;
1391
- constructor(types, names, blockNames) {
1392
- this.types = types;
1393
- const anonymous = new Map;
1394
- for (const type of types.values()) {
1395
- const shape = this.anonymousShape(type);
1396
- const shared = shape === null ? undefined : anonymous.get(shape);
1397
- if (shared !== undefined) {
1398
- this.names.set(type.id, required(this.names.get(shared)));
1399
- this.fields.set(type.id, required(this.fields.get(shared)));
1400
- this.aliases.add(type.id);
1401
- continue;
1402
- }
1403
- if (shape !== null) {
1404
- anonymous.set(shape, type.id);
1405
- }
1406
- if (type.kind === "block") {
1407
- const name = blockNames.get(type.block);
1408
- if (!name) {
1409
- throw new Error("Missing verified block name");
1410
- }
1411
- this.names.set(type.id, name);
1412
- }
1413
- if (["record", "array", "enum", "string"].includes(type.kind)) {
1414
- const label = sourceTypeName(type.id);
1415
- if (type.kind === "record" || type.kind === "enum") {
1416
- const prefix = type.kind === "record" ? "ST" : "E";
1417
- this.names.set(type.id, names.allocateObject(prefix, label));
1418
- } else {
1419
- this.names.set(type.id, names.allocate(`T_${label}`));
1420
- }
1421
- }
1422
- if (type.kind === "record" || type.kind === "enum") {
1423
- const names = new Names;
1424
- const fields = new Map;
1425
- for (const member of type.kind === "record" ? type.fields : type.members) {
1426
- fields.set(member.name, names.allocate(member.name));
1348
+ var wholeTarget = (item) => {
1349
+ if (item.kind === "assign" && !item.path?.length) {
1350
+ return item.root;
1351
+ }
1352
+ return item.kind === "invoke" ? item.destination : undefined;
1353
+ };
1354
+ function blockInstances(core) {
1355
+ const types = new Map(core.types.map((type) => [type.id, type]));
1356
+ const blocks = new Map(core.blocks.map((block) => [block.id, block]));
1357
+ const instances = new Map(core.blocks.map((block) => [block.id, []]));
1358
+ const visit = (variable, block, path) => {
1359
+ const type = types.get(variable.type);
1360
+ const declared = type?.kind === "array" ? Array.from({ length: type.length }, (_, offset) => [
1361
+ ...path,
1362
+ { variable, index: type.lowerBound + offset }
1363
+ ]) : [[...path, { variable }]];
1364
+ for (const instance of declared) {
1365
+ instances.get(block).push(instance);
1366
+ for (const child of blocks.get(block).state) {
1367
+ const instanced = instancedBlock4(child.type, types);
1368
+ if (instanced) {
1369
+ visit(child, instanced.block, instance);
1427
1370
  }
1428
- this.fields.set(type.id, fields);
1429
- }
1430
- }
1431
- for (const type of types.values()) {
1432
- if (type.kind === "array" && instancedBlock4(type.id, types)) {
1433
- this.names.set(type.id, `ARRAY[${type.lowerBound}..${type.lowerBound + type.length - 1}] OF ${this.name(type.element)}`);
1434
1371
  }
1435
1372
  }
1436
- const emitted = new Set;
1437
- const emit = (type) => {
1438
- if (instancedBlock4(type.id, types) || !this.names.has(type.id) || this.aliases.has(type.id) || emitted.has(type.id)) {
1439
- return;
1440
- }
1441
- if (type.kind === "array") {
1442
- emit(this.type(type.element));
1443
- }
1444
- if (type.kind === "record") {
1445
- for (const field of type.fields) {
1446
- emit(this.type(field.type));
1447
- }
1448
- }
1449
- emitted.add(type.id);
1450
- const name = this.name(type.id);
1451
- const declaration = this.dutDeclaration(type, name);
1452
- this.objects.push({ id: type.id, kind: "dataType", name, declaration });
1453
- };
1454
- for (const type of types.values()) {
1455
- emit(type);
1373
+ };
1374
+ for (const variable of core.variables) {
1375
+ const instanced = instancedBlock4(variable.type, types);
1376
+ if (instanced) {
1377
+ visit(variable, instanced.block, []);
1456
1378
  }
1457
1379
  }
1458
- anonymousShape(type) {
1459
- if (type.kind !== "record" || !anonymousRecordId.test(type.id)) {
1460
- return null;
1380
+ return instances;
1381
+ }
1382
+ function storagePath(root, path = []) {
1383
+ const logical = root.storage === "input" || root.storage === "output";
1384
+ if (!logical && root.storage !== "module" && root.storage !== "instance") {
1385
+ return;
1386
+ }
1387
+ let text = logical ? root.name : `${moduleName(root)}.${root.name}`;
1388
+ for (const segment of path) {
1389
+ if (segment.kind === "field") {
1390
+ text += `.${segment.name}`;
1391
+ continue;
1461
1392
  }
1462
- const known = this.shapes.get(type.id);
1463
- if (known !== undefined) {
1464
- return known;
1393
+ const index = constantIndex(segment.value);
1394
+ if (index === undefined) {
1395
+ return;
1465
1396
  }
1466
- const shape = JSON.stringify(type.fields.map((field) => [
1467
- field.name,
1468
- this.anonymousShape(this.type(field.type)) ?? field.type
1469
- ]));
1470
- this.shapes.set(type.id, shape);
1471
- return shape;
1397
+ text += `[${index}]`;
1472
1398
  }
1473
- dutDeclaration(type, name) {
1474
- if (type.kind === "record") {
1475
- const fields = type.fields.map((field) => ` ${this.field(type.id, field.name)} : ${this.name(field.type)};`).join(`
1476
- `);
1477
- return `TYPE ${name} :
1478
- STRUCT
1479
- ${fields}
1480
- END_STRUCT
1481
- END_TYPE
1482
- `;
1399
+ return text;
1400
+ }
1401
+
1402
+ class DebugAnalysis {
1403
+ core;
1404
+ outputs;
1405
+ tasks;
1406
+ instances;
1407
+ probes = new Map;
1408
+ events = [];
1409
+ writers;
1410
+ jobSites = new Map;
1411
+ decisions = new Map;
1412
+ callSites = new Map;
1413
+ carriers = new Set;
1414
+ variables;
1415
+ types;
1416
+ routines;
1417
+ blocks;
1418
+ routineWrites = new Map;
1419
+ temporaries = new Map;
1420
+ writerSites = 0;
1421
+ constructor(core, deployment, settings, outputs) {
1422
+ this.core = core;
1423
+ this.outputs = outputs;
1424
+ this.types = new Map(core.types.map((type) => [type.id, type]));
1425
+ this.blocks = new Map(core.blocks.map((block) => [block.id, block]));
1426
+ this.routines = new Map([...core.functions, ...core.blocks].map((routine) => [
1427
+ routine.id,
1428
+ routine
1429
+ ]));
1430
+ this.variables = variablesById(core);
1431
+ this.writers = outputs.map(() => []);
1432
+ this.tasks = routineTasks(core, deployment);
1433
+ this.instances = blockInstances(core);
1434
+ this.findCarriers();
1435
+ if (!settings) {
1436
+ return;
1483
1437
  }
1484
- if (type.kind === "array") {
1485
- return `${type.index ? `{attribute 'tsplc_keyed'}
1486
- ` : ""}TYPE ${name} : ARRAY[${type.lowerBound}..${type.lowerBound + type.length - 1}] OF ${this.name(type.element)};
1487
- END_TYPE
1488
- `;
1438
+ const routines = [
1439
+ ...core.functions,
1440
+ ...core.blocks.filter((block) => !block.standard)
1441
+ ];
1442
+ for (const routine of routines) {
1443
+ this.countCalls(routine.body, 1);
1489
1444
  }
1490
- if (type.kind === "string") {
1491
- return `TYPE ${name} : ${stringTypeName(type)}(${type.capacity});
1492
- END_TYPE
1493
- `;
1445
+ for (const routine of routines) {
1446
+ this.walk(settings, routine, routine.body, [], []);
1494
1447
  }
1495
- if (type.kind === "enum") {
1496
- const members = type.members.map((member) => ` ${this.field(type.id, member.name)} := ${member.value}`).join(`,
1497
- `);
1498
- return `{attribute 'qualified_only'}
1499
- {attribute 'strict'}
1500
- TYPE ${name} : (
1501
- ${members}
1502
- ) DINT;
1503
- END_TYPE
1504
- `;
1448
+ if (settings.trace) {
1449
+ for (const block of core.blocks) {
1450
+ const { job } = block;
1451
+ const task = this.tasks.get(block.id);
1452
+ if (!job || !task || this.instances.get(block.id)?.length !== 1) {
1453
+ continue;
1454
+ }
1455
+ const site = (type, phase) => this.site({
1456
+ kind: "job",
1457
+ job: { block: block.id, phase },
1458
+ path: job.name,
1459
+ type,
1460
+ span: job.span,
1461
+ text: `${job.name}: ${phase}`,
1462
+ task
1463
+ });
1464
+ this.jobSites.set(block.id, {
1465
+ start: site("UINT", "started"),
1466
+ completion: site("DINT", "finished")
1467
+ });
1468
+ }
1505
1469
  }
1506
- throw new Error("Unsupported verified data type");
1507
1470
  }
1508
- type(id) {
1509
- const type = this.types.get(id);
1510
- if (!type) {
1511
- throw new Error("Missing verified type");
1471
+ owningPath(variable) {
1472
+ const type = this.types.get(variable.type);
1473
+ const block = type?.kind === "block" ? this.blocks.get(type.block) : undefined;
1474
+ if (!block?.job) {
1475
+ return;
1512
1476
  }
1513
- return type;
1477
+ const paths = this.instances.get(block.id).filter((path) => path.at(-1).variable.id === variable.id);
1478
+ return paths.length === 1 ? paths[0] : undefined;
1514
1479
  }
1515
- name(id) {
1516
- return this.names.get(id) ?? id;
1480
+ site(site) {
1481
+ const id = this.events.length + 1;
1482
+ this.events.push({ ...site, id, operands: site.operands ?? [] });
1483
+ return id;
1517
1484
  }
1518
- field(id, name) {
1519
- const field = this.fields.get(id)?.get(name);
1520
- if (!field) {
1521
- throw new Error("Missing verified field");
1485
+ findCarriers() {
1486
+ const carries = (id) => {
1487
+ const block = this.blocks.get(id);
1488
+ if (block.runtime?.kind === "http") {
1489
+ return true;
1490
+ }
1491
+ return block.state.some((child) => {
1492
+ const type = instancedBlock4(child.type, this.types);
1493
+ return type !== undefined && carries(type.block);
1494
+ });
1495
+ };
1496
+ for (const block of this.core.blocks) {
1497
+ if (carries(block.id)) {
1498
+ this.carriers.add(block.id);
1499
+ }
1522
1500
  }
1523
- return field;
1524
1501
  }
1525
- declarationInitializer(value, id) {
1526
- const type = this.type(id);
1527
- if ((type.kind === "record" || type.kind === "array") && this.isZero(value)) {
1528
- return "";
1502
+ placeType(root, path = []) {
1503
+ let type = this.types.get(root.type);
1504
+ for (const segment of path) {
1505
+ if (segment.kind === "field" && type?.kind === "record") {
1506
+ type = this.types.get(type.fields.find((field) => field.name === segment.name).type);
1507
+ } else if (segment.kind === "index" && type?.kind === "array") {
1508
+ type = this.types.get(type.element);
1509
+ } else {
1510
+ return;
1511
+ }
1529
1512
  }
1530
- return ` := ${this.initializer(value, id)}`;
1513
+ return type;
1531
1514
  }
1532
- initializer(value, id) {
1533
- const type = this.type(id);
1534
- if (type.kind === "array" && value.kind === "array") {
1535
- return `[${value.items.map((item) => this.initializer(item, type.element)).join(", ")}]`;
1536
- }
1537
- if (type.kind !== "record" || value.kind !== "record") {
1538
- return this.literal(value, id);
1539
- }
1540
- const fields = type.fields.flatMap((field) => {
1541
- const initial = value.fields[field.name];
1542
- if (!initial) {
1543
- throw new Error("Missing verified record initializer");
1515
+ countCalls(items, weight) {
1516
+ for (const item of items) {
1517
+ if (item.kind === "invoke") {
1518
+ this.callSites.set(item.function, (this.callSites.get(item.function) ?? 0) + weight);
1519
+ }
1520
+ for (const body of nestedBodies3(item)) {
1521
+ this.countCalls(body, item.kind === "for" ? 2 : weight);
1544
1522
  }
1545
- return this.type(field.type).kind !== "enum" && this.isZero(initial) ? [] : [
1546
- `${this.field(id, field.name)} := ${this.initializer(initial, field.type)}`
1547
- ];
1548
- });
1549
- return fields.length ? `(${fields.join(", ")})` : this.literal(value, id);
1550
- }
1551
- isZero(value) {
1552
- if (value.kind === "bool") {
1553
- return !value.value;
1554
- }
1555
- if (value.kind === "integer") {
1556
- return value.value === "0";
1557
- }
1558
- if (value.kind === "float") {
1559
- return Object.is(value.value, 0);
1560
- }
1561
- if (value.kind === "string") {
1562
- return value.value === "";
1563
1523
  }
1564
- if (value.kind === "array") {
1565
- return value.items.every((item) => this.isZero(item));
1524
+ }
1525
+ writes(id) {
1526
+ const cached = this.routineWrites.get(id);
1527
+ if (cached) {
1528
+ return cached;
1566
1529
  }
1567
- if (value.kind === "record") {
1568
- return Object.values(value.fields).every((item) => this.isZero(item));
1530
+ const result = new Set;
1531
+ this.routineWrites.set(id, result);
1532
+ for (const root of this.statementWrites(this.routines.get(id)?.body ?? [])) {
1533
+ result.add(root);
1569
1534
  }
1570
- return false;
1535
+ return result;
1571
1536
  }
1572
- literal(value, id) {
1573
- const type = this.type(id);
1574
- if (type.kind === "enum" && value.kind === "integer") {
1575
- const member = type.members.find((member) => member.value === value.value);
1576
- if (!member) {
1577
- throw new Error("Missing verified enum member");
1537
+ statementWrites(items) {
1538
+ const result = new Set;
1539
+ for (const item of items) {
1540
+ for (const root of directWrites(item)) {
1541
+ result.add(root);
1542
+ }
1543
+ if (item.kind === "invoke") {
1544
+ for (const root of this.writes(item.function)) {
1545
+ result.add(root);
1546
+ }
1547
+ }
1548
+ if (item.kind === "blockUpdate") {
1549
+ const block = instancedBlock4(this.variables.get(item.instance).type, this.types);
1550
+ if (block) {
1551
+ for (const root of this.writes(block.block)) {
1552
+ result.add(root);
1553
+ }
1554
+ }
1555
+ }
1556
+ for (const body of nestedBodies3(item)) {
1557
+ for (const root of this.statementWrites(body)) {
1558
+ result.add(root);
1559
+ }
1578
1560
  }
1579
- return `${this.name(id)}.${this.field(id, member.name)}`;
1580
- }
1581
- if (type.kind === "string" && value.kind === "string") {
1582
- const delimiter = type.encoding === "utf16" ? '"' : "'";
1583
- return `${delimiter}${escapeString(value.value, delimiter)}${delimiter}`;
1584
1561
  }
1585
- if (type.kind === "array" && value.kind === "array") {
1586
- return `[${value.items.map((item) => this.literal(item, type.element)).join(", ")}]`;
1562
+ return result;
1563
+ }
1564
+ walk(settings, routine, items, prefixes, guards) {
1565
+ for (const [index, item] of items.entries()) {
1566
+ const here = [...prefixes, items.slice(0, index)];
1567
+ this.probe(settings, routine, item, here, guards);
1568
+ const guard = (conditions) => [
1569
+ ...guards,
1570
+ { conditions, depth: here.length }
1571
+ ];
1572
+ if (item.kind === "if") {
1573
+ this.walk(settings, routine, item.then, here, guard([item.condition]));
1574
+ this.walk(settings, routine, item.else, here, guard([item.condition]));
1575
+ }
1576
+ if (item.kind === "switch") {
1577
+ for (const body of nestedBodies3(item)) {
1578
+ this.walk(settings, routine, body, here, guard([item.value]));
1579
+ }
1580
+ }
1581
+ if (item.kind === "for") {
1582
+ this.walk(settings, routine, item.body, here, guards);
1583
+ }
1587
1584
  }
1588
- if (type.kind === "record" && value.kind === "record") {
1589
- const fields = type.fields.map((field) => {
1590
- const initial = value.fields[field.name];
1591
- if (!initial) {
1592
- throw new Error("Missing verified record initializer");
1585
+ }
1586
+ probe(settings, routine, item, prefixes, guards) {
1587
+ const task = this.tasks.get(routine.id);
1588
+ const probes = [];
1589
+ const written = writtenPlace(item);
1590
+ if (written && settings.writers) {
1591
+ let site;
1592
+ this.outputs.forEach((output, index) => {
1593
+ const when = this.reaches(written.root, written.path, output);
1594
+ if (!when) {
1595
+ return;
1593
1596
  }
1594
- return `${this.field(id, field.name)} := ${this.literal(initial, field.type)}`;
1597
+ site ??= ++this.writerSites;
1598
+ this.writers[index].push({
1599
+ id: site,
1600
+ routine: routine.id,
1601
+ span: item.span,
1602
+ statement: item
1603
+ });
1604
+ probes.push({ kind: "writer", site, output: index, when });
1595
1605
  });
1596
- return `(${fields.join(", ")})`;
1597
- }
1598
- if (type.kind === "duration" && value.kind === "duration") {
1599
- return `T#${BigInt(value.nanoseconds) / nanosecondsPerMillisecond2}ms`;
1600
1606
  }
1601
- if (type.kind === "calendar" && value.kind === "calendar") {
1602
- if (type.domain === "date") {
1603
- return `D#${value.value}`;
1607
+ if (settings.trace && task) {
1608
+ if (item.kind === "assign") {
1609
+ const root = this.variables.get(item.root);
1610
+ const type = this.placeType(root, item.path);
1611
+ const path = root.storage === "module" ? storagePath(root, item.path) : undefined;
1612
+ if (type?.kind === "enum" && path) {
1613
+ const operands = this.operands(routine, prefixes, guards, settings.trace);
1614
+ const site = this.site({
1615
+ kind: "state",
1616
+ path,
1617
+ routine: routine.id,
1618
+ type: type.id,
1619
+ span: item.span,
1620
+ task,
1621
+ operands
1622
+ });
1623
+ probes.push({ kind: "state", value: item.value, site, operands });
1624
+ }
1604
1625
  }
1605
- if (type.domain === "timeOfDay") {
1606
- return `TOD#${value.value}`;
1626
+ if (item.kind === "return" && item.value && "parameters" in routine && routine.result && this.callSites.get(routine.id) === 1) {
1627
+ const type = this.types.get(routine.result);
1628
+ if (type?.kind === "enum") {
1629
+ const slot = this.decisions.get(routine.id) ?? this.decisions.size;
1630
+ this.decisions.set(routine.id, slot);
1631
+ const path = routine.origin?.instance ? `${routine.origin.instance}.${routine.origin.name.split(".").at(-1)}` : routine.origin?.name ?? routine.name;
1632
+ const operands = this.operands(routine, prefixes, guards, settings.trace);
1633
+ const site = this.site({
1634
+ kind: "decision",
1635
+ path,
1636
+ routine: routine.id,
1637
+ type: type.id,
1638
+ span: item.span,
1639
+ task,
1640
+ operands
1641
+ });
1642
+ probes.push({
1643
+ kind: "decision",
1644
+ value: item.value,
1645
+ site,
1646
+ slot,
1647
+ operands
1648
+ });
1649
+ }
1607
1650
  }
1608
- return `DT#${value.value.replace("T", "-")}`;
1609
1651
  }
1610
- return scalarLiteral(value, id);
1652
+ if (probes.length) {
1653
+ this.probes.set(item, probes);
1654
+ }
1611
1655
  }
1612
- }
1613
-
1614
- // packages/compiler/src/codesys/global-names.ts
1615
- var planGlobalNames = (core, programNames = {}) => {
1616
- const names = new Names;
1617
- for (const name of Object.values(programNames)) {
1618
- names.reserve(name);
1656
+ reaches(root, path, output) {
1657
+ if (root !== output.root.id) {
1658
+ return;
1659
+ }
1660
+ const when = [];
1661
+ for (const [index, written] of path.entries()) {
1662
+ const bound = output.segments[index];
1663
+ if (!bound) {
1664
+ break;
1665
+ }
1666
+ if (written.kind === "field") {
1667
+ if (bound.kind !== "field" || bound.name !== written.name) {
1668
+ return;
1669
+ }
1670
+ continue;
1671
+ }
1672
+ if (bound.kind !== "index") {
1673
+ return;
1674
+ }
1675
+ const value = constantIndex(written.value);
1676
+ if (value === undefined) {
1677
+ when.push({ index: written.value, value: bound.value });
1678
+ } else if (value !== bound.value) {
1679
+ return;
1680
+ }
1681
+ }
1682
+ return when;
1619
1683
  }
1620
- const typeMap = new Map(core.types.map((type) => [type.id, type]));
1621
- const blockNames = new Map(core.blocks.map((block) => [
1622
- block.id,
1623
- block.standard ? standardBlocks[block.standard].native : names.allocateObject("FB", block.name)
1624
- ]));
1625
- for (const name of blockNames.values()) {
1626
- names.reserve(name);
1684
+ definitions(routine) {
1685
+ const cached = this.temporaries.get(routine.id);
1686
+ if (cached) {
1687
+ return cached;
1688
+ }
1689
+ const definitions = new Map;
1690
+ const define = (items) => {
1691
+ for (const item of items) {
1692
+ const target = wholeTarget(item);
1693
+ if (target && temporary(target)) {
1694
+ definitions.set(target, [...definitions.get(target) ?? [], item]);
1695
+ }
1696
+ for (const body of nestedBodies3(item)) {
1697
+ define(body);
1698
+ }
1699
+ }
1700
+ };
1701
+ define(routine.body);
1702
+ this.temporaries.set(routine.id, definitions);
1703
+ return definitions;
1627
1704
  }
1628
- const targetTypes = new CodesysTypes(typeMap, names, blockNames);
1629
- const { globalLists, retainedVariables } = storageLayout(core);
1630
- const hasExports = (group) => group.variables.some((variable) => variable.exported && !variable.exposure);
1631
- const globals = globalLists.map((group) => {
1632
- const splitByStorage = globalLists.some((other) => other.module === group.module && other.kind !== group.kind && hasExports(other));
1633
- const name = hasExports(group) ? names.allocate(pascalCase(splitByStorage ? `${group.module}-${group.kind}` : group.module)) : names.allocateObject("GVL", `${group.module}_${group.kind}`);
1634
- const fields = new Names;
1635
- for (const name of blockNames.values()) {
1636
- fields.reserve(name);
1705
+ operands(routine, prefixes, guards, trace) {
1706
+ const definitions = this.definitions(routine);
1707
+ const result = [];
1708
+ const seen = new Set;
1709
+ for (const guard of [...guards].reverse()) {
1710
+ const executed = new Set(prefixes.slice(0, guard.depth).flat());
1711
+ const between = this.statementWrites(prefixes.slice(guard.depth).flat());
1712
+ const add = (span, capture, read) => {
1713
+ const kind = this.types.get(capture.type)?.kind;
1714
+ const key = `${span.file}:${span.start}:${span.end}`;
1715
+ if (seen.has(key) || !["bool", "enum", "integer", "bits"].includes(kind ?? "")) {
1716
+ return;
1717
+ }
1718
+ seen.add(key);
1719
+ const path = read && storagePath(this.variables.get(read.root), read.path);
1720
+ result.push({
1721
+ capture,
1722
+ span,
1723
+ ...path && { path },
1724
+ stable: !read || !between.has(read.root)
1725
+ });
1726
+ };
1727
+ const direct = (value) => (value.path ?? []).every((segment) => segment.kind === "field" || constantIndex(segment.value) !== undefined);
1728
+ const visit = (value, evaluated) => {
1729
+ if (value.kind === "unary" || value.kind === "convert") {
1730
+ visit(value.operand, evaluated);
1731
+ }
1732
+ if (value.kind === "binary") {
1733
+ visit(value.left, evaluated);
1734
+ visit(value.right, evaluated);
1735
+ }
1736
+ if (value.kind !== "load") {
1737
+ return;
1738
+ }
1739
+ if (!temporary(value.root)) {
1740
+ if (evaluated || direct(value)) {
1741
+ add(value.span, value, value);
1742
+ }
1743
+ return;
1744
+ }
1745
+ const defined = definitions.get(value.root) ?? [];
1746
+ const [item] = defined;
1747
+ if (!item || defined.length !== 1) {
1748
+ for (const definition of defined) {
1749
+ if (definition.kind === "assign") {
1750
+ visit(definition.value, evaluated && executed.has(definition));
1751
+ }
1752
+ }
1753
+ return;
1754
+ }
1755
+ const reached = evaluated && executed.has(item);
1756
+ if (item.kind === "invoke") {
1757
+ if (reached) {
1758
+ add(item.span, value);
1759
+ }
1760
+ return;
1761
+ }
1762
+ if (item.kind !== "assign") {
1763
+ return;
1764
+ }
1765
+ const source = item.value;
1766
+ if (source.kind === "load" && !temporary(source.root)) {
1767
+ const read = {
1768
+ ...source,
1769
+ type: value.type,
1770
+ path: [...source.path ?? [], ...value.path ?? []]
1771
+ };
1772
+ if (reached) {
1773
+ add(source.span, value, read);
1774
+ } else if (direct(read)) {
1775
+ add(source.span, read, read);
1776
+ }
1777
+ return;
1778
+ }
1779
+ visit(source, reached);
1780
+ };
1781
+ for (const condition of guard.conditions) {
1782
+ visit(condition, true);
1783
+ }
1637
1784
  }
1785
+ return result.slice(0, trace.operands);
1786
+ }
1787
+ }
1788
+
1789
+ // packages/compiler/src/codesys/global-lists.ts
1790
+ import {
1791
+ defaultValue,
1792
+ instancedBlock as instancedBlock5
1793
+ } from "@tsplc/compiler/ir";
1794
+
1795
+ // packages/compiler/src/codesys/io-paths.ts
1796
+ import { ioLayout } from "@tsplc/typegen/hardware";
1797
+ var pathPattern = /^([\w$-]+)\.([A-Za-z_$][\w$]*)((?:\.[A-Za-z_$][\w$]*|\[-?\d+\])*)$/;
1798
+ var isStoragePath = (key) => key.includes(".") || key.includes("[");
1799
+ function resolveStoragePath(core, key) {
1800
+ const match = pathPattern.exec(key);
1801
+ if (!match) {
1638
1802
  return {
1639
- ...group,
1640
- name,
1641
- fields: new Map(group.variables.map((item) => [item.id, fields.allocate(item.name)]))
1803
+ error: `${key}: expected Module.variable followed by .field or [index].`
1642
1804
  };
1643
- });
1644
- return {
1645
- names,
1646
- typeMap,
1647
- blockNames,
1648
- targetTypes,
1649
- globals,
1650
- retainedVariables
1651
- };
1652
- };
1653
-
1654
- // packages/compiler/src/codesys/symbols.ts
1655
- function required2(value) {
1656
- if (value === undefined) {
1657
- throw new Error("Missing verified CODESYS symbol.");
1658
1805
  }
1659
- return value;
1660
- }
1661
- function createSymbols({ core, options }) {
1662
- const persistent = new Set(core.variables.filter((item) => item.storage !== "constant").map((item) => item.id));
1663
- const programRoutines = new Set;
1664
- for (const fn of core.functions) {
1665
- if (!fn.owner && [...accessedStorage(fn, core)].some((id) => persistent.has(id))) {
1666
- programRoutines.add(fn.id);
1806
+ const [, module, name, rest] = match;
1807
+ const roots = core.variables.filter((item) => item.storage === "module" && item.name === name && moduleName(item) === module);
1808
+ const [root] = roots;
1809
+ if (!root || roots.length !== 1) {
1810
+ return {
1811
+ error: root ? `${key}: ${module}.${name} is declared by more than one module named ${module}.` : `${key}: no mutable module variable ${module}.${name}.`
1812
+ };
1813
+ }
1814
+ const types = new Map(core.types.map((type) => [type.id, type]));
1815
+ let type = types.get(root.type);
1816
+ const segments = [];
1817
+ for (const [, field, index] of rest.matchAll(/\.([A-Za-z_$][\w$]*)|\[(-?\d+)\]/g)) {
1818
+ if (field !== undefined) {
1819
+ const member = type.kind === "record" ? type.fields.find((f) => f.name === field) : undefined;
1820
+ if (!member) {
1821
+ return { error: `${key}: no field ${field}.` };
1822
+ }
1823
+ segments.push({ kind: "field", record: type.id, name: field });
1824
+ type = types.get(member.type);
1825
+ } else {
1826
+ const value = Number(index);
1827
+ if (type.kind !== "array") {
1828
+ return { error: `${key}: ${index} indexes a non-array value.` };
1829
+ }
1830
+ if (value < type.lowerBound || value >= type.lowerBound + type.length) {
1831
+ return {
1832
+ error: `${key}: index ${value} is outside ${type.lowerBound}..${type.lowerBound + type.length - 1}.`
1833
+ };
1834
+ }
1835
+ segments.push({ kind: "index", value });
1836
+ type = types.get(type.element);
1667
1837
  }
1668
1838
  }
1669
- const globalNames = planGlobalNames(core, options.programNames);
1670
- return {
1671
- ...globalNames,
1672
- blocks: new Map(core.blocks.map((block) => [block.id, block])),
1673
- numeric: new NumericLowering(globalNames.typeMap, (label) => globalNames.names.allocate(label)),
1674
- programRoutines,
1675
- references: new Map,
1676
- functionNames: new Map,
1677
- programResults: new Map,
1678
- mailboxLocks: new Map,
1679
- blockFields: new Map,
1680
- routineScopes: new Map
1681
- };
1839
+ return { key, root, segments, type };
1682
1840
  }
1683
- function allocateFunctionNames(symbols, { core }) {
1684
- const entries = new Set(core.programs.map((program) => program.entry));
1685
- for (const fn of core.functions.filter((fn) => !fn.owner)) {
1686
- const program = symbols.programRoutines.has(fn.id);
1687
- const label = program && entries.has(fn.id) ? `${fn.name}_body` : fn.name;
1688
- symbols.functionNames.set(fn.id, symbols.names.allocateObject(program ? "PRG" : "F", label));
1841
+ function iecSpelling(type, types) {
1842
+ if (type.kind === "bool" || type.kind === "integer" || type.kind === "bits" || type.kind === "float" || type.kind === "duration" || type.kind === "calendar") {
1843
+ return type.id;
1844
+ }
1845
+ if (type.kind !== "array") {
1846
+ return;
1689
1847
  }
1848
+ const element = iecSpelling(types.get(type.element), types);
1849
+ const upper = type.lowerBound + type.length - 1;
1850
+ return element && !element.startsWith("ARRAY") ? `ARRAY[${type.lowerBound}..${upper}] OF ${element}` : undefined;
1690
1851
  }
1691
- var instrumentationFieldTypes = {
1692
- busy: "BOOL",
1693
- step: "UINT",
1694
- startedAt: "UDINT",
1695
- job: "UDINT",
1696
- sequence: "UDINT"
1697
- };
1698
- function allocateBlockFields(symbols, instrumentation, plan, objects) {
1699
- const { core } = plan;
1700
- const { functionNames, blockNames, blockFields } = symbols;
1701
- for (const block of core.blocks) {
1702
- const fields = new Names;
1703
- const mapped = new Map;
1704
- for (const object of objects) {
1705
- fields.reserve(object.name);
1706
- }
1707
- fields.reserve(instrumentation.global);
1708
- for (const objectName of [
1709
- ...core.functions.filter((fn) => !fn.owner).map((fn) => required2(functionNames.get(fn.id))),
1710
- ...blockNames.values()
1711
- ]) {
1712
- fields.reserve(objectName);
1713
- }
1714
- for (const method of core.functions.filter((fn) => fn.owner?.block === block.id)) {
1715
- functionNames.set(method.id, fields.allocate(method.name));
1716
- }
1717
- const native = block.standard && standardBlocks2[block.standard];
1718
- for (const item of [...block.inputs, ...block.outputs, ...block.state]) {
1719
- mapped.set(item.id, native ? required2([...native.inputs, ...native.outputs].find(([name]) => name === item.name))[1] : fields.allocate(item.name));
1852
+ function ioTargets(core) {
1853
+ const types = new Map(core.types.map((type) => [type.id, type]));
1854
+ const targets = [];
1855
+ const add = (key, type) => {
1856
+ const layout = ioLayout(iecSpelling(type, types) ?? "");
1857
+ if (layout) {
1858
+ targets.push({ key, layout });
1720
1859
  }
1721
- if (block.runtime?.kind === "mailbox") {
1722
- symbols.mailboxLocks.set(block.id, fields.allocate("plc_mailbox_lock"));
1860
+ };
1861
+ const visit = (key, type) => {
1862
+ add(key, type);
1863
+ if (type.kind === "record") {
1864
+ for (const field of type.fields) {
1865
+ visit(`${key}.${field.name}`, types.get(field.type));
1866
+ }
1723
1867
  }
1724
- blockFields.set(block.id, mapped);
1725
- const settings = plan.project.debug;
1726
- const stepped = instrumentation.analysis.jobSites.has(block.id) || plan.telemetry?.failures.has(block.id);
1727
- const tracked = Boolean(block.job && (settings?.jobs || stepped));
1728
- const carries = settings?.jobs && instrumentation.analysis.carriers.has(block.id);
1729
- if (tracked || carries) {
1730
- instrumentation.fields.set(block.id, {
1731
- ...tracked && {
1732
- busy: fields.allocate("tsplcBusy"),
1733
- track: fields.allocate("TsplcTrack")
1734
- },
1735
- ...tracked && settings?.jobs && { startedAt: fields.allocate("startedAt") },
1736
- ...stepped && { step: fields.allocate("tsplcStep") },
1737
- ...carries && { job: fields.allocate("requestJob") },
1738
- ...carries && block.runtime?.kind === "http" && {
1739
- sequence: fields.allocate("sequence")
1740
- }
1741
- });
1868
+ if (type.kind === "array") {
1869
+ visit(`${key}[\${number}]`, types.get(type.element));
1742
1870
  }
1743
- }
1744
- }
1745
- function allocateRoutineScope(symbols, instrumentation, objects, fn) {
1746
- const block = "inputs" in fn ? fn : undefined;
1747
- const owner = block ?? ("owner" in fn && fn.owner ? symbols.blocks.get(fn.owner.block) : undefined);
1748
- const names = new Names;
1749
- const references = new Map;
1750
- for (const object of objects) {
1751
- names.reserve(object.name);
1752
- }
1753
- names.reserve(instrumentation.global);
1754
- for (const name of [
1755
- ...symbols.functionNames.values(),
1756
- ...symbols.blockNames.values()
1757
- ]) {
1758
- names.reserve(name);
1759
- }
1760
- if (symbols.programRoutines.has(fn.id) && "parameters" in fn && fn.result) {
1761
- symbols.programResults.set(fn.id, names.allocate("plc_result"));
1762
- }
1763
- if (owner) {
1764
- for (const item of [...owner.outputs, ...owner.state]) {
1765
- const name = required2(required2(symbols.blockFields.get(owner.id)).get(item.id));
1766
- names.reserve(name);
1767
- references.set(item.id, name);
1871
+ };
1872
+ for (const variable of core.variables) {
1873
+ if (variable.storage === "input" || variable.storage === "output") {
1874
+ add(variable.name, types.get(variable.type));
1875
+ } else if (variable.storage === "module") {
1876
+ visit(`${moduleName(variable)}.${variable.name}`, types.get(variable.type));
1768
1877
  }
1769
1878
  }
1770
- for (const item of "parameters" in fn ? fn.parameters : fn.inputs) {
1771
- const name = block ? required2(required2(symbols.blockFields.get(block.id)).get(item.id)) : names.allocate(item.name);
1772
- names.reserve(name);
1773
- references.set(item.id, name);
1774
- }
1775
- for (const item of fn.locals) {
1776
- references.set(item.id, names.allocate(item.name));
1777
- }
1778
- symbols.routineScopes.set(fn.id, { names, references });
1879
+ return targets;
1779
1880
  }
1780
1881
 
1781
1882
  // packages/compiler/src/codesys/global-lists.ts
@@ -2647,7 +2748,7 @@ import {
2647
2748
  } from "@tsplc/compiler/ir";
2648
2749
  import { serviceOfPath } from "@tsplc/server";
2649
2750
  // packages/compiler/package.json
2650
- var version = "0.5.8";
2751
+ var version = "0.5.9";
2651
2752
 
2652
2753
  // packages/compiler/src/codesys/telemetry.ts
2653
2754
  import {
@@ -5151,7 +5252,6 @@ import {
5151
5252
  forwardTemporaries,
5152
5253
  instancedBlock as instancedBlock8,
5153
5254
  isVerifiedCore,
5154
- joinPrograms,
5155
5255
  nestedBodies as nestedBodies7,
5156
5256
  shareRoutines,
5157
5257
  statementExpressions as statementExpressions4,
@@ -5389,24 +5489,20 @@ function sharedRoutines(core, deployment, debug) {
5389
5489
  return unshared;
5390
5490
  }
5391
5491
  const issues = [];
5392
- const scheduled = {
5393
- tasks: schedulePrograms(core, deployment.tasks, (message) => {
5394
- issues.push(message);
5395
- })
5396
- };
5492
+ schedulePrograms(core, deployment.tasks, (message) => {
5493
+ issues.push(message);
5494
+ });
5397
5495
  if (issues.length) {
5398
5496
  return unshared;
5399
5497
  }
5400
- const continuations = new Set(core.programs.flatMap((program) => program.continuation ? [program.name] : []));
5401
- const joined = joinPrograms(core, scheduled.tasks.map((task) => task.programs.filter((name) => continuations.has(name))));
5402
- const folded = foldConstantRoutines(joined.core);
5498
+ const folded = foldConstantRoutines(core);
5403
5499
  const tasks = routineTasks(folded.core, {
5404
5500
  tasks: schedulePrograms(folded.core, deployment.tasks, () => {})
5405
5501
  });
5406
5502
  const shared = shareRoutines(folded.core, (routine) => tasks.get(routine.id));
5407
5503
  return {
5408
5504
  core: forwardTemporaries(shared.core),
5409
- routines: new Map([...joined.routines, ...shared.routines])
5505
+ routines: shared.routines
5410
5506
  };
5411
5507
  }
5412
5508
  function validateIo(core, options, report) {
@@ -5678,43 +5774,6 @@ function validateConstants(core, report) {
5678
5774
  });
5679
5775
  }
5680
5776
 
5681
- // packages/compiler/src/codesys/programs.ts
5682
- function emitScanProgram({ plan, symbols, instrumentation }, ioChannels, program) {
5683
- const { core, options } = plan;
5684
- const { names, functionNames } = symbols;
5685
- const explicit = options.programNames && Object.hasOwn(options.programNames, program.name) ? options.programNames[program.name] : undefined;
5686
- const name = explicit ?? names.allocateObject("PRG", program.name);
5687
- const fn = required2(core.functions.find((item) => item.id === program.entry));
5688
- const used = accessedStorage(fn, core);
5689
- const channels = ioChannels.filter((channel) => used.has(channel.root));
5690
- const stateful = symbols.programRoutines.has(program.entry);
5691
- const call = `${functionNames.get(program.entry)}();`;
5692
- const task = plan.deployment.tasks.find((item) => item.programs[0] === program.name);
5693
- const ring = task && instrumentation.rings.get(task.name);
5694
- const clock = task && instrumentation.scanClocks.get(task.name);
5695
- const lines = [
5696
- ...ring ? [`${instrumentation.global}.${ring}();`] : [],
5697
- ...clock ? [`${clock} := TO_DINT(TIME_TO_UDINT(TIME()));`] : [],
5698
- ...channels.filter((channel) => channel.input).map(({ target, wire, inverted }) => `${target} := ${inverted ? "NOT " : ""}${wire};`),
5699
- stateful ? call : `plc_discard := ${call}`,
5700
- ...channels.filter((channel) => !channel.input).map(({ target, wire }) => `${wire} := ${target};`)
5701
- ];
5702
- return {
5703
- id: program.id,
5704
- kind: "program",
5705
- name,
5706
- declaration: stateful ? `PROGRAM ${name}
5707
- ` : `PROGRAM ${name}
5708
- VAR
5709
- plc_discard : BOOL;
5710
- END_VAR
5711
- `,
5712
- implementation: `${lines.join(`
5713
- `)}
5714
- `
5715
- };
5716
- }
5717
-
5718
5777
  // packages/compiler/src/codesys/routines.ts
5719
5778
  import {
5720
5779
  defaultValue as defaultValue2,
@@ -6314,6 +6373,7 @@ function emitCodesys(plan) {
6314
6373
  for (const program of core.programs) {
6315
6374
  objects.push(emitScanProgram(context, ioList.channels, program));
6316
6375
  }
6376
+ objects.push(...emitTaskWrappers(context, objects));
6317
6377
  const sources = new Sources(plan.project.root);
6318
6378
  const functionIds = new Map;
6319
6379
  const manifest = debugManifest(context, (key) => ioTarget(plan, symbols, key), sources, functionIds);
@@ -6430,5 +6490,5 @@ export {
6430
6490
  publicationSelectors
6431
6491
  };
6432
6492
 
6433
- //# debugId=D655035FED03E81364756E2164756E21
6493
+ //# debugId=85C2092C54C9668964756E2164756E21
6434
6494
  //# sourceMappingURL=codesys.js.map