@tsplc/compiler 0.2.16 → 0.2.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/cli.js +920 -943
- package/dist/cli.js.map +13 -10
- package/dist/codesys.js +3893 -3352
- package/dist/codesys.js.map +29 -20
- package/dist/elaborate-capture.js +33 -17
- package/dist/elaborate-capture.js.map +3 -3
- package/dist/index.js +8787 -6855
- package/dist/index.js.map +40 -20
- package/dist/ir.js +1575 -1072
- package/dist/ir.js.map +21 -17
- package/dist/math.js.map +2 -2
- package/dist/project.js +154 -60
- package/dist/project.js.map +5 -5
- package/dist/telemetry.js +27 -9
- package/dist/telemetry.js.map +5 -5
- package/package.json +112 -112
- package/src/codesys/config.ts +50 -0
- package/src/codesys/debug.ts +670 -0
- package/src/codesys/emit.ts +142 -0
- package/src/codesys/engineering.ts +109 -0
- package/src/codesys/expressions.ts +92 -0
- package/src/codesys/global-lists.ts +250 -0
- package/src/codesys/global-names.ts +68 -0
- package/src/codesys/http.ts +890 -0
- package/src/codesys/index.ts +30 -0
- package/src/codesys/instrumentation.ts +430 -0
- package/src/codesys/io-paths.ts +140 -0
- package/src/codesys/manifest.ts +643 -0
- package/src/codesys/names.ts +81 -0
- package/src/codesys/numeric.ts +409 -0
- package/src/codesys/operands.ts +62 -0
- package/src/codesys/plan.ts +605 -0
- package/src/codesys/programs.ts +53 -0
- package/src/codesys/publication.ts +171 -0
- package/src/codesys/routines.ts +603 -0
- package/src/codesys/sources.ts +71 -0
- package/src/codesys/st-files.ts +115 -0
- package/src/codesys/storage.ts +97 -0
- package/src/codesys/symbols.ts +220 -0
- package/src/codesys/task-access.ts +320 -0
- package/src/codesys/telemetry.ts +732 -0
- package/src/codesys/types.ts +250 -0
- package/src/codesys/vendor.ts +150 -0
- package/src/frontend/analyzer.ts +794 -0
- package/src/frontend/async.ts +317 -1137
- package/src/frontend/blocks.ts +537 -403
- package/src/frontend/configuration.ts +176 -144
- package/src/frontend/const-functions.ts +183 -148
- package/src/frontend/cooperative.ts +73 -43
- package/src/frontend/coroutines.ts +1032 -0
- package/src/frontend/elaborate/calls.ts +535 -0
- package/src/frontend/elaborate/capture.ts +157 -101
- package/src/frontend/elaborate/dialect.ts +257 -0
- package/src/frontend/elaborate/expressions.ts +992 -0
- package/src/frontend/elaborate/frame.ts +53 -0
- package/src/frontend/elaborate/graph.ts +116 -71
- package/src/frontend/elaborate/imports.ts +70 -0
- package/src/frontend/elaborate/index.ts +435 -331
- package/src/frontend/elaborate/initializers.ts +198 -0
- package/src/frontend/elaborate/layouts.ts +591 -384
- package/src/frontend/elaborate/model.ts +264 -169
- package/src/frontend/elaborate/specialize.ts +343 -2586
- package/src/frontend/elaborate/statements.ts +606 -0
- package/src/frontend/elaborate/storage.ts +546 -0
- package/src/frontend/elaborate/values.ts +58 -0
- package/src/frontend/elaborate/writes.ts +100 -0
- package/src/frontend/exposure.ts +172 -140
- package/src/frontend/expressions.ts +1383 -0
- package/src/frontend/intrinsics.ts +337 -0
- package/src/frontend/module-graph.ts +89 -59
- package/src/frontend/positions.ts +271 -200
- package/src/frontend/promise-chains.ts +897 -0
- package/src/frontend/promises.ts +390 -747
- package/src/frontend/routines.ts +181 -0
- package/src/frontend/sdk.ts +82 -0
- package/src/frontend/services.ts +506 -372
- package/src/frontend/statements.ts +855 -0
- package/src/frontend/tasks.ts +471 -0
- package/src/frontend/telemetry.ts +174 -0
- package/src/frontend/types.ts +845 -551
- package/src/frontend/typescript.ts +323 -2543
- package/src/index.ts +5 -5
- package/src/ir/aggregates.ts +275 -0
- package/src/ir/allocation.ts +84 -0
- package/src/ir/core-model.ts +146 -0
- package/src/ir/declarations.ts +295 -0
- package/src/ir/diagnostics.ts +61 -0
- package/src/ir/domains.ts +152 -0
- package/src/ir/fold.ts +342 -0
- package/src/ir/index.ts +90 -0
- package/{ir/errors.ts → src/ir/job-errors.ts} +12 -10
- package/src/ir/layouts.ts +181 -0
- package/src/ir/link.ts +354 -0
- package/src/ir/model.ts +386 -0
- package/{ir → src/ir}/normalization-error.ts +4 -4
- package/src/ir/normalize.ts +70 -0
- package/src/ir/numeric.ts +171 -0
- package/src/ir/ranges.ts +256 -0
- package/src/ir/routine.ts +1163 -0
- package/src/ir/scalars.ts +321 -0
- package/src/ir/types.ts +127 -0
- package/src/project/artifacts.ts +342 -0
- package/src/project/cli.ts +177 -0
- package/src/project/debugger.ts +82 -0
- package/src/project/index.ts +6 -0
- package/src/project/plant.ts +467 -0
- package/src/project/project-commands.ts +372 -0
- package/src/project/project.ts +457 -0
- package/src/project/release.ts +153 -0
- package/src/project/server.ts +150 -0
- package/src/project/terminal.ts +32 -0
- package/stdlib/math.ts +14 -10
- package/stdlib/telemetry.ts +71 -47
- package/types/async.d.ts +46 -40
- package/types/data-types.d.ts +26 -26
- package/types/globals.d.ts +41 -38
- package/types/index.d.ts +96 -51
- package/types/plc.d.ts +3 -4
- package/types/telemetry.d.ts +14 -14
- package/backends/codesys/config.ts +0 -54
- package/backends/codesys/debug.ts +0 -509
- package/backends/codesys/emit.ts +0 -1738
- package/backends/codesys/engineering.ts +0 -88
- package/backends/codesys/global-names.ts +0 -49
- package/backends/codesys/http.ts +0 -675
- package/backends/codesys/index.ts +0 -13
- package/backends/codesys/io-paths.ts +0 -105
- package/backends/codesys/manifest.ts +0 -312
- package/backends/codesys/names.ts +0 -76
- package/backends/codesys/numeric.ts +0 -356
- package/backends/codesys/plan.ts +0 -457
- package/backends/codesys/publication.ts +0 -59
- package/backends/codesys/storage.ts +0 -70
- package/backends/codesys/task-access.ts +0 -293
- package/backends/codesys/telemetry.ts +0 -593
- package/backends/codesys/types.ts +0 -179
- package/backends/codesys/vendor.ts +0 -108
- package/ir/aggregates.ts +0 -333
- package/ir/allocation.ts +0 -74
- package/ir/core-model.ts +0 -129
- package/ir/core.ts +0 -64
- package/ir/declarations.ts +0 -208
- package/ir/diagnostics.ts +0 -43
- package/ir/domains.ts +0 -96
- package/ir/index.ts +0 -8
- package/ir/link.ts +0 -185
- package/ir/model.ts +0 -346
- package/ir/routine.ts +0 -859
- package/ir/scalars.ts +0 -675
- package/ir/types.ts +0 -76
- package/project/artifacts.ts +0 -277
- package/project/cli.ts +0 -395
- package/project/index.ts +0 -1
- package/project/plant.ts +0 -509
- package/project/project.ts +0 -358
- package/project/server.ts +0 -113
package/backends/codesys/emit.ts
DELETED
|
@@ -1,1738 +0,0 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
Constant,
|
|
3
|
-
CoreExpression,
|
|
4
|
-
CoreFunction,
|
|
5
|
-
CoreFunctionBlock,
|
|
6
|
-
CorePath,
|
|
7
|
-
CoreStatement,
|
|
8
|
-
EmitResult,
|
|
9
|
-
GeneratedObject,
|
|
10
|
-
SourceSpan,
|
|
11
|
-
Variable,
|
|
12
|
-
} from "@tsplc/compiler/ir";
|
|
13
|
-
import {
|
|
14
|
-
defaultValue,
|
|
15
|
-
instancedBlock,
|
|
16
|
-
jobErrors,
|
|
17
|
-
standardBlocks,
|
|
18
|
-
telemetryOperands,
|
|
19
|
-
} from "@tsplc/compiler/ir";
|
|
20
|
-
import { createHash } from "node:crypto";
|
|
21
|
-
import type { DebugEventSite, DebugFunction, DebugJob, DebugManifest } from "@tsplc/debug/manifest";
|
|
22
|
-
import { serviceOfPath } from "@tsplc/server";
|
|
23
|
-
import { DebugAnalysis, type InstancePath, type Operand, storagePath } from "./debug.ts";
|
|
24
|
-
import { Sources, debugConstants, debugHardware, debugTypes, ioAddress } from "./manifest.ts";
|
|
25
|
-
import { isStoragePath, resolveStoragePath, type StorageBinding } from "./io-paths.ts";
|
|
26
|
-
import { version } from "../../package.json";
|
|
27
|
-
import { planGlobalNames } from "./global-names.ts";
|
|
28
|
-
import { Names } from "./names.ts";
|
|
29
|
-
import { NumericLowering } from "./numeric.ts";
|
|
30
|
-
import { type CodesysPlan, diagnostic, isCodesysPlan } from "./plan.ts";
|
|
31
|
-
import { accessedStorage } from "./task-access.ts";
|
|
32
|
-
import { emitHttp, httpMethods, httpCertificateVerifier, opcuaServiceCapacity } from "./http.ts";
|
|
33
|
-
import { callParameters, generated, telemetryClient, telemetryObjects } from "./telemetry.ts";
|
|
34
|
-
import type { Publication } from "@tsplc/config";
|
|
35
|
-
|
|
36
|
-
export interface SourceMapping {
|
|
37
|
-
path: string;
|
|
38
|
-
line: number;
|
|
39
|
-
span: SourceSpan;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
/** Stands for the build id in the sender until the id, a hash over everything else, is known. */
|
|
43
|
-
const buildPlaceholder = "<build>";
|
|
44
|
-
|
|
45
|
-
// All symbol relationships were checked by normalization and planning. Failure
|
|
46
|
-
// here is an emitter invariant violation, rather than a recoverable source error.
|
|
47
|
-
function required<T>(value: T | undefined): T {
|
|
48
|
-
if (value === undefined) throw new Error("Missing verified CODESYS symbol.");
|
|
49
|
-
return value;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
type CodesysBundle = EmitResult & {
|
|
53
|
-
/** Variables a generated device tree maps to their bit or byte channels. */
|
|
54
|
-
ioMappings: readonly { key: string; address: string; variable: string }[];
|
|
55
|
-
mappings: readonly SourceMapping[];
|
|
56
|
-
ioSymbols: Readonly<Record<string, string>>;
|
|
57
|
-
publication: Publication;
|
|
58
|
-
/** The debugger's view of this build; its id is also published as `build.target`. */
|
|
59
|
-
debug?: DebugManifest;
|
|
60
|
-
};
|
|
61
|
-
|
|
62
|
-
export function emitCodesys(plan: CodesysPlan): CodesysBundle {
|
|
63
|
-
if (!isCodesysPlan(plan)) {
|
|
64
|
-
return {
|
|
65
|
-
artifacts: [],
|
|
66
|
-
objects: [],
|
|
67
|
-
mappings: [],
|
|
68
|
-
ioSymbols: {},
|
|
69
|
-
publication: { production: [], development: [] },
|
|
70
|
-
ioMappings: [],
|
|
71
|
-
diagnostics: [diagnostic("Emission requires a validated CODESYS plan.")],
|
|
72
|
-
};
|
|
73
|
-
}
|
|
74
|
-
return new CodesysEmitter(plan).emit();
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
// A bundle owns target names and source mappings. Per-routine declarations and
|
|
78
|
-
// implementation lines stay local to emitRoutine, so they cannot leak between POUs.
|
|
79
|
-
class CodesysEmitter {
|
|
80
|
-
private readonly names;
|
|
81
|
-
private networkName: string | undefined;
|
|
82
|
-
private readonly rpcChannels: {
|
|
83
|
-
path: string;
|
|
84
|
-
request: string;
|
|
85
|
-
requestId: string;
|
|
86
|
-
reply: string;
|
|
87
|
-
replyId: string;
|
|
88
|
-
epoch: string;
|
|
89
|
-
}[] = [];
|
|
90
|
-
private readonly references = new Map<string, string>();
|
|
91
|
-
/** Each `io` binding: an AT wire copied to or from its logical target around the scan. */
|
|
92
|
-
private readonly channels: {
|
|
93
|
-
key: string;
|
|
94
|
-
root: string;
|
|
95
|
-
input: boolean;
|
|
96
|
-
target: string;
|
|
97
|
-
wire: string;
|
|
98
|
-
inverted?: boolean;
|
|
99
|
-
}[] = [];
|
|
100
|
-
private readonly ioMappings: { key: string; address: string; variable: string }[] = [];
|
|
101
|
-
private readonly objects: GeneratedObject[] = [];
|
|
102
|
-
private readonly mappings: SourceMapping[] = [];
|
|
103
|
-
private readonly mailboxLocks = new Map<string, string>();
|
|
104
|
-
private readonly blockFields = new Map<string, Map<string, string>>();
|
|
105
|
-
private readonly typeMap;
|
|
106
|
-
private readonly blocks;
|
|
107
|
-
private readonly blockNames;
|
|
108
|
-
private readonly functionNames = new Map<string, string>();
|
|
109
|
-
private readonly programRoutines = new Set<string>();
|
|
110
|
-
private readonly programResults = new Map<string, string>();
|
|
111
|
-
private readonly routineScopes = new Map<
|
|
112
|
-
string,
|
|
113
|
-
{ names: Names; references: Map<string, string> }
|
|
114
|
-
>();
|
|
115
|
-
private readonly targetTypes;
|
|
116
|
-
private readonly numeric: NumericLowering;
|
|
117
|
-
private readonly globals;
|
|
118
|
-
private readonly retainedVariables;
|
|
119
|
-
private readonly debug: DebugAnalysis;
|
|
120
|
-
/** `GVL_TsplcDebug`, and the names of its fields. */
|
|
121
|
-
private readonly debugGlobal: string;
|
|
122
|
-
private readonly debugNames = new Names();
|
|
123
|
-
/** Each task's ring and sender in `GVL_TsplcDebug`. */
|
|
124
|
-
private readonly rings = new Map<string, string>();
|
|
125
|
-
private readonly debugSlots: { decisions: string; writers: string };
|
|
126
|
-
private readonly telemetryNames: { writer: string; record: string; client: string } | undefined;
|
|
127
|
-
/** Instrumentation fields of each block: its job state and the requesting job's id. */
|
|
128
|
-
private readonly debugFields = new Map<
|
|
129
|
-
string,
|
|
130
|
-
{
|
|
131
|
-
busy?: string;
|
|
132
|
-
/** The method that records the job starting and finishing, allocated with `busy`. */
|
|
133
|
-
track?: string;
|
|
134
|
-
step?: string;
|
|
135
|
-
startedAt?: string;
|
|
136
|
-
job?: string;
|
|
137
|
-
sequence?: string;
|
|
138
|
-
}
|
|
139
|
-
>();
|
|
140
|
-
/** Job instances in manifest order, and the job id each single-instance declaration passes to its service calls. */
|
|
141
|
-
private readonly jobs: { block: CoreFunctionBlock; path: InstancePath }[];
|
|
142
|
-
private readonly jobIds = new Map<string, number>();
|
|
143
|
-
/** Raw bytes over each assembly, in `GVL_TsplcDebug`, by device. */
|
|
144
|
-
private readonly devices = new Map<
|
|
145
|
-
string,
|
|
146
|
-
Partial<Record<"input" | "output", { field: string; address: string; bytes: number }>>
|
|
147
|
-
>();
|
|
148
|
-
|
|
149
|
-
constructor(private readonly plan: CodesysPlan) {
|
|
150
|
-
const { core, options } = plan;
|
|
151
|
-
const persistent = new Set(
|
|
152
|
-
core.variables.filter((item) => item.storage !== "constant").map((item) => item.id),
|
|
153
|
-
);
|
|
154
|
-
for (const fn of core.functions) {
|
|
155
|
-
if (!fn.owner && [...accessedStorage(fn, core)].some((id) => persistent.has(id)))
|
|
156
|
-
this.programRoutines.add(fn.id);
|
|
157
|
-
}
|
|
158
|
-
const { names, typeMap, blockNames, targetTypes, globals, retainedVariables } = planGlobalNames(
|
|
159
|
-
core,
|
|
160
|
-
options.programNames,
|
|
161
|
-
);
|
|
162
|
-
this.names = names;
|
|
163
|
-
this.typeMap = typeMap;
|
|
164
|
-
this.blockNames = blockNames;
|
|
165
|
-
this.targetTypes = targetTypes;
|
|
166
|
-
this.globals = globals;
|
|
167
|
-
this.retainedVariables = retainedVariables;
|
|
168
|
-
this.blocks = new Map(core.blocks.map((block) => [block.id, block]));
|
|
169
|
-
this.numeric = new NumericLowering(this.typeMap, (label) => this.names.allocate(label));
|
|
170
|
-
this.objects.push(...this.targetTypes.objects);
|
|
171
|
-
|
|
172
|
-
const settings = plan.project.debug;
|
|
173
|
-
// A simulation build binds no fieldbus I/O, but its outputs are still the configured ones.
|
|
174
|
-
const hardware = plan.project.hardware;
|
|
175
|
-
const outputs = [
|
|
176
|
-
...core.variables
|
|
177
|
-
.filter((variable) => variable.storage === "output")
|
|
178
|
-
.map((root) => ({ key: root.name, root, segments: [] })),
|
|
179
|
-
...(hardware
|
|
180
|
-
? Object.entries(hardware.config.io).flatMap(([key, binding]) => {
|
|
181
|
-
if (!isStoragePath(key) || !ioAddress(hardware, binding)?.startsWith("%Q")) return [];
|
|
182
|
-
const resolved = resolveStoragePath(core, key);
|
|
183
|
-
return "error" in resolved ? [] : [resolved];
|
|
184
|
-
})
|
|
185
|
-
: plan.storageBindings.filter(({ key }) =>
|
|
186
|
-
required(options.io[key]).address.startsWith("%Q"),
|
|
187
|
-
)
|
|
188
|
-
).map(({ key, root, segments }) => ({ key, root, segments })),
|
|
189
|
-
];
|
|
190
|
-
this.debug = new DebugAnalysis(core, plan.deployment, settings, outputs);
|
|
191
|
-
this.debugGlobal = this.names.allocateObject("GVL", "TsplcDebug");
|
|
192
|
-
this.debugNames.allocate("buildId");
|
|
193
|
-
this.debugSlots = {
|
|
194
|
-
decisions: this.debugNames.allocate("decisions"),
|
|
195
|
-
writers: this.debugNames.allocate("writers"),
|
|
196
|
-
};
|
|
197
|
-
const telemetry = plan.telemetry;
|
|
198
|
-
if (telemetry) {
|
|
199
|
-
const tasks = new Set([
|
|
200
|
-
...[...telemetry.calls.values(), ...telemetry.failures.values()].map((site) => site.task),
|
|
201
|
-
...this.debug.events.map((site) => site.task),
|
|
202
|
-
]);
|
|
203
|
-
for (const task of plan.deployment.tasks)
|
|
204
|
-
if (tasks.has(task.name)) this.rings.set(task.name, this.debugNames.allocate(task.name));
|
|
205
|
-
if (this.rings.size)
|
|
206
|
-
this.telemetryNames = {
|
|
207
|
-
writer: this.names.allocateObject("FB", "TsplcTelemetry"),
|
|
208
|
-
record: this.names.allocateObject("ST", "TsplcRecord"),
|
|
209
|
-
client: this.names.allocateObject("FB", "TsplcTelemetryHttp"),
|
|
210
|
-
};
|
|
211
|
-
}
|
|
212
|
-
this.jobs = core.blocks
|
|
213
|
-
.filter((block) => block.job)
|
|
214
|
-
.flatMap((block) => this.debug.instances.get(block.id)!.map((path) => ({ block, path })));
|
|
215
|
-
this.jobs.forEach(({ path }, index) => {
|
|
216
|
-
const declared = path.at(-1)!.variable;
|
|
217
|
-
if (this.debug.owningPath(declared) === path) this.jobIds.set(declared.id, index + 1);
|
|
218
|
-
});
|
|
219
|
-
if (settings && hardware?.tree)
|
|
220
|
-
for (const device of hardware.catalog.devices)
|
|
221
|
-
this.devices.set(
|
|
222
|
-
device.id,
|
|
223
|
-
Object.fromEntries(
|
|
224
|
-
device.assemblies.map((assembly) => [
|
|
225
|
-
assembly.direction,
|
|
226
|
-
{
|
|
227
|
-
field: this.debugNames.allocate(`${device.id}_${assembly.direction}s`),
|
|
228
|
-
address: assembly.address,
|
|
229
|
-
bytes: assembly.size,
|
|
230
|
-
},
|
|
231
|
-
]),
|
|
232
|
-
),
|
|
233
|
-
);
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
emit(): CodesysBundle {
|
|
237
|
-
this.emitGlobals();
|
|
238
|
-
this.emitIo();
|
|
239
|
-
if (Object.values(this.plan.http).some((endpoint) => endpoint.transport !== "opcua")) {
|
|
240
|
-
this.networkName = this.names.allocateObject("GVL", "TsplcNetwork");
|
|
241
|
-
this.objects.push({
|
|
242
|
-
id: "runtime:httpNetwork",
|
|
243
|
-
kind: "globalList",
|
|
244
|
-
name: this.networkName,
|
|
245
|
-
// Blocks in other global lists take this in their initializers, so it must initialize first.
|
|
246
|
-
declaration: `{attribute 'qualified_only'}
|
|
247
|
-
{attribute 'global_init_slot' := '40000'}
|
|
248
|
-
VAR_GLOBAL
|
|
249
|
-
network:NBS.AsyncProperty := (usiTaskPrio:=15,udiTaskInterval:=1000,tnTaskName:='tsPLC HTTP');
|
|
250
|
-
END_VAR
|
|
251
|
-
`,
|
|
252
|
-
});
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
// Helpers must be discovered before allocating local names: an ST local must
|
|
256
|
-
// never shadow a helper, function, FB, or DUT that the implementation calls.
|
|
257
|
-
const { core } = this.plan;
|
|
258
|
-
const entries = new Set(core.programs.map((program) => program.entry));
|
|
259
|
-
for (const fn of core.functions.filter((fn) => !fn.owner)) {
|
|
260
|
-
const program = this.programRoutines.has(fn.id);
|
|
261
|
-
const label = program && entries.has(fn.id) ? `${fn.name}_body` : fn.name;
|
|
262
|
-
this.functionNames.set(fn.id, this.names.allocateObject(program ? "PRG" : "F", label));
|
|
263
|
-
}
|
|
264
|
-
for (const fn of core.functions) this.prepareStatements(fn.body);
|
|
265
|
-
for (const block of core.blocks) this.prepareStatements(block.body);
|
|
266
|
-
this.objects.push(...this.numeric.objects);
|
|
267
|
-
this.allocateBlockFields();
|
|
268
|
-
|
|
269
|
-
this.emitTelemetry();
|
|
270
|
-
const routines = [...core.functions, ...core.blocks.filter((block) => !block.standard)];
|
|
271
|
-
for (const fn of routines) this.allocateRoutineScope(fn);
|
|
272
|
-
for (const fn of routines) this.emitRoutine(fn);
|
|
273
|
-
for (const program of core.programs) this.emitProgram(program);
|
|
274
|
-
const debug = this.emitDebugGlobal();
|
|
275
|
-
|
|
276
|
-
const { objects, mappings } = this;
|
|
277
|
-
const paths = new Map<string, string>();
|
|
278
|
-
for (const object of objects) {
|
|
279
|
-
const path = this.objectPath(object);
|
|
280
|
-
paths.set(object.id, path);
|
|
281
|
-
object.sourcePath =
|
|
282
|
-
object.implementation === undefined ? `${path}.st` : `${path}/declaration.st`;
|
|
283
|
-
}
|
|
284
|
-
const artifacts = objects.flatMap((object) => {
|
|
285
|
-
const path = paths.get(object.id)!;
|
|
286
|
-
return object.implementation === undefined
|
|
287
|
-
? [{ path: `${path}.st`, content: object.declaration }]
|
|
288
|
-
: [
|
|
289
|
-
{ path: `${path}/declaration.st`, content: object.declaration },
|
|
290
|
-
{ path: `${path}/implementation.st`, content: object.implementation },
|
|
291
|
-
];
|
|
292
|
-
});
|
|
293
|
-
for (const mapping of mappings) {
|
|
294
|
-
const object = objects.find((object) => {
|
|
295
|
-
const key = object.kind === "method" ? object.id : object.name;
|
|
296
|
-
return mapping.path === `${key}.st` || mapping.path.startsWith(`${key}/`);
|
|
297
|
-
});
|
|
298
|
-
if (object) {
|
|
299
|
-
const key = object.kind === "method" ? object.id : object.name;
|
|
300
|
-
mapping.path = paths.get(object.id)! + mapping.path.slice(key.length);
|
|
301
|
-
}
|
|
302
|
-
}
|
|
303
|
-
const ioSymbols = Object.fromEntries([
|
|
304
|
-
...this.channels.map((channel) => [channel.key, channel.target]),
|
|
305
|
-
...this.ioMappings.map((mapping) => [mapping.key, mapping.variable]),
|
|
306
|
-
]);
|
|
307
|
-
const { ioMappings } = this;
|
|
308
|
-
const logicalIo = this.plan.core.variables
|
|
309
|
-
.filter((variable) => variable.storage === "input" || variable.storage === "output")
|
|
310
|
-
.map((variable) => variable.id);
|
|
311
|
-
const rpcSymbols = [
|
|
312
|
-
...new Set(
|
|
313
|
-
this.rpcChannels.flatMap((channel) =>
|
|
314
|
-
[channel.request, channel.requestId, channel.reply, channel.replyId, channel.epoch].map(
|
|
315
|
-
(path) => path.replace(/\[\d+\]$/, ""),
|
|
316
|
-
),
|
|
317
|
-
),
|
|
318
|
-
),
|
|
319
|
-
];
|
|
320
|
-
const published = (ids: readonly string[]) =>
|
|
321
|
-
[...ids, ...logicalIo].map((id) => required(this.references.get(id))).concat(rpcSymbols);
|
|
322
|
-
const publication = {
|
|
323
|
-
production: published(this.plan.publication.production),
|
|
324
|
-
development: published(this.plan.publication.development),
|
|
325
|
-
};
|
|
326
|
-
const exposures = Object.fromEntries(
|
|
327
|
-
core.variables
|
|
328
|
-
.filter((variable) => variable.exposure)
|
|
329
|
-
.map((variable) => {
|
|
330
|
-
const record = this.typeMap.get(variable.type);
|
|
331
|
-
if (record?.kind !== "record") throw new Error("Invalid exposure record.");
|
|
332
|
-
const root = required(this.references.get(variable.id));
|
|
333
|
-
const fields = Object.fromEntries(
|
|
334
|
-
record.fields
|
|
335
|
-
.filter((field) => field.name !== "contractVersion")
|
|
336
|
-
.map((field) => {
|
|
337
|
-
const type = this.typeMap.get(field.type);
|
|
338
|
-
const kind =
|
|
339
|
-
type?.kind === "bool" ? "boolean" : type?.kind === "string" ? "string" : "number";
|
|
340
|
-
return [
|
|
341
|
-
field.name,
|
|
342
|
-
{ path: `${root}.${this.targetTypes.field(record.id, field.name)}`, kind },
|
|
343
|
-
];
|
|
344
|
-
}),
|
|
345
|
-
);
|
|
346
|
-
return [
|
|
347
|
-
variable.exposure!.name,
|
|
348
|
-
{
|
|
349
|
-
version: variable.exposure!.version,
|
|
350
|
-
versionPath: `${root}.${this.targetTypes.field(record.id, "contractVersion")}`,
|
|
351
|
-
telemetry: fields,
|
|
352
|
-
},
|
|
353
|
-
];
|
|
354
|
-
}),
|
|
355
|
-
);
|
|
356
|
-
artifacts.push(
|
|
357
|
-
{ path: "exposures.json", content: JSON.stringify(exposures, null, 2) + "\n" },
|
|
358
|
-
{
|
|
359
|
-
path: "machines.ts",
|
|
360
|
-
content: `// Generated explicit read-only machine interfaces. Do not edit.\nexport const machines=${JSON.stringify(exposures, null, 2)} as const;\nexport const serviceChannels=${JSON.stringify(this.rpcChannels, null, 2)} as const;\n`,
|
|
361
|
-
},
|
|
362
|
-
);
|
|
363
|
-
return {
|
|
364
|
-
artifacts,
|
|
365
|
-
objects,
|
|
366
|
-
mappings,
|
|
367
|
-
ioSymbols,
|
|
368
|
-
ioMappings,
|
|
369
|
-
publication,
|
|
370
|
-
debug,
|
|
371
|
-
diagnostics: [],
|
|
372
|
-
};
|
|
373
|
-
}
|
|
374
|
-
|
|
375
|
-
private objectPath(object: GeneratedObject): string {
|
|
376
|
-
const { core } = this.plan;
|
|
377
|
-
if (object.kind === "method" && object.parent) {
|
|
378
|
-
const parent = required(this.objects.find((candidate) => candidate.id === object.parent));
|
|
379
|
-
return `${this.objectPath(parent)}/methods/${object.name}`;
|
|
380
|
-
}
|
|
381
|
-
if (object.kind === "method") {
|
|
382
|
-
const method = required(core.functions.find((fn) => fn.id === object.id));
|
|
383
|
-
const owner = required(this.objects.find((item) => item.id === method.owner?.block));
|
|
384
|
-
return `${this.objectPath(owner)}/methods/${object.name}`;
|
|
385
|
-
}
|
|
386
|
-
let source = object.id.split(":")[0] ?? "";
|
|
387
|
-
const program = core.programs.find((item) => item.id === object.id);
|
|
388
|
-
if (program) source = program.entry.split(":")[0] ?? "";
|
|
389
|
-
const group = this.globals.find((item) => item.id === object.id);
|
|
390
|
-
if (group) {
|
|
391
|
-
// Variable IDs are relative to tsconfig, unlike their diagnostic spans.
|
|
392
|
-
source = group.variables[0]?.id.split(":")[0] ?? "";
|
|
393
|
-
}
|
|
394
|
-
if (
|
|
395
|
-
/^[\w./ -]+\.tsx?$/.test(source) &&
|
|
396
|
-
!source.split(/[\\/]/).includes("..") &&
|
|
397
|
-
!source.startsWith("/")
|
|
398
|
-
) {
|
|
399
|
-
const segments = source.replaceAll("\\", "/").split("/").slice(0, -1);
|
|
400
|
-
if (segments[0] === "src") segments.shift();
|
|
401
|
-
// A DUT directory can also contain sibling input/output layouts. Keep
|
|
402
|
-
// that directory for every DUT, or its primary type would block the folder.
|
|
403
|
-
if (object.kind !== "dataType" && segments.at(-1) === object.name) segments.pop();
|
|
404
|
-
return [...segments, object.name].join("/");
|
|
405
|
-
}
|
|
406
|
-
return `${object.kind === "dataType" ? "Types" : object.id === "io" ? "IO" : "_Generated"}/${object.name}`;
|
|
407
|
-
}
|
|
408
|
-
|
|
409
|
-
private emitGlobals(): void {
|
|
410
|
-
const { options } = this.plan;
|
|
411
|
-
const { globals, references, mappings, targetTypes, typeMap, objects } = this;
|
|
412
|
-
for (const group of globals) {
|
|
413
|
-
const { name, fields } = group;
|
|
414
|
-
const published = new Set(this.plan.publication[options.buildTarget]);
|
|
415
|
-
const publish = group.variables.some((variable) => published.has(variable.id));
|
|
416
|
-
const lines = [
|
|
417
|
-
...(publish ? ["{attribute 'linkalways'}"] : []),
|
|
418
|
-
"{attribute 'qualified_only'}",
|
|
419
|
-
group.storage === "constants"
|
|
420
|
-
? "VAR_GLOBAL CONSTANT"
|
|
421
|
-
: group.storage === "retained"
|
|
422
|
-
? "VAR_GLOBAL RETAIN"
|
|
423
|
-
: "VAR_GLOBAL",
|
|
424
|
-
];
|
|
425
|
-
for (const item of group.variables) {
|
|
426
|
-
const field = required(fields.get(item.id));
|
|
427
|
-
references.set(item.id, `${name}.${field}`);
|
|
428
|
-
if (published.has(item.id))
|
|
429
|
-
lines.push(` {attribute 'symbol' := '${item.exposure ? "read" : "readwrite"}'}`);
|
|
430
|
-
mappings.push({ path: `${name}.st`, line: lines.length + 1, span: item.span });
|
|
431
|
-
let initial = "";
|
|
432
|
-
if (!instancedBlock(item.type, typeMap)) {
|
|
433
|
-
const value = item.initial ?? defaultValue(item.type, typeMap);
|
|
434
|
-
// CONSTANT declarations always keep their initializer. Mutable zero
|
|
435
|
-
// aggregates use the same implicit initialization as the original ST.
|
|
436
|
-
initial =
|
|
437
|
-
group.storage === "constants"
|
|
438
|
-
? ` := ${targetTypes.literal(value, item.type)}`
|
|
439
|
-
: targetTypes.declarationInitializer(value, item.type);
|
|
440
|
-
}
|
|
441
|
-
lines.push(` ${field} : ${targetTypes.name(item.type)}${initial};`);
|
|
442
|
-
}
|
|
443
|
-
lines.push("END_VAR");
|
|
444
|
-
objects.push({
|
|
445
|
-
id: group.id,
|
|
446
|
-
kind: "globalList",
|
|
447
|
-
name,
|
|
448
|
-
declaration: `${lines.join("\n")}\n`,
|
|
449
|
-
});
|
|
450
|
-
}
|
|
451
|
-
}
|
|
452
|
-
|
|
453
|
-
private emitIo(): void {
|
|
454
|
-
const { core, options } = this.plan;
|
|
455
|
-
const { names, references, channels, ioMappings, mappings, targetTypes, typeMap, objects } =
|
|
456
|
-
this;
|
|
457
|
-
const ioName = names.allocate("GVL_IO");
|
|
458
|
-
const ioFields = new Names();
|
|
459
|
-
for (const name of this.blockNames.values()) ioFields.reserve(name);
|
|
460
|
-
const ioLines = ["{attribute 'linkalways'}", "{attribute 'qualified_only'}", "VAR_GLOBAL"];
|
|
461
|
-
for (const item of core.variables.filter(
|
|
462
|
-
(item) => item.storage === "input" || item.storage === "output",
|
|
463
|
-
)) {
|
|
464
|
-
const field = ioFields.allocate(item.name);
|
|
465
|
-
const initial = item.initial ?? defaultValue(item.type, typeMap);
|
|
466
|
-
const binding = required(options.io[item.name]);
|
|
467
|
-
references.set(item.id, `${ioName}.${field}`);
|
|
468
|
-
if (binding.mapped) {
|
|
469
|
-
ioMappings.push({
|
|
470
|
-
key: item.name,
|
|
471
|
-
address: binding.address,
|
|
472
|
-
variable: `${ioName}.${field}`,
|
|
473
|
-
});
|
|
474
|
-
mappings.push({ path: `${ioName}.st`, line: ioLines.length + 2, span: item.span });
|
|
475
|
-
ioLines.push(
|
|
476
|
-
" {attribute 'symbol' := 'read'}",
|
|
477
|
-
` ${field} : ${targetTypes.name(item.type)} := ${targetTypes.literal(initial, item.type)};`,
|
|
478
|
-
);
|
|
479
|
-
continue;
|
|
480
|
-
}
|
|
481
|
-
const wire = ioFields.allocate(`${item.name}_physical`);
|
|
482
|
-
channels.push({
|
|
483
|
-
key: item.name,
|
|
484
|
-
root: item.id,
|
|
485
|
-
input: item.storage === "input",
|
|
486
|
-
target: `${ioName}.${field}`,
|
|
487
|
-
wire: `${ioName}.${wire}`,
|
|
488
|
-
inverted: binding.inverted,
|
|
489
|
-
});
|
|
490
|
-
mappings.push(
|
|
491
|
-
{ path: `${ioName}.st`, line: ioLines.length + 1, span: item.span },
|
|
492
|
-
{ path: `${ioName}.st`, line: ioLines.length + 3, span: item.span },
|
|
493
|
-
);
|
|
494
|
-
ioLines.push(
|
|
495
|
-
` ${wire} AT ${binding.address} : ${targetTypes.name(item.type)};`,
|
|
496
|
-
// Publish the scan's logical value for monitoring. Physical wires stay
|
|
497
|
-
// private; external writes cannot alter the controller's IO snapshot.
|
|
498
|
-
" {attribute 'symbol' := 'read'}",
|
|
499
|
-
` ${field} : ${targetTypes.name(item.type)} := ${targetTypes.literal(initial, item.type)};`,
|
|
500
|
-
);
|
|
501
|
-
}
|
|
502
|
-
for (const { key, root, segments, type } of this.plan.storageBindings) {
|
|
503
|
-
const { address, mapped, inverted } = required(options.io[key]);
|
|
504
|
-
const target = this.bindingTarget({ root, segments });
|
|
505
|
-
if (mapped) {
|
|
506
|
-
ioMappings.push({ key, address, variable: target });
|
|
507
|
-
continue;
|
|
508
|
-
}
|
|
509
|
-
const wire = ioFields.allocate(`${key.replace(/\W+/g, "_").replace(/_+$/, "")}_physical`);
|
|
510
|
-
// The wire takes the target's own type, so equal-width EDS types need no conversion.
|
|
511
|
-
ioLines.push(` ${wire} AT ${address} : ${targetTypes.name(type.id)};`);
|
|
512
|
-
channels.push({
|
|
513
|
-
key,
|
|
514
|
-
root: root.id,
|
|
515
|
-
input: address[1] === "I",
|
|
516
|
-
target,
|
|
517
|
-
wire: `${ioName}.${wire}`,
|
|
518
|
-
inverted,
|
|
519
|
-
});
|
|
520
|
-
}
|
|
521
|
-
ioLines.push("END_VAR");
|
|
522
|
-
// Mapped storage bindings need no IO list; mapped logical IO is declared here.
|
|
523
|
-
if (ioLines.length > 4)
|
|
524
|
-
objects.push({
|
|
525
|
-
id: "io",
|
|
526
|
-
kind: "globalList",
|
|
527
|
-
name: ioName,
|
|
528
|
-
declaration: `${ioLines.join("\n")}\n`,
|
|
529
|
-
});
|
|
530
|
-
}
|
|
531
|
-
|
|
532
|
-
/** The target symbol of an `io` storage path. */
|
|
533
|
-
private bindingTarget({ root, segments }: Pick<StorageBinding, "root" | "segments">): string {
|
|
534
|
-
return segments.reduce(
|
|
535
|
-
(path, segment) =>
|
|
536
|
-
segment.kind === "field"
|
|
537
|
-
? `${path}.${this.targetTypes.field(segment.record, segment.name)}`
|
|
538
|
-
: `${path}[${segment.value}]`,
|
|
539
|
-
required(this.references.get(root.id)),
|
|
540
|
-
);
|
|
541
|
-
}
|
|
542
|
-
|
|
543
|
-
private prepareStatements(items: readonly CoreStatement[]): void {
|
|
544
|
-
const { numeric } = this;
|
|
545
|
-
for (const item of items) {
|
|
546
|
-
if (item.kind === "assign") {
|
|
547
|
-
numeric.prepare(item.value);
|
|
548
|
-
item.path?.forEach((segment) => {
|
|
549
|
-
if (segment.kind === "index") numeric.prepare(segment.value);
|
|
550
|
-
});
|
|
551
|
-
}
|
|
552
|
-
if (item.kind === "if") {
|
|
553
|
-
numeric.prepare(item.condition);
|
|
554
|
-
this.prepareStatements(item.then);
|
|
555
|
-
this.prepareStatements(item.else);
|
|
556
|
-
}
|
|
557
|
-
if (item.kind === "switch") {
|
|
558
|
-
numeric.prepare(item.value);
|
|
559
|
-
for (const branch of item.cases) this.prepareStatements(branch.body);
|
|
560
|
-
this.prepareStatements(item.fallback);
|
|
561
|
-
}
|
|
562
|
-
if (item.kind === "for") {
|
|
563
|
-
if (item.dynamic) {
|
|
564
|
-
numeric.prepare(item.dynamic.start);
|
|
565
|
-
numeric.prepare(item.dynamic.limit);
|
|
566
|
-
}
|
|
567
|
-
this.prepareStatements(item.body);
|
|
568
|
-
}
|
|
569
|
-
if (item.kind === "return" && item.value) numeric.prepare(item.value);
|
|
570
|
-
if (item.kind === "telemetry")
|
|
571
|
-
for (const value of telemetryOperands(item)) numeric.prepare(value);
|
|
572
|
-
if (item.kind === "invoke") {
|
|
573
|
-
if (item.index) numeric.prepare(item.index);
|
|
574
|
-
for (const value of item.arguments) numeric.prepare(value);
|
|
575
|
-
}
|
|
576
|
-
if (item.kind === "blockUpdate") {
|
|
577
|
-
if (item.index) numeric.prepare(item.index);
|
|
578
|
-
for (const value of Object.values(item.inputs)) numeric.prepare(value);
|
|
579
|
-
}
|
|
580
|
-
}
|
|
581
|
-
}
|
|
582
|
-
|
|
583
|
-
private allocateBlockFields(): void {
|
|
584
|
-
const { core } = this.plan;
|
|
585
|
-
const { objects, functionNames, blockNames, blockFields } = this;
|
|
586
|
-
for (const block of core.blocks) {
|
|
587
|
-
const fields = new Names(),
|
|
588
|
-
mapped = new Map<string, string>();
|
|
589
|
-
for (const object of objects) fields.reserve(object.name);
|
|
590
|
-
fields.reserve(this.debugGlobal);
|
|
591
|
-
for (const objectName of [
|
|
592
|
-
...core.functions.filter((fn) => !fn.owner).map((fn) => required(functionNames.get(fn.id))),
|
|
593
|
-
...blockNames.values(),
|
|
594
|
-
])
|
|
595
|
-
fields.reserve(objectName);
|
|
596
|
-
for (const method of core.functions.filter((fn) => fn.owner?.block === block.id))
|
|
597
|
-
functionNames.set(method.id, fields.allocate(method.name));
|
|
598
|
-
const native = block.standard && standardBlocks[block.standard];
|
|
599
|
-
for (const item of [...block.inputs, ...block.outputs, ...block.state])
|
|
600
|
-
mapped.set(
|
|
601
|
-
item.id,
|
|
602
|
-
native
|
|
603
|
-
? required(
|
|
604
|
-
[...native.inputs, ...native.outputs].find(([name]) => name === item.name),
|
|
605
|
-
)[1]
|
|
606
|
-
: fields.allocate(item.name, true),
|
|
607
|
-
);
|
|
608
|
-
if (block.runtime?.kind === "mailbox")
|
|
609
|
-
this.mailboxLocks.set(block.id, fields.allocate("plc_mailbox_lock"));
|
|
610
|
-
blockFields.set(block.id, mapped);
|
|
611
|
-
|
|
612
|
-
const settings = this.plan.project.debug;
|
|
613
|
-
// Trace sites and an unhandled failure need the step a job finished at.
|
|
614
|
-
const stepped =
|
|
615
|
-
this.debug.jobSites.has(block.id) || this.plan.telemetry?.failures.has(block.id);
|
|
616
|
-
const tracked = Boolean(block.job && (settings?.jobs || stepped));
|
|
617
|
-
const carries = settings?.jobs && this.debug.carriers.has(block.id);
|
|
618
|
-
if (tracked || carries)
|
|
619
|
-
this.debugFields.set(block.id, {
|
|
620
|
-
...(tracked && {
|
|
621
|
-
busy: fields.allocate("tsplcBusy"),
|
|
622
|
-
track: fields.allocate("TsplcTrack"),
|
|
623
|
-
}),
|
|
624
|
-
...(tracked && settings?.jobs && { startedAt: fields.allocate("startedAt") }),
|
|
625
|
-
...(stepped && { step: fields.allocate("tsplcStep") }),
|
|
626
|
-
...(carries && { job: fields.allocate("requestJob") }),
|
|
627
|
-
...(carries &&
|
|
628
|
-
block.runtime?.kind === "http" && { sequence: fields.allocate("sequence") }),
|
|
629
|
-
});
|
|
630
|
-
}
|
|
631
|
-
}
|
|
632
|
-
|
|
633
|
-
private allocateRoutineScope(fn: CoreFunction | CoreFunctionBlock): void {
|
|
634
|
-
const block = "inputs" in fn ? fn : undefined;
|
|
635
|
-
const owner =
|
|
636
|
-
block ?? ("owner" in fn && fn.owner ? this.blocks.get(fn.owner.block) : undefined);
|
|
637
|
-
const names = new Names(),
|
|
638
|
-
references = new Map<string, string>();
|
|
639
|
-
for (const object of this.objects) names.reserve(object.name);
|
|
640
|
-
names.reserve(this.debugGlobal);
|
|
641
|
-
for (const name of [...this.functionNames.values(), ...this.blockNames.values()])
|
|
642
|
-
names.reserve(name);
|
|
643
|
-
if (this.programRoutines.has(fn.id) && "parameters" in fn && fn.result)
|
|
644
|
-
this.programResults.set(fn.id, names.allocate("plc_result"));
|
|
645
|
-
if (owner) {
|
|
646
|
-
for (const item of [...owner.outputs, ...owner.state]) {
|
|
647
|
-
const name = required(required(this.blockFields.get(owner.id)).get(item.id));
|
|
648
|
-
names.reserve(name);
|
|
649
|
-
references.set(item.id, name);
|
|
650
|
-
}
|
|
651
|
-
}
|
|
652
|
-
for (const item of "parameters" in fn ? fn.parameters : fn.inputs) {
|
|
653
|
-
const name = block
|
|
654
|
-
? required(required(this.blockFields.get(block.id)).get(item.id))
|
|
655
|
-
: names.allocate(item.name);
|
|
656
|
-
names.reserve(name);
|
|
657
|
-
references.set(item.id, name);
|
|
658
|
-
}
|
|
659
|
-
for (const item of fn.locals) references.set(item.id, names.allocate(item.name));
|
|
660
|
-
this.routineScopes.set(fn.id, { names, references });
|
|
661
|
-
}
|
|
662
|
-
|
|
663
|
-
private routineHeader(
|
|
664
|
-
fn: CoreFunction | CoreFunctionBlock,
|
|
665
|
-
name: string,
|
|
666
|
-
): { kind: GeneratedObject["kind"]; declaration: string } {
|
|
667
|
-
if ("inputs" in fn) return { kind: "functionBlock", declaration: `FUNCTION_BLOCK ${name}` };
|
|
668
|
-
if (fn.owner)
|
|
669
|
-
return {
|
|
670
|
-
kind: "method",
|
|
671
|
-
declaration: `METHOD ${fn.owner.access.toUpperCase()} ${name}${fn.result ? ` : ${this.targetTypes.name(fn.result)}` : ""}`,
|
|
672
|
-
};
|
|
673
|
-
if (this.programRoutines.has(fn.id)) return { kind: "program", declaration: `PROGRAM ${name}` };
|
|
674
|
-
return {
|
|
675
|
-
kind: "function",
|
|
676
|
-
declaration: `FUNCTION ${name} : ${fn.result ? this.targetTypes.name(fn.result) : "BOOL"}`,
|
|
677
|
-
};
|
|
678
|
-
}
|
|
679
|
-
|
|
680
|
-
private emitRoutine(fn: CoreFunction | CoreFunctionBlock): void {
|
|
681
|
-
const { core } = this.plan;
|
|
682
|
-
if ("inputs" in fn && (fn.runtime?.kind === "http" || fn.runtime?.kind === "rpc")) {
|
|
683
|
-
const endpoint = required(this.plan.http[fn.id]);
|
|
684
|
-
const rpcGlobal =
|
|
685
|
-
endpoint.transport === "opcua"
|
|
686
|
-
? this.names.allocateObject("GVL", "TsplcRpc_" + required(this.blockNames.get(fn.id)))
|
|
687
|
-
: undefined;
|
|
688
|
-
if (rpcGlobal) {
|
|
689
|
-
this.objects.push({
|
|
690
|
-
id: fn.id + ":rpc",
|
|
691
|
-
kind: "globalList",
|
|
692
|
-
name: rpcGlobal,
|
|
693
|
-
declaration: `{attribute 'qualified_only'}
|
|
694
|
-
VAR_GLOBAL
|
|
695
|
-
{attribute 'symbol' := 'read'} requests:ARRAY[1..${opcuaServiceCapacity}] OF STRING(2048);
|
|
696
|
-
{attribute 'symbol' := 'read'} requestIds:ARRAY[1..${opcuaServiceCapacity}] OF STRING(64);
|
|
697
|
-
{attribute 'symbol' := 'readwrite'} replyIds:ARRAY[1..${opcuaServiceCapacity}] OF STRING(64);
|
|
698
|
-
{attribute 'symbol' := 'readwrite'} replies:ARRAY[1..${opcuaServiceCapacity}] OF STRING(2048);
|
|
699
|
-
{attribute 'symbol' := 'readwrite'} epochs:ARRAY[1..${opcuaServiceCapacity}] OF STRING(32);
|
|
700
|
-
inUse:ARRAY[1..${opcuaServiceCapacity}] OF __XWORD;
|
|
701
|
-
sequence:ARRAY[1..${opcuaServiceCapacity}] OF UDINT;
|
|
702
|
-
END_VAR`,
|
|
703
|
-
});
|
|
704
|
-
for (let slot = 1; slot <= opcuaServiceCapacity; slot++)
|
|
705
|
-
this.rpcChannels.push({
|
|
706
|
-
path: endpoint.path,
|
|
707
|
-
request: `${rpcGlobal}.requests[${slot}]`,
|
|
708
|
-
reply: `${rpcGlobal}.replies[${slot}]`,
|
|
709
|
-
requestId: `${rpcGlobal}.requestIds[${slot}]`,
|
|
710
|
-
replyId: `${rpcGlobal}.replyIds[${slot}]`,
|
|
711
|
-
epoch: `${rpcGlobal}.epochs[${slot}]`,
|
|
712
|
-
});
|
|
713
|
-
}
|
|
714
|
-
const requestFields = this.debugFields.get(fn.id);
|
|
715
|
-
const generated = emitHttp(
|
|
716
|
-
fn,
|
|
717
|
-
required(this.blockNames.get(fn.id)),
|
|
718
|
-
required(this.blockFields.get(fn.id)),
|
|
719
|
-
this.typeMap,
|
|
720
|
-
this.targetTypes,
|
|
721
|
-
endpoint,
|
|
722
|
-
this.networkName ? `${this.networkName}.network` : "",
|
|
723
|
-
rpcGlobal,
|
|
724
|
-
requestFields?.job && requestFields.sequence
|
|
725
|
-
? { job: requestFields.job, sequence: requestFields.sequence }
|
|
726
|
-
: undefined,
|
|
727
|
-
);
|
|
728
|
-
this.objects.push(
|
|
729
|
-
generated,
|
|
730
|
-
...httpMethods(generated.id, endpoint.transport),
|
|
731
|
-
...httpCertificateVerifier(generated.id, generated.name, required(this.plan.http[fn.id])),
|
|
732
|
-
);
|
|
733
|
-
return;
|
|
734
|
-
}
|
|
735
|
-
const {
|
|
736
|
-
blockNames,
|
|
737
|
-
functionNames,
|
|
738
|
-
references,
|
|
739
|
-
objects,
|
|
740
|
-
mappings,
|
|
741
|
-
targetTypes,
|
|
742
|
-
typeMap,
|
|
743
|
-
blocks,
|
|
744
|
-
blockFields,
|
|
745
|
-
numeric,
|
|
746
|
-
retainedVariables,
|
|
747
|
-
} = this;
|
|
748
|
-
const block = "inputs" in fn ? fn : undefined;
|
|
749
|
-
const method = "owner" in fn ? fn.owner : undefined;
|
|
750
|
-
const program = this.programRoutines.has(fn.id);
|
|
751
|
-
const owner = method ? required(blocks.get(method.block)) : block;
|
|
752
|
-
const name = block ? required(blockNames.get(block.id)) : required(functionNames.get(fn.id));
|
|
753
|
-
const inputs = "parameters" in fn ? fn.parameters : fn.inputs;
|
|
754
|
-
const state = owner ? [...owner.outputs, ...owner.state] : [];
|
|
755
|
-
const mappingName = method ? fn.id : name;
|
|
756
|
-
const routineScope = required(this.routineScopes.get(fn.id));
|
|
757
|
-
const scope = new Map([...references, ...routineScope.references]),
|
|
758
|
-
locals = routineScope.names;
|
|
759
|
-
const declarations = fn.locals.map(
|
|
760
|
-
(item) => ` ${required(scope.get(item.id))} : ${targetTypes.name(item.type)};`,
|
|
761
|
-
);
|
|
762
|
-
const declarationSpans = fn.locals.map((item) => item.span);
|
|
763
|
-
const mutex =
|
|
764
|
-
method && owner?.runtime?.kind === "mailbox"
|
|
765
|
-
? required(this.mailboxLocks.get(owner.id))
|
|
766
|
-
: undefined;
|
|
767
|
-
const acquired = mutex ? locals.allocate("plc_acquired") : undefined;
|
|
768
|
-
const unavailable = mutex && fn.result ? locals.allocate("plc_unavailable") : undefined;
|
|
769
|
-
if (acquired) {
|
|
770
|
-
declarations.push(` ${acquired} : BOOL;`);
|
|
771
|
-
declarationSpans.push(fn.span);
|
|
772
|
-
}
|
|
773
|
-
if (unavailable && fn.result) {
|
|
774
|
-
declarations.push(
|
|
775
|
-
` ${unavailable} : ${targetTypes.name(fn.result)} := ${targetTypes.literal(defaultValue(fn.result, typeMap), fn.result)};`,
|
|
776
|
-
);
|
|
777
|
-
declarationSpans.push(fn.span);
|
|
778
|
-
}
|
|
779
|
-
// Count target lines as they are appended; diagnostics use these exact offsets.
|
|
780
|
-
const lines: string[] = [];
|
|
781
|
-
const write = (line: string, depth: number, source?: SourceSpan): void => {
|
|
782
|
-
lines.push(" ".repeat(depth) + line);
|
|
783
|
-
if (source)
|
|
784
|
-
mappings.push({
|
|
785
|
-
path: `${mappingName}/implementation.st`,
|
|
786
|
-
line: lines.length,
|
|
787
|
-
span: source,
|
|
788
|
-
});
|
|
789
|
-
};
|
|
790
|
-
|
|
791
|
-
// Only the holder releases, so a failed swap is spurious (see the acquire above); retry it.
|
|
792
|
-
const release = (lock: string, depth: number, source?: SourceSpan) => {
|
|
793
|
-
write(`WHILE NOT __COMPARE_AND_SWAP(ADR(${lock}), 1, 0) DO`, depth, source);
|
|
794
|
-
write(";", depth + 1);
|
|
795
|
-
write("END_WHILE;", depth);
|
|
796
|
-
};
|
|
797
|
-
|
|
798
|
-
const load = (id: string): string => {
|
|
799
|
-
const value = scope.get(id);
|
|
800
|
-
if (!value) throw new Error(`Missing verified storage ${id}.`);
|
|
801
|
-
return value;
|
|
802
|
-
};
|
|
803
|
-
const scopeTypes = new Map(
|
|
804
|
-
[...core.variables, ...inputs, ...state, ...fn.locals].map((variable) => [
|
|
805
|
-
variable.id,
|
|
806
|
-
variable.type,
|
|
807
|
-
]),
|
|
808
|
-
);
|
|
809
|
-
|
|
810
|
-
// Block output records are a source abstraction; target FB fields are direct.
|
|
811
|
-
const place = (id: string, path: CorePath = []): string => {
|
|
812
|
-
let text = load(id),
|
|
813
|
-
typeId = required(scopeTypes.get(id));
|
|
814
|
-
let outputBlock: string | undefined;
|
|
815
|
-
for (const segment of path) {
|
|
816
|
-
const type = required(typeMap.get(typeId));
|
|
817
|
-
if (segment.kind === "field" && type.kind === "block" && segment.name === "out") {
|
|
818
|
-
outputBlock = type.block;
|
|
819
|
-
typeId = required(type.output);
|
|
820
|
-
continue;
|
|
821
|
-
}
|
|
822
|
-
if (segment.kind === "field" && outputBlock) {
|
|
823
|
-
const output = required(
|
|
824
|
-
required(blocks.get(outputBlock)).outputs.find((field) => field.name === segment.name),
|
|
825
|
-
);
|
|
826
|
-
text += `.${required(required(blockFields.get(outputBlock)).get(output.id))}`;
|
|
827
|
-
typeId = output.type;
|
|
828
|
-
outputBlock = undefined;
|
|
829
|
-
} else if (segment.kind === "field" && type.kind === "record") {
|
|
830
|
-
text += `.${targetTypes.field(typeId, segment.name)}`;
|
|
831
|
-
typeId = required(type.fields.find((field) => field.name === segment.name)).type;
|
|
832
|
-
} else if (segment.kind === "index" && type.kind === "array") {
|
|
833
|
-
// A strict enum converts explicitly to its DINT base, as HTTP JSON encoding does.
|
|
834
|
-
text +=
|
|
835
|
-
typeMap.get(segment.value.type)?.kind === "enum"
|
|
836
|
-
? `[TO_DINT(${expression(segment.value)})]`
|
|
837
|
-
: `[${expression(segment.value)}]`;
|
|
838
|
-
typeId = type.element;
|
|
839
|
-
} else throw new Error("Invalid verified place");
|
|
840
|
-
}
|
|
841
|
-
return text;
|
|
842
|
-
};
|
|
843
|
-
|
|
844
|
-
const expression = (value: CoreExpression): string => {
|
|
845
|
-
if (value.kind === "constant") return targetTypes.literal(value.value, value.type);
|
|
846
|
-
if (value.kind === "load") return place(value.root, value.path);
|
|
847
|
-
if (value.kind === "borrow") return place(value.place.root, value.place.path);
|
|
848
|
-
if (value.kind === "convert" && typeMap.get(value.type)?.kind === "string")
|
|
849
|
-
return expression(value.operand);
|
|
850
|
-
if (value.kind === "unary" || value.kind === "convert")
|
|
851
|
-
return numeric.render(value, [expression(value.operand)]);
|
|
852
|
-
return numeric.render(value, [expression(value.left), expression(value.right)]);
|
|
853
|
-
};
|
|
854
|
-
|
|
855
|
-
// Aggregate constants are expanded into legal leaf assignments for ST.
|
|
856
|
-
const assignConstant = (
|
|
857
|
-
destination: string,
|
|
858
|
-
value: Constant,
|
|
859
|
-
id: string,
|
|
860
|
-
depth: number,
|
|
861
|
-
span: SourceSpan,
|
|
862
|
-
): void => {
|
|
863
|
-
const type = required(typeMap.get(id));
|
|
864
|
-
if (type.kind === "record" && value.kind === "record")
|
|
865
|
-
type.fields.forEach((field) => {
|
|
866
|
-
assignConstant(
|
|
867
|
-
`${destination}.${targetTypes.field(id, field.name)}`,
|
|
868
|
-
required(value.fields[field.name]),
|
|
869
|
-
field.type,
|
|
870
|
-
depth,
|
|
871
|
-
span,
|
|
872
|
-
);
|
|
873
|
-
});
|
|
874
|
-
else if (type.kind === "array" && value.kind === "array")
|
|
875
|
-
value.items.forEach((item, index) => {
|
|
876
|
-
assignConstant(
|
|
877
|
-
`${destination}[${type.lowerBound + index}]`,
|
|
878
|
-
item,
|
|
879
|
-
type.element,
|
|
880
|
-
depth,
|
|
881
|
-
span,
|
|
882
|
-
);
|
|
883
|
-
});
|
|
884
|
-
else write(`${destination} := ${targetTypes.literal(value, id)};`, depth, span);
|
|
885
|
-
};
|
|
886
|
-
|
|
887
|
-
const ring = (task = this.debug.tasks.get(fn.id)) =>
|
|
888
|
-
`${this.debugGlobal}.${required(this.rings.get(required(task)))}`;
|
|
889
|
-
// Trace operands are DINTs: BOOL as 0/1, enums by value, integers clamped to the DINT range.
|
|
890
|
-
const encode = (value: CoreExpression): string => {
|
|
891
|
-
const type = required(typeMap.get(value.type));
|
|
892
|
-
const text = expression(value);
|
|
893
|
-
if (type.kind === "bool") return `BOOL_TO_DINT(${text})`;
|
|
894
|
-
if (type.kind !== "integer" && type.kind !== "bits") return `TO_DINT(${text})`;
|
|
895
|
-
const signed = type.kind === "integer" && type.signed;
|
|
896
|
-
if (type.bits < 32 || (signed && type.bits === 32)) return `TO_DINT(${text})`;
|
|
897
|
-
if (signed) return `TO_DINT(LIMIT(LINT#-2147483648, ${text}, LINT#2147483647))`;
|
|
898
|
-
const wide = type.bits === 32 ? "UDINT" : "ULINT";
|
|
899
|
-
return `TO_DINT(MIN(TO_${wide}(${text}), ${wide}#2147483647))`;
|
|
900
|
-
};
|
|
901
|
-
// CODESYS requires every input, so operands a site lacks are passed as 0.
|
|
902
|
-
const record = (site: number, value: string, operands: readonly Operand[] = []): string => {
|
|
903
|
-
const captured = Array.from(
|
|
904
|
-
{ length: required(this.plan.telemetry?.traceOperands) },
|
|
905
|
-
(_, index) => {
|
|
906
|
-
const operand = operands[index];
|
|
907
|
-
return `, operand${index} := ${operand ? encode(operand.capture) : "DINT#0"}`;
|
|
908
|
-
},
|
|
909
|
-
);
|
|
910
|
-
return `${ring()}.Trace(site := UINT#${site}, value := ${value}, operands := USINT#${operands.length}${captured.join("")});`;
|
|
911
|
-
};
|
|
912
|
-
const instrument = (item: CoreStatement, depth: number): void => {
|
|
913
|
-
for (const probe of this.debug.probes.get(item) ?? []) {
|
|
914
|
-
if (probe.kind === "writer") {
|
|
915
|
-
const writer = `${this.debugGlobal}.${this.debugSlots.writers}[${probe.output}] := UINT#${probe.site};`;
|
|
916
|
-
if (!probe.when.length) {
|
|
917
|
-
write(writer, depth, item.span);
|
|
918
|
-
continue;
|
|
919
|
-
}
|
|
920
|
-
const reached = probe.when.map(
|
|
921
|
-
({ index, value }) => `TO_DINT(${expression(index)}) = DINT#${value}`,
|
|
922
|
-
);
|
|
923
|
-
write(`IF ${reached.join(" AND ")} THEN`, depth, item.span);
|
|
924
|
-
write(writer, depth + 1, item.span);
|
|
925
|
-
write("END_IF;", depth, item.span);
|
|
926
|
-
continue;
|
|
927
|
-
}
|
|
928
|
-
const value = `TO_DINT(${expression(probe.value)})`;
|
|
929
|
-
if (item.kind === "assign")
|
|
930
|
-
write(
|
|
931
|
-
`IF ${place(item.root, item.path)} <> ${expression(probe.value)} THEN`,
|
|
932
|
-
depth,
|
|
933
|
-
item.span,
|
|
934
|
-
);
|
|
935
|
-
else {
|
|
936
|
-
const last = `${this.debugGlobal}.${this.debugSlots.decisions}[${required(probe.slot)}]`;
|
|
937
|
-
write(`IF ${value} <> ${last} THEN`, depth, item.span);
|
|
938
|
-
write(`${last} := ${value};`, depth + 1, item.span);
|
|
939
|
-
}
|
|
940
|
-
write(record(probe.site, value, probe.operands), depth + 1, item.span);
|
|
941
|
-
write("END_IF;", depth, item.span);
|
|
942
|
-
}
|
|
943
|
-
};
|
|
944
|
-
|
|
945
|
-
const tracked = block && this.debugFields.get(block.id);
|
|
946
|
-
const jobField = (job: CoreFunctionBlock, name: string) =>
|
|
947
|
-
load(required(job.state.find((item) => item.name === name)).id);
|
|
948
|
-
/**
|
|
949
|
-
* The job's tracking method, which records it starting or finishing. The job calls it on
|
|
950
|
-
* entry and on every exit: its caller stops calling it once it is done, so only the call that
|
|
951
|
-
* finishes it sees the finish.
|
|
952
|
-
*/
|
|
953
|
-
const jobTracking = (job: CoreFunctionBlock, fields: NonNullable<typeof tracked>) => {
|
|
954
|
-
const busy = jobField(job, "busy");
|
|
955
|
-
const sites = this.debug.jobSites.get(job.id);
|
|
956
|
-
const failure = this.plan.telemetry?.failures.get(job.id);
|
|
957
|
-
const lines: string[] = [];
|
|
958
|
-
const line = (text: string, depth: number) => lines.push(" ".repeat(depth) + text);
|
|
959
|
-
line(`IF ${busy} = ${required(fields.busy)} THEN`, 0);
|
|
960
|
-
line("RETURN;", 1);
|
|
961
|
-
line("END_IF;", 0);
|
|
962
|
-
if (fields.startedAt || sites) {
|
|
963
|
-
line(`IF ${busy} THEN`, 0);
|
|
964
|
-
if (fields.startedAt) line(`${fields.startedAt} := TIME_TO_UDINT(TIME());`, 1);
|
|
965
|
-
if (sites) line(record(sites.start, `TO_DINT(${jobField(job, "step")})`), 1);
|
|
966
|
-
line("END_IF;", 0);
|
|
967
|
-
}
|
|
968
|
-
if (sites || failure) {
|
|
969
|
-
const error = jobField(job, "error");
|
|
970
|
-
line(`IF NOT ${busy} THEN`, 0);
|
|
971
|
-
if (sites) {
|
|
972
|
-
line(`IF ${error} <> 0 THEN`, 1);
|
|
973
|
-
line(record(sites.completion, `-TO_DINT(${error})`), 2);
|
|
974
|
-
line("ELSE", 1);
|
|
975
|
-
line(record(sites.completion, `TO_DINT(${required(fields.step)})`), 2);
|
|
976
|
-
line("END_IF;", 1);
|
|
977
|
-
}
|
|
978
|
-
// Cancellation is asked for, so it isn't a failure.
|
|
979
|
-
if (failure) {
|
|
980
|
-
line(`IF ${error} <> 0 AND ${error} <> 1 THEN`, 1);
|
|
981
|
-
line(
|
|
982
|
-
`${ring(failure.task)}.Failure${failure.id}(code := ${error}, step := ${required(fields.step)});`,
|
|
983
|
-
2,
|
|
984
|
-
);
|
|
985
|
-
line("END_IF;", 1);
|
|
986
|
-
}
|
|
987
|
-
line("END_IF;", 0);
|
|
988
|
-
}
|
|
989
|
-
line(`${fields.busy} := ${busy};`, 0);
|
|
990
|
-
return `${lines.join("\n")}\n`;
|
|
991
|
-
};
|
|
992
|
-
|
|
993
|
-
const body = (items: readonly CoreStatement[], depth: number): void => {
|
|
994
|
-
for (const item of items) {
|
|
995
|
-
switch (item.kind) {
|
|
996
|
-
case "assign":
|
|
997
|
-
instrument(item, depth);
|
|
998
|
-
if (
|
|
999
|
-
tracked?.step &&
|
|
1000
|
-
block?.job &&
|
|
1001
|
-
item.root === block.state.find((field) => field.name === "step")?.id
|
|
1002
|
-
)
|
|
1003
|
-
write(`${tracked.step} := ${jobField(block, "step")};`, depth, item.span);
|
|
1004
|
-
if (item.value.kind === "constant")
|
|
1005
|
-
assignConstant(
|
|
1006
|
-
place(item.root, item.path),
|
|
1007
|
-
item.value.value,
|
|
1008
|
-
item.value.type,
|
|
1009
|
-
depth,
|
|
1010
|
-
item.span,
|
|
1011
|
-
);
|
|
1012
|
-
else
|
|
1013
|
-
write(
|
|
1014
|
-
`${place(item.root, item.path)} := ${expression(item.value)};`,
|
|
1015
|
-
depth,
|
|
1016
|
-
item.span,
|
|
1017
|
-
);
|
|
1018
|
-
break;
|
|
1019
|
-
case "blockUpdate": {
|
|
1020
|
-
const instance = instancedBlock(required(scopeTypes.get(item.instance)), typeMap);
|
|
1021
|
-
if (!instance) throw new Error("Invalid verified block receiver");
|
|
1022
|
-
const target = required(blocks.get(instance.block));
|
|
1023
|
-
const arguments_ = Object.entries(item.inputs).map(([input, value]) => {
|
|
1024
|
-
const formal = required(target.inputs.find((field) => field.name === input));
|
|
1025
|
-
return `${required(required(blockFields.get(target.id)).get(formal.id))} := ${expression(value)}`;
|
|
1026
|
-
});
|
|
1027
|
-
// Service calls report the job that made them: a single-instance job passes its own id,
|
|
1028
|
-
// and everything between it and the call passes the id it was given.
|
|
1029
|
-
const job = this.debugFields.get(target.id)?.job;
|
|
1030
|
-
const id = this.jobIds.get(item.instance);
|
|
1031
|
-
const given = owner && this.debugFields.get(owner.id)?.job;
|
|
1032
|
-
if (job && (id || given)) arguments_.push(`${job} := ${id ? `UDINT#${id}` : given}`);
|
|
1033
|
-
const receiver = item.index
|
|
1034
|
-
? `${load(item.instance)}[${expression(item.index)}]`
|
|
1035
|
-
: load(item.instance);
|
|
1036
|
-
write(`${receiver}(${arguments_.join(", ")});`, depth, item.span);
|
|
1037
|
-
break;
|
|
1038
|
-
}
|
|
1039
|
-
case "invoke": {
|
|
1040
|
-
const receiver = item.instance
|
|
1041
|
-
? `${load(item.instance)}${item.index ? `[${expression(item.index)}]` : ""}.`
|
|
1042
|
-
: "";
|
|
1043
|
-
const called = required(core.functions.find((fn) => fn.id === item.function));
|
|
1044
|
-
const programCall = this.programRoutines.has(called.id);
|
|
1045
|
-
const arguments_ = item.arguments.map((value, index) => {
|
|
1046
|
-
if (
|
|
1047
|
-
!called.owner &&
|
|
1048
|
-
!programCall &&
|
|
1049
|
-
!called.parameters.some((parameter) => parameter.mode === "inOut")
|
|
1050
|
-
)
|
|
1051
|
-
return expression(value);
|
|
1052
|
-
const parameter = required(called.parameters[index]);
|
|
1053
|
-
const formal = required(
|
|
1054
|
-
required(this.routineScopes.get(called.id)).references.get(parameter.id),
|
|
1055
|
-
);
|
|
1056
|
-
return `${formal} := ${expression(value)}`;
|
|
1057
|
-
});
|
|
1058
|
-
const call = `${receiver}${required(functionNames.get(item.function))}(${arguments_.join(", ")})`;
|
|
1059
|
-
if (programCall) {
|
|
1060
|
-
write(`${call};`, depth, item.span);
|
|
1061
|
-
if (item.destination)
|
|
1062
|
-
write(
|
|
1063
|
-
`${load(item.destination)} := ${required(functionNames.get(called.id))}.${required(this.programResults.get(called.id))};`,
|
|
1064
|
-
depth,
|
|
1065
|
-
item.span,
|
|
1066
|
-
);
|
|
1067
|
-
break;
|
|
1068
|
-
}
|
|
1069
|
-
write(
|
|
1070
|
-
item.destination ? `${load(item.destination)} := ${call};` : `${call};`,
|
|
1071
|
-
depth,
|
|
1072
|
-
item.span,
|
|
1073
|
-
);
|
|
1074
|
-
break;
|
|
1075
|
-
}
|
|
1076
|
-
case "if":
|
|
1077
|
-
write(`IF ${expression(item.condition)} THEN`, depth, item.span);
|
|
1078
|
-
body(item.then, depth + 1);
|
|
1079
|
-
if (item.else.length) {
|
|
1080
|
-
write("ELSE", depth, item.span);
|
|
1081
|
-
body(item.else, depth + 1);
|
|
1082
|
-
}
|
|
1083
|
-
write("END_IF;", depth, item.span);
|
|
1084
|
-
break;
|
|
1085
|
-
case "switch": {
|
|
1086
|
-
for (const [index, branch] of item.cases.entries()) {
|
|
1087
|
-
const conditions = branch.values.map(
|
|
1088
|
-
(value) =>
|
|
1089
|
-
`(${expression(item.value)} = ${targetTypes.literal(value, item.value.type)})`,
|
|
1090
|
-
);
|
|
1091
|
-
write(`${index ? "ELSIF" : "IF"} ${conditions.join(" OR ")} THEN`, depth, item.span);
|
|
1092
|
-
body(branch.body, depth + 1);
|
|
1093
|
-
}
|
|
1094
|
-
if (item.cases.length) {
|
|
1095
|
-
if (item.fallback.length) write("ELSE", depth, item.span);
|
|
1096
|
-
body(item.fallback, depth + 1);
|
|
1097
|
-
write("END_IF;", depth, item.span);
|
|
1098
|
-
} else body(item.fallback, depth);
|
|
1099
|
-
break;
|
|
1100
|
-
}
|
|
1101
|
-
case "for": {
|
|
1102
|
-
// Iterate with a DINT ordinal rather than overflowing the authored
|
|
1103
|
-
// counter at a width boundary. Reconstruct its typed value each scan.
|
|
1104
|
-
const counterType = scopeTypes.get(item.counter);
|
|
1105
|
-
if (!counterType || item.start.kind !== "integer")
|
|
1106
|
-
throw new Error("Invalid verified loop");
|
|
1107
|
-
if (!item.maxIterations) {
|
|
1108
|
-
if (item.counterScope === "existing")
|
|
1109
|
-
write(
|
|
1110
|
-
`${load(item.counter)} := ${item.dynamic ? expression(item.dynamic.start) : targetTypes.literal(item.start, counterType)};`,
|
|
1111
|
-
depth,
|
|
1112
|
-
item.span,
|
|
1113
|
-
);
|
|
1114
|
-
break;
|
|
1115
|
-
}
|
|
1116
|
-
const ordinal = locals.allocate("iteration");
|
|
1117
|
-
declarations.push(` ${ordinal} : DINT;`);
|
|
1118
|
-
declarationSpans.push(item.span);
|
|
1119
|
-
const wide = counterType === "ULINT" ? "ULINT" : "LINT";
|
|
1120
|
-
const ascending = BigInt(item.step) > 0n;
|
|
1121
|
-
const step = BigInt(item.step) < 0n ? -BigInt(item.step) : BigInt(item.step);
|
|
1122
|
-
let iterations = `DINT#${item.maxIterations}`;
|
|
1123
|
-
let first = `${wide}#${item.start.value}`;
|
|
1124
|
-
if (item.dynamic) {
|
|
1125
|
-
first = `TO_${wide}(${expression(item.dynamic.start)})`;
|
|
1126
|
-
const last = `TO_${wide}(${expression(item.dynamic.limit)})`;
|
|
1127
|
-
const count = locals.allocate("iterationCount");
|
|
1128
|
-
declarations.push(` ${count} : DINT;`);
|
|
1129
|
-
declarationSpans.push(item.span);
|
|
1130
|
-
const comparison = ascending ? "<" : ">";
|
|
1131
|
-
const inclusive = item.dynamic.exclusive ? "" : "=";
|
|
1132
|
-
const distance = ascending ? `${last} - ${first}` : `${first} - ${last}`;
|
|
1133
|
-
const exclusive = item.dynamic.exclusive ? ` - ${wide}#1` : "";
|
|
1134
|
-
write(`${count} := DINT#0;`, depth, item.span);
|
|
1135
|
-
write(`IF ${first} ${comparison}${inclusive} ${last} THEN`, depth, item.span);
|
|
1136
|
-
write(
|
|
1137
|
-
`${count} := ${wide}_TO_DINT(((${distance}${exclusive}) / ${wide}#${step}) + ${wide}#1);`,
|
|
1138
|
-
depth + 1,
|
|
1139
|
-
item.span,
|
|
1140
|
-
);
|
|
1141
|
-
write("END_IF;", depth, item.span);
|
|
1142
|
-
iterations = count;
|
|
1143
|
-
}
|
|
1144
|
-
write(
|
|
1145
|
-
`FOR ${ordinal} := DINT#0 TO ${item.dynamic ? `${iterations} - DINT#1` : `DINT#${item.maxIterations - 1}`} DO`,
|
|
1146
|
-
depth,
|
|
1147
|
-
item.span,
|
|
1148
|
-
);
|
|
1149
|
-
const counterValue = `${load(item.counter)} := TO_${counterType}(${first} ${ascending ? "+" : "-"} (${wide}#${step} * DINT_TO_${wide}(${ordinal})));`;
|
|
1150
|
-
write(counterValue, depth + 1, item.span);
|
|
1151
|
-
body(item.body, depth + 1);
|
|
1152
|
-
write("END_FOR;", depth, item.span);
|
|
1153
|
-
// CODESYS keeps the ordinal at EXIT and advances it on normal
|
|
1154
|
-
// completion/CONTINUE. Reconstructing here preserves that distinction.
|
|
1155
|
-
if (item.counterScope === "existing") write(counterValue, depth, item.span);
|
|
1156
|
-
break;
|
|
1157
|
-
}
|
|
1158
|
-
case "return":
|
|
1159
|
-
instrument(item, depth);
|
|
1160
|
-
if (block) {
|
|
1161
|
-
if (item.value) {
|
|
1162
|
-
const returned = expression(item.value);
|
|
1163
|
-
for (const output of block.outputs)
|
|
1164
|
-
write(
|
|
1165
|
-
`${load(output.id)} := ${returned}.${targetTypes.field(required(block.result), output.name)};`,
|
|
1166
|
-
depth,
|
|
1167
|
-
item.span,
|
|
1168
|
-
);
|
|
1169
|
-
}
|
|
1170
|
-
} else if (program) {
|
|
1171
|
-
if (item.value)
|
|
1172
|
-
write(
|
|
1173
|
-
`${required(this.programResults.get(fn.id))} := ${expression(item.value)};`,
|
|
1174
|
-
depth,
|
|
1175
|
-
item.span,
|
|
1176
|
-
);
|
|
1177
|
-
} else if (!method || fn.result)
|
|
1178
|
-
write(
|
|
1179
|
-
`${name} := ${item.value ? expression(item.value) : "TRUE"};`,
|
|
1180
|
-
depth,
|
|
1181
|
-
item.span,
|
|
1182
|
-
);
|
|
1183
|
-
if (mutex) release(mutex, depth, item.span);
|
|
1184
|
-
if (tracked?.track) write(`${tracked.track}();`, depth);
|
|
1185
|
-
write("RETURN;", depth, item.span);
|
|
1186
|
-
break;
|
|
1187
|
-
case "break":
|
|
1188
|
-
write("EXIT;", depth, item.span);
|
|
1189
|
-
break;
|
|
1190
|
-
case "continue":
|
|
1191
|
-
write("CONTINUE;", depth, item.span);
|
|
1192
|
-
break;
|
|
1193
|
-
case "telemetry": {
|
|
1194
|
-
const site = required(this.plan.telemetry?.calls.get(item));
|
|
1195
|
-
const arguments_ = callParameters(item).map(
|
|
1196
|
-
({ name, value }) => `${name} := ${expression(value)}`,
|
|
1197
|
-
);
|
|
1198
|
-
write(
|
|
1199
|
-
`${ring(site.task)}.Record${site.id}(${arguments_.join(", ")});`,
|
|
1200
|
-
depth,
|
|
1201
|
-
item.span,
|
|
1202
|
-
);
|
|
1203
|
-
break;
|
|
1204
|
-
}
|
|
1205
|
-
}
|
|
1206
|
-
}
|
|
1207
|
-
};
|
|
1208
|
-
|
|
1209
|
-
if (mutex && acquired) {
|
|
1210
|
-
// ARM64 implements __COMPARE_AND_SWAP with load-linked/store-conditional, which can fail
|
|
1211
|
-
// even when the word holds the expected value. Retry while the lock reads free.
|
|
1212
|
-
write(`${acquired} := FALSE;`, 0);
|
|
1213
|
-
write(`WHILE NOT ${acquired} AND ${mutex} = 0 DO`, 0);
|
|
1214
|
-
write(`${acquired} := __COMPARE_AND_SWAP(ADR(${mutex}), 0, 1);`, 1);
|
|
1215
|
-
write("END_WHILE;", 0);
|
|
1216
|
-
write(`IF NOT ${acquired} THEN`, 0);
|
|
1217
|
-
if (unavailable) write(`${name} := ${unavailable};`, 1);
|
|
1218
|
-
write("RETURN;", 1);
|
|
1219
|
-
write("END_IF;", 0);
|
|
1220
|
-
}
|
|
1221
|
-
if (block && tracked?.track) {
|
|
1222
|
-
// Before the job's own early return, so a job started since its last call is seen.
|
|
1223
|
-
write(`${tracked.track}();`, 0);
|
|
1224
|
-
// The step it was in when it finished.
|
|
1225
|
-
if (tracked.step) write(`${tracked.step} := ${jobField(block, "step")};`, 0);
|
|
1226
|
-
}
|
|
1227
|
-
body(fn.body, 0);
|
|
1228
|
-
if (tracked?.track) write(`${tracked.track}();`, 0);
|
|
1229
|
-
if (mutex) release(mutex, 0);
|
|
1230
|
-
if (!block && !method && !program && !fn.result) write(`${name} := TRUE;`, 0);
|
|
1231
|
-
|
|
1232
|
-
const header = this.routineHeader(fn, name);
|
|
1233
|
-
const declaration = [header.declaration];
|
|
1234
|
-
mappings.push({ path: `${mappingName}/declaration.st`, line: 1, span: fn.span });
|
|
1235
|
-
const section = (keyword: string, items: readonly Variable[]): void => {
|
|
1236
|
-
if (!items.length) return;
|
|
1237
|
-
declaration.push(keyword);
|
|
1238
|
-
for (const item of items) {
|
|
1239
|
-
mappings.push({
|
|
1240
|
-
path: `${mappingName}/declaration.st`,
|
|
1241
|
-
line: declaration.length + 1,
|
|
1242
|
-
span: item.span,
|
|
1243
|
-
});
|
|
1244
|
-
const initial =
|
|
1245
|
-
item.initial && !instancedBlock(item.type, typeMap)
|
|
1246
|
-
? targetTypes.declarationInitializer(item.initial, item.type)
|
|
1247
|
-
: "";
|
|
1248
|
-
declaration.push(` ${load(item.id)} : ${targetTypes.name(item.type)}${initial};`);
|
|
1249
|
-
}
|
|
1250
|
-
declaration.push("END_VAR");
|
|
1251
|
-
};
|
|
1252
|
-
|
|
1253
|
-
section(
|
|
1254
|
-
"VAR_INPUT",
|
|
1255
|
-
inputs.filter((item) => item.mode !== "inOut"),
|
|
1256
|
-
);
|
|
1257
|
-
section(
|
|
1258
|
-
"VAR_IN_OUT",
|
|
1259
|
-
inputs.filter((item) => item.mode === "inOut"),
|
|
1260
|
-
);
|
|
1261
|
-
if (tracked && tracked.job)
|
|
1262
|
-
declaration.push("VAR_INPUT", ` ${tracked.job} : UDINT;`, "END_VAR");
|
|
1263
|
-
if (program && "parameters" in fn && fn.result) {
|
|
1264
|
-
declaration.push(
|
|
1265
|
-
"VAR_OUTPUT",
|
|
1266
|
-
` ${required(this.programResults.get(fn.id))} : ${targetTypes.name(fn.result)};`,
|
|
1267
|
-
"END_VAR",
|
|
1268
|
-
);
|
|
1269
|
-
}
|
|
1270
|
-
if (block) {
|
|
1271
|
-
if (block.runtime?.kind === "mailbox")
|
|
1272
|
-
declaration.push(
|
|
1273
|
-
"VAR",
|
|
1274
|
-
` ${required(this.mailboxLocks.get(block.id))} : __XWORD;`,
|
|
1275
|
-
"END_VAR",
|
|
1276
|
-
);
|
|
1277
|
-
section("VAR_OUTPUT", block.outputs);
|
|
1278
|
-
section(
|
|
1279
|
-
"VAR",
|
|
1280
|
-
block.state.filter((item) => !retainedVariables.has(item.id)),
|
|
1281
|
-
);
|
|
1282
|
-
section(
|
|
1283
|
-
"VAR RETAIN",
|
|
1284
|
-
block.state.filter((item) => retainedVariables.has(item.id)),
|
|
1285
|
-
);
|
|
1286
|
-
const fields = (
|
|
1287
|
-
[
|
|
1288
|
-
[tracked && tracked.busy, "BOOL"],
|
|
1289
|
-
[tracked && tracked.step, "UINT"],
|
|
1290
|
-
[tracked && tracked.startedAt, "UDINT"],
|
|
1291
|
-
] as const
|
|
1292
|
-
).flatMap(([field, type]) => (field ? [` ${field} : ${type};`] : []));
|
|
1293
|
-
if (fields.length) declaration.push("VAR", ...fields, "END_VAR");
|
|
1294
|
-
}
|
|
1295
|
-
if (declarations.length) {
|
|
1296
|
-
declaration.push(block || program ? "VAR_TEMP" : "VAR");
|
|
1297
|
-
declarationSpans.forEach((span, index) => {
|
|
1298
|
-
mappings.push({
|
|
1299
|
-
path: `${mappingName}/declaration.st`,
|
|
1300
|
-
line: declaration.length + index + 1,
|
|
1301
|
-
span,
|
|
1302
|
-
});
|
|
1303
|
-
});
|
|
1304
|
-
declaration.push(...declarations, "END_VAR");
|
|
1305
|
-
}
|
|
1306
|
-
|
|
1307
|
-
objects.push({
|
|
1308
|
-
id: fn.id,
|
|
1309
|
-
kind: header.kind,
|
|
1310
|
-
name,
|
|
1311
|
-
declaration: `${declaration.join("\n")}\n`,
|
|
1312
|
-
implementation: `${lines.join("\n")}\n`,
|
|
1313
|
-
});
|
|
1314
|
-
if (block && tracked?.track)
|
|
1315
|
-
objects.push({
|
|
1316
|
-
id: `${fn.id}:${tracked.track}`,
|
|
1317
|
-
parent: fn.id,
|
|
1318
|
-
kind: "method",
|
|
1319
|
-
name: tracked.track,
|
|
1320
|
-
declaration: `METHOD PRIVATE ${tracked.track}\n`,
|
|
1321
|
-
implementation: jobTracking(block, tracked),
|
|
1322
|
-
});
|
|
1323
|
-
}
|
|
1324
|
-
|
|
1325
|
-
private emitProgram(program: CodesysPlan["core"]["programs"][number]): void {
|
|
1326
|
-
const { core, options } = this.plan;
|
|
1327
|
-
const { names, functionNames, objects } = this;
|
|
1328
|
-
// Each wrapper snapshots physical inputs before the authored scan and commits
|
|
1329
|
-
// outputs afterwards. RETURN in an authored routine cannot skip that epilogue.
|
|
1330
|
-
const explicit =
|
|
1331
|
-
options.programNames && Object.hasOwn(options.programNames, program.name)
|
|
1332
|
-
? options.programNames[program.name]
|
|
1333
|
-
: undefined;
|
|
1334
|
-
const name = explicit ?? names.allocateObject("PRG", program.name);
|
|
1335
|
-
const fn = required(core.functions.find((item) => item.id === program.entry));
|
|
1336
|
-
const used = accessedStorage(fn, core);
|
|
1337
|
-
const channels = this.channels.filter((channel) => used.has(channel.root));
|
|
1338
|
-
const stateful = this.programRoutines.has(program.entry);
|
|
1339
|
-
const call = `${functionNames.get(program.entry)}();`;
|
|
1340
|
-
const lines = [
|
|
1341
|
-
...this.scanPrologue(program.name),
|
|
1342
|
-
...channels
|
|
1343
|
-
.filter((channel) => channel.input)
|
|
1344
|
-
.map(({ target, wire, inverted }) => `${target} := ${inverted ? "NOT " : ""}${wire};`),
|
|
1345
|
-
stateful ? call : `plc_discard := ${call}`,
|
|
1346
|
-
...channels
|
|
1347
|
-
.filter((channel) => !channel.input)
|
|
1348
|
-
.map(({ target, wire }) => `${wire} := ${target};`),
|
|
1349
|
-
];
|
|
1350
|
-
objects.push({
|
|
1351
|
-
id: program.id,
|
|
1352
|
-
kind: "program",
|
|
1353
|
-
name,
|
|
1354
|
-
declaration: stateful
|
|
1355
|
-
? `PROGRAM ${name}\n`
|
|
1356
|
-
: `PROGRAM ${name}\nVAR\n plc_discard : BOOL;\nEND_VAR\n`,
|
|
1357
|
-
implementation: `${lines.join("\n")}\n`,
|
|
1358
|
-
});
|
|
1359
|
-
}
|
|
1360
|
-
|
|
1361
|
-
/** The first program of a task with a ring runs its sender first, which counts the scan and reads the clock. */
|
|
1362
|
-
private scanPrologue(program: string): string[] {
|
|
1363
|
-
const task = this.plan.deployment.tasks.find((item) => item.programs[0] === program);
|
|
1364
|
-
const ring = task && this.rings.get(task.name);
|
|
1365
|
-
return ring ? [`${this.debugGlobal}.${ring}();`] : [];
|
|
1366
|
-
}
|
|
1367
|
-
|
|
1368
|
-
private emitTelemetry(): void {
|
|
1369
|
-
const { telemetry } = this.plan;
|
|
1370
|
-
const names = this.telemetryNames;
|
|
1371
|
-
if (!telemetry || !names) return;
|
|
1372
|
-
this.objects.push(
|
|
1373
|
-
...telemetryObjects({
|
|
1374
|
-
plan: telemetry,
|
|
1375
|
-
names,
|
|
1376
|
-
target: this.targetTypes,
|
|
1377
|
-
endpoint: required(this.plan.http[telemetryClient]),
|
|
1378
|
-
network: `${required(this.networkName)}.network`,
|
|
1379
|
-
build: buildPlaceholder,
|
|
1380
|
-
types: this.typeMap,
|
|
1381
|
-
}),
|
|
1382
|
-
);
|
|
1383
|
-
}
|
|
1384
|
-
|
|
1385
|
-
/**
|
|
1386
|
-
* `GVL_TsplcDebug` holds the build id, which identifies this ST and its manifest, so the id is
|
|
1387
|
-
* computed over everything else first.
|
|
1388
|
-
*/
|
|
1389
|
-
private emitDebugGlobal(): DebugManifest {
|
|
1390
|
-
const manifest = this.manifest();
|
|
1391
|
-
const hash = createHash("sha256");
|
|
1392
|
-
for (const object of this.objects)
|
|
1393
|
-
hash.update(`${object.name}\n${object.declaration}\n${object.implementation ?? ""}\n`);
|
|
1394
|
-
hash.update(JSON.stringify(manifest));
|
|
1395
|
-
const id = hash.digest("hex").slice(0, 16);
|
|
1396
|
-
|
|
1397
|
-
// A batch names its build; the id is known only now, so the sender's literal is filled in last.
|
|
1398
|
-
const send = this.objects.find((object) => object.id === "tsplc:telemetryWriter:Send");
|
|
1399
|
-
if (send) send.implementation = send.implementation!.replace(buildPlaceholder, id);
|
|
1400
|
-
|
|
1401
|
-
const fields = [`buildId : STRING(16) := '${id}'`];
|
|
1402
|
-
for (const [task, field] of this.rings)
|
|
1403
|
-
fields.push(`${field} : ${required(this.telemetryNames).writer} := (task := '${task}')`);
|
|
1404
|
-
const settings = this.plan.project.debug;
|
|
1405
|
-
if (settings) {
|
|
1406
|
-
if (this.debug.decisions.size)
|
|
1407
|
-
fields.push(
|
|
1408
|
-
`${this.debugSlots.decisions} : ARRAY[0..${this.debug.decisions.size - 1}] OF DINT`,
|
|
1409
|
-
);
|
|
1410
|
-
if (settings.writers && this.debug.outputs.length)
|
|
1411
|
-
fields.push(
|
|
1412
|
-
`${this.debugSlots.writers} : ARRAY[0..${this.debug.outputs.length - 1}] OF UINT`,
|
|
1413
|
-
);
|
|
1414
|
-
for (const raw of [...this.devices.values()].flatMap((device) => Object.values(device)))
|
|
1415
|
-
fields.push(`${raw.field} AT ${raw.address} : ARRAY[0..${raw.bytes - 1}] OF BYTE`);
|
|
1416
|
-
}
|
|
1417
|
-
this.objects.push({
|
|
1418
|
-
id: "debug",
|
|
1419
|
-
kind: "globalList",
|
|
1420
|
-
name: this.debugGlobal,
|
|
1421
|
-
// Nothing in the program reads the build id; linkalways keeps it in the application.
|
|
1422
|
-
declaration: `{attribute 'linkalways'}
|
|
1423
|
-
{attribute 'qualified_only'}
|
|
1424
|
-
VAR_GLOBAL
|
|
1425
|
-
${fields.map((field) => ` ${field};\n`).join("")}END_VAR
|
|
1426
|
-
`,
|
|
1427
|
-
});
|
|
1428
|
-
return { ...manifest, build: { ...manifest.build, id } };
|
|
1429
|
-
}
|
|
1430
|
-
|
|
1431
|
-
/** The IEC path of a block instance. */
|
|
1432
|
-
private instancePath(path: InstancePath): string {
|
|
1433
|
-
let text = "",
|
|
1434
|
-
holder: string | undefined;
|
|
1435
|
-
for (const { variable, index } of path) {
|
|
1436
|
-
text += holder
|
|
1437
|
-
? `.${required(required(this.blockFields.get(holder)).get(variable.id))}`
|
|
1438
|
-
: required(this.references.get(variable.id));
|
|
1439
|
-
if (index !== undefined) text += `[${index}]`;
|
|
1440
|
-
holder = required(instancedBlock(variable.type, this.typeMap)).block;
|
|
1441
|
-
}
|
|
1442
|
-
return text;
|
|
1443
|
-
}
|
|
1444
|
-
|
|
1445
|
-
/** Service calls a job instance makes, down to (not into) the jobs it starts itself. */
|
|
1446
|
-
private requests(id: string, prefix: string, job?: number): DebugJob["requests"] {
|
|
1447
|
-
const block = required(this.blocks.get(id));
|
|
1448
|
-
return block.state.flatMap((child) => {
|
|
1449
|
-
const instance = instancedBlock(child.type, this.typeMap);
|
|
1450
|
-
if (!instance) return [];
|
|
1451
|
-
// A nested job tags the calls below it with its own id.
|
|
1452
|
-
const caller = this.jobIds.get(child.id) ?? job;
|
|
1453
|
-
const type = required(this.typeMap.get(child.type));
|
|
1454
|
-
const field = `${prefix}.${required(required(this.blockFields.get(id)).get(child.id))}`;
|
|
1455
|
-
const targets =
|
|
1456
|
-
type.kind === "array"
|
|
1457
|
-
? Array.from(
|
|
1458
|
-
{ length: type.length },
|
|
1459
|
-
(_, index) => `${field}[${type.lowerBound + index}]`,
|
|
1460
|
-
)
|
|
1461
|
-
: [field];
|
|
1462
|
-
const sequence = this.debugFields.get(instance.block)?.sequence;
|
|
1463
|
-
const path = this.plan.http[instance.block]?.path;
|
|
1464
|
-
return targets.flatMap((target) =>
|
|
1465
|
-
sequence && path
|
|
1466
|
-
? [
|
|
1467
|
-
{
|
|
1468
|
-
service: serviceOfPath(path) ?? path,
|
|
1469
|
-
target,
|
|
1470
|
-
sequence: `${target}.${sequence}`,
|
|
1471
|
-
...(caller !== undefined && { job: caller }),
|
|
1472
|
-
},
|
|
1473
|
-
]
|
|
1474
|
-
: this.requests(instance.block, target, caller),
|
|
1475
|
-
);
|
|
1476
|
-
});
|
|
1477
|
-
}
|
|
1478
|
-
|
|
1479
|
-
/** Static member reads in a body, by TypeScript path. */
|
|
1480
|
-
private reads(body: readonly CoreStatement[], sources: Sources): DebugFunction["reads"] {
|
|
1481
|
-
const reads = new Map<string, DebugFunction["reads"][number]>();
|
|
1482
|
-
const path = (items: CorePath = []) => {
|
|
1483
|
-
for (const segment of items) if (segment.kind === "index") expression(segment.value);
|
|
1484
|
-
};
|
|
1485
|
-
const expression = (value: CoreExpression): void => {
|
|
1486
|
-
if (value.kind === "unary" || value.kind === "convert") expression(value.operand);
|
|
1487
|
-
if (value.kind === "binary") {
|
|
1488
|
-
expression(value.left);
|
|
1489
|
-
expression(value.right);
|
|
1490
|
-
}
|
|
1491
|
-
if (value.kind !== "load") return;
|
|
1492
|
-
path(value.path);
|
|
1493
|
-
const read = storagePath(required(this.debug.variables.get(value.root)), value.path);
|
|
1494
|
-
const range = read && sources.range(value.span);
|
|
1495
|
-
if (range) reads.set(`${JSON.stringify(range)}${read}`, { range, path: read });
|
|
1496
|
-
};
|
|
1497
|
-
const statements = (items: readonly CoreStatement[]): void => {
|
|
1498
|
-
for (const item of items) {
|
|
1499
|
-
if (item.kind === "assign") {
|
|
1500
|
-
path(item.path);
|
|
1501
|
-
expression(item.value);
|
|
1502
|
-
}
|
|
1503
|
-
if (item.kind === "if") {
|
|
1504
|
-
expression(item.condition);
|
|
1505
|
-
statements(item.then);
|
|
1506
|
-
statements(item.else);
|
|
1507
|
-
}
|
|
1508
|
-
if (item.kind === "switch") {
|
|
1509
|
-
expression(item.value);
|
|
1510
|
-
for (const branch of item.cases) statements(branch.body);
|
|
1511
|
-
statements(item.fallback);
|
|
1512
|
-
}
|
|
1513
|
-
if (item.kind === "for") {
|
|
1514
|
-
if (item.dynamic) {
|
|
1515
|
-
expression(item.dynamic.start);
|
|
1516
|
-
expression(item.dynamic.limit);
|
|
1517
|
-
}
|
|
1518
|
-
statements(item.body);
|
|
1519
|
-
}
|
|
1520
|
-
if (item.kind === "return" && item.value) expression(item.value);
|
|
1521
|
-
if (item.kind === "telemetry") telemetryOperands(item).forEach(expression);
|
|
1522
|
-
if (item.kind === "invoke") {
|
|
1523
|
-
if (item.index) expression(item.index);
|
|
1524
|
-
item.arguments.forEach(expression);
|
|
1525
|
-
}
|
|
1526
|
-
if (item.kind === "blockUpdate") {
|
|
1527
|
-
if (item.index) expression(item.index);
|
|
1528
|
-
Object.values(item.inputs).forEach(expression);
|
|
1529
|
-
}
|
|
1530
|
-
}
|
|
1531
|
-
};
|
|
1532
|
-
statements(body);
|
|
1533
|
-
return [...reads.values()];
|
|
1534
|
-
}
|
|
1535
|
-
|
|
1536
|
-
/** The target symbol and type that hold an `io` key's value, when this program has it. */
|
|
1537
|
-
private ioTarget(key: string): { target: string; type: string } | undefined {
|
|
1538
|
-
const { core } = this.plan;
|
|
1539
|
-
const logical = core.variables.find(
|
|
1540
|
-
(variable) =>
|
|
1541
|
-
(variable.storage === "input" || variable.storage === "output") && variable.name === key,
|
|
1542
|
-
);
|
|
1543
|
-
if (logical) return { target: required(this.references.get(logical.id)), type: logical.type };
|
|
1544
|
-
if (!isStoragePath(key)) return undefined;
|
|
1545
|
-
const resolved = resolveStoragePath(core, key);
|
|
1546
|
-
return "error" in resolved
|
|
1547
|
-
? undefined
|
|
1548
|
-
: { target: this.bindingTarget(resolved), type: resolved.type.id };
|
|
1549
|
-
}
|
|
1550
|
-
|
|
1551
|
-
private manifest(): DebugManifest {
|
|
1552
|
-
const { core, project, deployment, options } = this.plan;
|
|
1553
|
-
const settings = project.debug;
|
|
1554
|
-
const sources = new Sources(project.root);
|
|
1555
|
-
const global = (field: string) => `${this.debugGlobal}.${field}`;
|
|
1556
|
-
|
|
1557
|
-
const functionIds = new Map<string, number>();
|
|
1558
|
-
const functions = [
|
|
1559
|
-
...core.functions,
|
|
1560
|
-
...core.blocks.filter((block) => !block.standard && !block.runtime),
|
|
1561
|
-
].flatMap((routine): DebugFunction[] => {
|
|
1562
|
-
const block = "inputs" in routine ? routine : undefined;
|
|
1563
|
-
const fn = "parameters" in routine ? routine : undefined;
|
|
1564
|
-
const declaration = sources.range(block?.job?.span ?? routine.span);
|
|
1565
|
-
if (!declaration) return [];
|
|
1566
|
-
const id = functionIds.size;
|
|
1567
|
-
functionIds.set(routine.id, id);
|
|
1568
|
-
const task = this.debug.tasks.get(routine.id);
|
|
1569
|
-
const origin = fn?.origin;
|
|
1570
|
-
const method = fn?.owner;
|
|
1571
|
-
return [
|
|
1572
|
-
{
|
|
1573
|
-
id,
|
|
1574
|
-
name: block?.job?.name ?? origin?.name ?? routine.name,
|
|
1575
|
-
declaration,
|
|
1576
|
-
...(origin?.instance && { instance: origin.instance }),
|
|
1577
|
-
...(task && { task }),
|
|
1578
|
-
target: block
|
|
1579
|
-
? required(this.blockNames.get(block.id))
|
|
1580
|
-
: method
|
|
1581
|
-
? `${required(this.blockNames.get(method.block))}.${required(this.functionNames.get(routine.id))}`
|
|
1582
|
-
: required(this.functionNames.get(routine.id)),
|
|
1583
|
-
reads: this.reads(routine.body, sources),
|
|
1584
|
-
},
|
|
1585
|
-
];
|
|
1586
|
-
});
|
|
1587
|
-
const declared = (routine: string | undefined) => {
|
|
1588
|
-
const id = routine === undefined ? undefined : functionIds.get(routine);
|
|
1589
|
-
return id === undefined ? undefined : { id, range: functions[id]!.declaration };
|
|
1590
|
-
};
|
|
1591
|
-
|
|
1592
|
-
const events = this.debug.events.flatMap((site): DebugEventSite[] => {
|
|
1593
|
-
const owner = declared(site.routine);
|
|
1594
|
-
const range = sources.range(site.span) ?? owner?.range;
|
|
1595
|
-
if (!range) return [];
|
|
1596
|
-
return [
|
|
1597
|
-
{
|
|
1598
|
-
id: site.id,
|
|
1599
|
-
kind: site.kind,
|
|
1600
|
-
...(site.job && {
|
|
1601
|
-
job: this.jobs.findIndex(({ block }) => block.id === site.job!.block) + 1,
|
|
1602
|
-
phase: site.job.phase,
|
|
1603
|
-
}),
|
|
1604
|
-
path: site.path,
|
|
1605
|
-
...(owner && { function: owner.id }),
|
|
1606
|
-
type: site.type,
|
|
1607
|
-
range,
|
|
1608
|
-
text: site.text ?? sources.text(site.span) ?? "",
|
|
1609
|
-
task: site.task,
|
|
1610
|
-
operands: site.operands.map((operand) => ({
|
|
1611
|
-
text: sources.text(operand.span) ?? "",
|
|
1612
|
-
range: sources.range(operand.span) ?? range,
|
|
1613
|
-
type: operand.capture.type,
|
|
1614
|
-
...(operand.path && { path: operand.path }),
|
|
1615
|
-
stable: operand.stable,
|
|
1616
|
-
})),
|
|
1617
|
-
},
|
|
1618
|
-
];
|
|
1619
|
-
});
|
|
1620
|
-
|
|
1621
|
-
const jobs = this.jobs.flatMap(({ block, path }, index): DebugJob[] => {
|
|
1622
|
-
const job = required(block.job);
|
|
1623
|
-
const declaration = sources.range(job.span);
|
|
1624
|
-
if (!declaration) return [];
|
|
1625
|
-
const target = this.instancePath(path);
|
|
1626
|
-
const startedAt = this.debugFields.get(block.id)?.startedAt;
|
|
1627
|
-
return [
|
|
1628
|
-
{
|
|
1629
|
-
id: index + 1,
|
|
1630
|
-
name: job.name,
|
|
1631
|
-
declaration,
|
|
1632
|
-
...(job.instance && { instance: job.instance }),
|
|
1633
|
-
target,
|
|
1634
|
-
steps: job.steps.map((step) => ({
|
|
1635
|
-
step: step.step,
|
|
1636
|
-
kind: step.kind,
|
|
1637
|
-
range: sources.range(step.span) ?? declaration,
|
|
1638
|
-
text: step.text,
|
|
1639
|
-
})),
|
|
1640
|
-
...(startedAt && { startedAt: `${target}.${startedAt}` }),
|
|
1641
|
-
requests: this.requests(block.id, target),
|
|
1642
|
-
// Compiler-made functions, such as each service call's own job, carry its prefix.
|
|
1643
|
-
...(generated(job.name) && { generated: true as const }),
|
|
1644
|
-
},
|
|
1645
|
-
];
|
|
1646
|
-
});
|
|
1647
|
-
|
|
1648
|
-
const writers = settings?.writers
|
|
1649
|
-
? this.debug.outputs.map((output, index) => ({
|
|
1650
|
-
output: output.key,
|
|
1651
|
-
target: global(`${this.debugSlots.writers}[${index}]`),
|
|
1652
|
-
sites: required(this.debug.writers[index]).flatMap((site) => {
|
|
1653
|
-
const owner = declared(site.routine);
|
|
1654
|
-
return owner
|
|
1655
|
-
? [
|
|
1656
|
-
{
|
|
1657
|
-
id: site.id,
|
|
1658
|
-
range: sources.range(site.span) ?? owner.range,
|
|
1659
|
-
function: owner.id,
|
|
1660
|
-
},
|
|
1661
|
-
]
|
|
1662
|
-
: [];
|
|
1663
|
-
}),
|
|
1664
|
-
}))
|
|
1665
|
-
: [];
|
|
1666
|
-
|
|
1667
|
-
const roots = core.variables
|
|
1668
|
-
.filter((variable) => ["module", "instance", "input", "output"].includes(variable.storage))
|
|
1669
|
-
.map((variable) => {
|
|
1670
|
-
const declaration = sources.range(variable.span);
|
|
1671
|
-
return {
|
|
1672
|
-
path: required(storagePath(variable)),
|
|
1673
|
-
target: required(this.references.get(variable.id)),
|
|
1674
|
-
type: variable.type,
|
|
1675
|
-
...(declaration && { declaration }),
|
|
1676
|
-
readable: true,
|
|
1677
|
-
...(variable.name.startsWith("tsplc") && { generated: true as const }),
|
|
1678
|
-
};
|
|
1679
|
-
});
|
|
1680
|
-
|
|
1681
|
-
const types = debugTypes(
|
|
1682
|
-
core.types,
|
|
1683
|
-
this.targetTypes,
|
|
1684
|
-
this.blocks,
|
|
1685
|
-
(block, variable) => required(required(this.blockFields.get(block)).get(variable)),
|
|
1686
|
-
(block) => {
|
|
1687
|
-
const fields = this.debugFields.get(block);
|
|
1688
|
-
return (
|
|
1689
|
-
[
|
|
1690
|
-
[fields?.busy, "BOOL"],
|
|
1691
|
-
[fields?.step, "UINT"],
|
|
1692
|
-
[fields?.startedAt, "UDINT"],
|
|
1693
|
-
[fields?.job, "UDINT"],
|
|
1694
|
-
[fields?.sequence, "UDINT"],
|
|
1695
|
-
] as const
|
|
1696
|
-
).flatMap(([name, type]) => (name ? [{ name, target: name, type }] : []));
|
|
1697
|
-
},
|
|
1698
|
-
sources,
|
|
1699
|
-
);
|
|
1700
|
-
const hardware = debugHardware(
|
|
1701
|
-
project.hardware ?? {
|
|
1702
|
-
catalog: { descriptors: [], devices: [] },
|
|
1703
|
-
config: { devices: {}, io: options.io },
|
|
1704
|
-
tree: false,
|
|
1705
|
-
},
|
|
1706
|
-
(key) => this.ioTarget(key),
|
|
1707
|
-
(id) =>
|
|
1708
|
-
Object.fromEntries(
|
|
1709
|
-
Object.entries(this.devices.get(id) ?? {}).map(([direction, raw]) => [
|
|
1710
|
-
direction,
|
|
1711
|
-
global(raw.field),
|
|
1712
|
-
]),
|
|
1713
|
-
),
|
|
1714
|
-
);
|
|
1715
|
-
const constants = debugConstants(core.folded ?? [], sources);
|
|
1716
|
-
|
|
1717
|
-
return {
|
|
1718
|
-
kind: "tsplc-debug",
|
|
1719
|
-
version: 1,
|
|
1720
|
-
build: { id: "", target: global("buildId"), compiler: `@tsplc/compiler ${version}` },
|
|
1721
|
-
sources: sources.files,
|
|
1722
|
-
types,
|
|
1723
|
-
roots,
|
|
1724
|
-
constants,
|
|
1725
|
-
...hardware,
|
|
1726
|
-
functions,
|
|
1727
|
-
jobs,
|
|
1728
|
-
events,
|
|
1729
|
-
writers,
|
|
1730
|
-
tasks: deployment.tasks.map((task) => ({
|
|
1731
|
-
name: task.name,
|
|
1732
|
-
intervalMs: Number(task.intervalNanoseconds) / 1e6,
|
|
1733
|
-
priority: task.priority,
|
|
1734
|
-
})),
|
|
1735
|
-
errors: jobErrors,
|
|
1736
|
-
};
|
|
1737
|
-
}
|
|
1738
|
-
}
|