@tsplc/tmp-compiler 0.0.0-stage → 0.6.3

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.
Files changed (185) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +41 -2
  3. package/dist/cli.js +2325 -0
  4. package/dist/cli.js.map +26 -0
  5. package/dist/clock.js +11 -0
  6. package/dist/clock.js.map +11 -0
  7. package/dist/codesys.js +6563 -0
  8. package/dist/codesys.js.map +51 -0
  9. package/dist/collections.js +399 -0
  10. package/dist/collections.js.map +10 -0
  11. package/dist/index.js +16198 -0
  12. package/dist/index.js.map +62 -0
  13. package/dist/ir.js +3948 -0
  14. package/dist/ir.js.map +35 -0
  15. package/dist/retain.js +10 -0
  16. package/dist/retain.js.map +10 -0
  17. package/dist/signals.js +115 -0
  18. package/dist/signals.js.map +10 -0
  19. package/dist/telemetry.js +121 -0
  20. package/dist/telemetry.js.map +12 -0
  21. package/package.json +122 -4
  22. package/src/codesys/config.ts +50 -0
  23. package/src/codesys/debug.ts +655 -0
  24. package/src/codesys/emit.ts +185 -0
  25. package/src/codesys/endpoints.ts +111 -0
  26. package/src/codesys/engineering.ts +96 -0
  27. package/src/codesys/explain/expressions.ts +445 -0
  28. package/src/codesys/explain/flags.ts +134 -0
  29. package/src/codesys/explain/parameters.ts +53 -0
  30. package/src/codesys/explain/rows.ts +182 -0
  31. package/src/codesys/explain/tables.ts +79 -0
  32. package/src/codesys/explain/tasks.ts +68 -0
  33. package/src/codesys/explain/writes.ts +497 -0
  34. package/src/codesys/explain.ts +149 -0
  35. package/src/codesys/expressions.ts +100 -0
  36. package/src/codesys/global-lists.ts +284 -0
  37. package/src/codesys/global-names.ts +66 -0
  38. package/src/codesys/http.ts +1090 -0
  39. package/src/codesys/index.ts +13 -0
  40. package/src/codesys/instrumentation.ts +574 -0
  41. package/src/codesys/io-paths.ts +149 -0
  42. package/src/codesys/loops.ts +101 -0
  43. package/src/codesys/manifest.ts +684 -0
  44. package/src/codesys/names.ts +58 -0
  45. package/src/codesys/numeric.ts +516 -0
  46. package/src/codesys/plan.ts +688 -0
  47. package/src/codesys/programs.ts +138 -0
  48. package/src/codesys/publication.ts +99 -0
  49. package/src/codesys/required.ts +8 -0
  50. package/src/codesys/routines.ts +247 -0
  51. package/src/codesys/scan-clock.ts +103 -0
  52. package/src/codesys/scheduling.ts +96 -0
  53. package/src/codesys/service-channels.ts +24 -0
  54. package/src/codesys/sources.ts +118 -0
  55. package/src/codesys/st-files.ts +219 -0
  56. package/src/codesys/statements.ts +409 -0
  57. package/src/codesys/storage.ts +150 -0
  58. package/src/codesys/symbols.ts +240 -0
  59. package/src/codesys/task-access.ts +186 -0
  60. package/src/codesys/telemetry-settings.ts +19 -0
  61. package/src/codesys/telemetry.ts +852 -0
  62. package/src/codesys/types.ts +310 -0
  63. package/src/codesys/vendor.ts +113 -0
  64. package/src/frontend/analyzer.ts +779 -0
  65. package/src/frontend/async.ts +530 -0
  66. package/src/frontend/blocks.ts +578 -0
  67. package/src/frontend/configuration.ts +83 -0
  68. package/src/frontend/const-enums.ts +196 -0
  69. package/src/frontend/const-functions.ts +204 -0
  70. package/src/frontend/control-flow.ts +787 -0
  71. package/src/frontend/cooperative.ts +114 -0
  72. package/src/frontend/coroutines.ts +1344 -0
  73. package/src/frontend/dialect-names.ts +104 -0
  74. package/src/frontend/elaborate/array-searches.ts +224 -0
  75. package/src/frontend/elaborate/assignments.ts +343 -0
  76. package/src/frontend/elaborate/calls.ts +1342 -0
  77. package/src/frontend/elaborate/capture-protocol.ts +237 -0
  78. package/src/frontend/elaborate/capture.ts +388 -0
  79. package/src/frontend/elaborate/declarations.ts +124 -0
  80. package/src/frontend/elaborate/dialect.ts +473 -0
  81. package/src/frontend/elaborate/expressions.ts +2177 -0
  82. package/src/frontend/elaborate/filtered-arrays.ts +643 -0
  83. package/src/frontend/elaborate/frame.ts +145 -0
  84. package/src/frontend/elaborate/generics.ts +123 -0
  85. package/src/frontend/elaborate/graph.ts +141 -0
  86. package/src/frontend/elaborate/imports.ts +105 -0
  87. package/src/frontend/elaborate/index.ts +851 -0
  88. package/src/frontend/elaborate/initializers.ts +235 -0
  89. package/src/frontend/elaborate/iterators.ts +1541 -0
  90. package/src/frontend/elaborate/layouts.ts +1025 -0
  91. package/src/frontend/elaborate/model.ts +478 -0
  92. package/src/frontend/elaborate/names.ts +134 -0
  93. package/src/frontend/elaborate/reduce.ts +900 -0
  94. package/src/frontend/elaborate/references.ts +727 -0
  95. package/src/frontend/elaborate/retention.ts +284 -0
  96. package/src/frontend/elaborate/specialize.ts +1137 -0
  97. package/src/frontend/elaborate/statements.ts +1220 -0
  98. package/src/frontend/elaborate/storage.ts +836 -0
  99. package/src/frontend/elaborate/time-constructors.ts +34 -0
  100. package/src/frontend/elaborate/values.ts +200 -0
  101. package/src/frontend/elaborate/writes.ts +415 -0
  102. package/src/frontend/expressions.ts +1382 -0
  103. package/src/frontend/generated-names.ts +95 -0
  104. package/src/frontend/intrinsics.ts +382 -0
  105. package/src/frontend/lowering-key.ts +23 -0
  106. package/src/frontend/module-graph.ts +156 -0
  107. package/src/frontend/positions.ts +359 -0
  108. package/src/frontend/promise-chains.ts +872 -0
  109. package/src/frontend/promises.ts +419 -0
  110. package/src/frontend/routines.ts +239 -0
  111. package/src/frontend/sdk.ts +187 -0
  112. package/src/frontend/services.ts +612 -0
  113. package/src/frontend/statements.ts +871 -0
  114. package/src/frontend/tasks.ts +526 -0
  115. package/src/frontend/telemetry.ts +174 -0
  116. package/src/frontend/types.ts +1073 -0
  117. package/src/frontend/typescript.ts +659 -0
  118. package/src/index.ts +9 -0
  119. package/src/ir/aggregates.ts +291 -0
  120. package/src/ir/allocation.ts +96 -0
  121. package/src/ir/conditions.ts +855 -0
  122. package/src/ir/core-model.ts +289 -0
  123. package/src/ir/declarations.ts +281 -0
  124. package/src/ir/diagnostics.ts +68 -0
  125. package/src/ir/domains.ts +151 -0
  126. package/src/ir/fold.ts +279 -0
  127. package/src/ir/identity.ts +19 -0
  128. package/src/ir/index.ts +137 -0
  129. package/src/ir/job-errors.ts +69 -0
  130. package/src/ir/layouts.ts +211 -0
  131. package/src/ir/link.ts +302 -0
  132. package/src/ir/model.ts +394 -0
  133. package/src/ir/normalization-error.ts +10 -0
  134. package/src/ir/normalize.ts +52 -0
  135. package/src/ir/numeric.ts +163 -0
  136. package/src/ir/operands.ts +160 -0
  137. package/src/ir/ranges.ts +420 -0
  138. package/src/ir/routine.ts +1116 -0
  139. package/src/ir/scalars.ts +453 -0
  140. package/src/ir/share.ts +790 -0
  141. package/src/ir/short-circuit.ts +140 -0
  142. package/src/ir/tables.ts +111 -0
  143. package/src/ir/temporaries.ts +138 -0
  144. package/src/ir/types.ts +151 -0
  145. package/src/project/artifacts.ts +424 -0
  146. package/src/project/cli.ts +211 -0
  147. package/src/project/debugger.ts +111 -0
  148. package/src/project/deployments.ts +387 -0
  149. package/src/project/flags.ts +14 -0
  150. package/src/project/git.ts +35 -0
  151. package/src/project/plant.ts +629 -0
  152. package/src/project/project-commands.ts +507 -0
  153. package/src/project/project.ts +559 -0
  154. package/src/project/release.ts +152 -0
  155. package/src/project/server-check.ts +54 -0
  156. package/src/project/server.ts +165 -0
  157. package/src/project/terminal.ts +45 -0
  158. package/src/runtime/async.ts +207 -0
  159. package/src/runtime/launch.ts +59 -0
  160. package/src/runtime/main.ts +59 -0
  161. package/src/runtime/missing-file.ts +3 -0
  162. package/src/runtime/process.ts +177 -0
  163. package/src/runtime/program.ts +109 -0
  164. package/src/runtime/retain.ts +108 -0
  165. package/src/runtime/runtime.ts +324 -0
  166. package/src/runtime/settings.ts +27 -0
  167. package/src/runtime/storage.ts +456 -0
  168. package/src/runtime/symbols.ts +97 -0
  169. package/src/runtime/telemetry.ts +154 -0
  170. package/src/runtime/transport.ts +168 -0
  171. package/stdlib/clock.ts +8 -0
  172. package/stdlib/collections.ts +534 -0
  173. package/stdlib/plc-time.ts +2 -0
  174. package/stdlib/retain.ts +4 -0
  175. package/stdlib/signals.ts +142 -0
  176. package/stdlib/telemetry.ts +89 -0
  177. package/types/async.d.ts +87 -0
  178. package/types/clock.d.ts +8 -0
  179. package/types/config.d.ts +2 -0
  180. package/types/data-types.d.ts +31 -0
  181. package/types/dialect.d.ts +49 -0
  182. package/types/globals.d.ts +10 -0
  183. package/types/index.d.ts +212 -0
  184. package/types/retain.d.ts +12 -0
  185. package/types/telemetry.d.ts +47 -0
@@ -0,0 +1,655 @@
1
+ import {
2
+ type CoreExpression,
3
+ type CoreFunction,
4
+ type CoreFunctionBlock,
5
+ type CorePath,
6
+ type CoreStatement,
7
+ type CoreTables,
8
+ constantIndex,
9
+ coreTables,
10
+ type Deployment,
11
+ directWrites,
12
+ instancedBlock,
13
+ isBlockRoutine,
14
+ isTemporary,
15
+ nestedBodies,
16
+ type SourceSpan,
17
+ type Variable,
18
+ type VerifiedCoreModule,
19
+ } from "@tsplc/compiler/ir";
20
+ import type { ResolvedDebugConfig } from "@tsplc/config";
21
+ import { neverWrittenSlot } from "@tsplc/debug/manifest";
22
+ import { required } from "./required";
23
+ import { storagePath } from "./storage";
24
+ import { routineTasks } from "./task-access";
25
+
26
+ type Routine = CoreFunction | CoreFunctionBlock;
27
+
28
+ /** A guard leaf captured at an event site; `capture` is evaluated at the site. */
29
+ export interface Operand {
30
+ capture: CoreExpression;
31
+ span: SourceSpan;
32
+ path?: string;
33
+ stable: boolean;
34
+ }
35
+
36
+ type Probe =
37
+ | {
38
+ kind: "state" | "decision";
39
+ site: number;
40
+ value: CoreExpression;
41
+ operands: readonly Operand[];
42
+ /** A decision's last-value slot. */
43
+ slot?: number;
44
+ }
45
+ | {
46
+ kind: "writer";
47
+ site: number;
48
+ output: number;
49
+ /** Dynamic indexes that must equal the output's index for this write to reach it. */
50
+ when: readonly { index: CoreExpression; value: number }[];
51
+ };
52
+
53
+ interface EventSite {
54
+ id: number;
55
+ kind: "state" | "decision" | "job";
56
+ /** A job site's block and whether the job starts or finishes there. */
57
+ job?: { block: string; phase: "started" | "finished" };
58
+ path: string;
59
+ routine?: string;
60
+ type: string;
61
+ span: SourceSpan;
62
+ /** Defaults to the source text of `span`. */
63
+ text?: string;
64
+ task: string;
65
+ operands: readonly Operand[];
66
+ }
67
+
68
+ interface WriterSite {
69
+ id: number;
70
+ routine: string;
71
+ span: SourceSpan;
72
+ statement: CoreStatement;
73
+ }
74
+
75
+ /** An output the program drives: a logical output, or a storage path bound to a %Q address. */
76
+ export interface Output {
77
+ key: string;
78
+ root: Variable;
79
+ segments: readonly (
80
+ | { kind: "field"; name: string }
81
+ | { kind: "index"; value: number }
82
+ )[];
83
+ }
84
+
85
+ /** One declared block instance, from its module root down: each variable and its array index. */
86
+ export type InstancePath = readonly { variable: Variable; index?: number }[];
87
+
88
+ type Load = CoreExpression & { kind: "load" };
89
+
90
+ /** A call in a loop may run any number of times a scan: counted as two, it is never the only call. */
91
+ const callsInLoop = 2;
92
+
93
+ /** The place a statement writes directly: an assignment's, or a call's stored result, written as directly. */
94
+ const writtenPlace = (
95
+ item: CoreStatement,
96
+ ): { root: string; path: CorePath } | undefined => {
97
+ if (item.kind === "assign") {
98
+ return { root: item.root, path: item.path ?? [] };
99
+ }
100
+ return item.kind === "invoke" && item.destination
101
+ ? { root: item.destination, path: [] }
102
+ : undefined;
103
+ };
104
+
105
+ /** The root a statement assigns as a whole: a plain assignment's, or a call result's. */
106
+ const wholeTarget = (item: CoreStatement): string | undefined => {
107
+ if (item.kind === "assign" && !item.path?.length) {
108
+ return item.root;
109
+ }
110
+ return item.kind === "invoke" ? item.destination : undefined;
111
+ };
112
+
113
+ /** Every declared instance of each block, from its module root down. */
114
+ export function blockInstances(
115
+ core: VerifiedCoreModule,
116
+ ): Map<string, InstancePath[]> {
117
+ const { types, blockOf } = coreTables(core);
118
+ const instances = new Map<string, InstancePath[]>(
119
+ core.blocks.map((block) => [block.id, []]),
120
+ );
121
+ const visit = (
122
+ variable: Variable,
123
+ block: string,
124
+ path: InstancePath,
125
+ ): void => {
126
+ const type = types.get(variable.type);
127
+ const declared =
128
+ type?.kind === "array"
129
+ ? Array.from({ length: type.length }, (_, offset) => [
130
+ ...path,
131
+ { variable, index: type.lowerBound + offset },
132
+ ])
133
+ : [[...path, { variable }]];
134
+ for (const instance of declared) {
135
+ required(instances.get(block)).push(instance);
136
+ for (const child of blockOf(block).state) {
137
+ const instanced = instancedBlock(child.type, types);
138
+ if (instanced) {
139
+ visit(child, instanced.block, instance);
140
+ }
141
+ }
142
+ }
143
+ };
144
+ for (const variable of core.variables) {
145
+ const instanced = instancedBlock(variable.type, types);
146
+ if (instanced) {
147
+ visit(variable, instanced.block, []);
148
+ }
149
+ }
150
+ return instances;
151
+ }
152
+
153
+ /** The TypeScript path of a module storage place, when every index is constant. */
154
+ export function typescriptPath(
155
+ root: Variable,
156
+ path: CorePath = [],
157
+ ): string | undefined {
158
+ const logical = root.storage === "input" || root.storage === "output";
159
+ if (!logical && root.storage !== "module" && root.storage !== "instance") {
160
+ return undefined;
161
+ }
162
+ const segments: string[] = [];
163
+ for (const segment of path) {
164
+ if (segment.kind === "field") {
165
+ segments.push(`.${segment.name}`);
166
+ continue;
167
+ }
168
+ const index = constantIndex(segment.value);
169
+ if (index === undefined) {
170
+ return undefined;
171
+ }
172
+ segments.push(`[${index}]`);
173
+ }
174
+ return `${logical ? root.name : storagePath(root)}${segments.join("")}`;
175
+ }
176
+
177
+ /** The TypeScript path of a block instance. */
178
+ export const instanceText = (path: InstancePath): string =>
179
+ path
180
+ .map(({ variable, index }, position) => {
181
+ const name =
182
+ position === 0
183
+ ? (typescriptPath(variable) ?? variable.name)
184
+ : `.${variable.name}`;
185
+ return index === undefined ? name : `${name}[${index}]`;
186
+ })
187
+ .join("");
188
+
189
+ /**
190
+ * Where the debugger looks: which task runs each routine, every block instance, and the
191
+ * probes each instrumented statement gets. Probes follow `debug`; with no settings there are none.
192
+ */
193
+ export class DebugAnalysis {
194
+ readonly tasks;
195
+ readonly instances;
196
+ readonly probes = new Map<CoreStatement, Probe[]>();
197
+ readonly events: EventSite[] = [];
198
+ readonly writers: WriterSite[][];
199
+ /**
200
+ * Event sites of each job block: its start, with the entry step, and its completion, with the
201
+ * last step or the negated error. Steps in between are not recorded: a job that polls would fill the ring.
202
+ */
203
+ readonly jobSites = new Map<string, { start: number; completion: number }>();
204
+ /** Decision slots by routine. */
205
+ readonly decisions = new Map<string, number>();
206
+ /**
207
+ * Call sites per routine, a call in a loop counting as many. A decision has one last-value slot,
208
+ * so a function called more than once per scan would flip it on every call and flood the ring.
209
+ */
210
+ private readonly callSites = new Map<string, number>();
211
+ /** Blocks that contain a service call, so they carry the requesting job's id down to it. */
212
+ readonly carriers = new Set<string>();
213
+ private readonly tables: CoreTables;
214
+ private readonly routineWrites = new Map<string, ReadonlySet<string>>();
215
+ private readonly temporaries = new Map<
216
+ string,
217
+ ReadonlyMap<string, readonly CoreStatement[]>
218
+ >();
219
+ /** The last writer site id given out; the first follows the id of a slot never written. */
220
+ private writerSites = neverWrittenSlot;
221
+
222
+ constructor(
223
+ private readonly core: VerifiedCoreModule,
224
+ deployment: Deployment,
225
+ settings: ResolvedDebugConfig | undefined,
226
+ readonly outputs: readonly Output[],
227
+ ) {
228
+ this.tables = coreTables(core);
229
+ this.writers = outputs.map(() => []);
230
+ this.tasks = routineTasks(core, deployment);
231
+ this.instances = blockInstances(core);
232
+ this.findCarriers();
233
+ if (!settings) {
234
+ return;
235
+ }
236
+ const routines = [
237
+ ...core.functions,
238
+ ...core.blocks.filter((block) => !block.standard),
239
+ ];
240
+ for (const routine of routines) {
241
+ this.countCalls(routine.body, 1);
242
+ }
243
+ for (const routine of routines) {
244
+ this.walk(settings, routine, routine.body, [], []);
245
+ }
246
+ if (settings.trace) {
247
+ for (const block of core.blocks) {
248
+ const { job } = block;
249
+ const task = this.tasks.get(block.id);
250
+ if (!job || !task || this.instances.get(block.id)?.length !== 1) {
251
+ continue;
252
+ }
253
+ const site = (type: string, phase: "started" | "finished") =>
254
+ this.site({
255
+ kind: "job",
256
+ job: { block: block.id, phase },
257
+ path: job.name,
258
+ type,
259
+ span: job.span,
260
+ text: `${job.name}: ${phase}`,
261
+ task,
262
+ });
263
+ this.jobSites.set(block.id, {
264
+ start: site("UINT", "started"),
265
+ completion: site("DINT", "finished"),
266
+ });
267
+ }
268
+ }
269
+ }
270
+
271
+ /** The instance path of a job declaration, when it declares exactly one instance. */
272
+ owningPath(variable: Variable): InstancePath | undefined {
273
+ const type = this.tables.types.get(variable.type);
274
+ const block =
275
+ type?.kind === "block" ? this.tables.blockOf(type.block) : undefined;
276
+ if (!block?.job) {
277
+ return undefined;
278
+ }
279
+ const paths = required(this.instances.get(block.id)).filter(
280
+ (path) => path.at(-1)?.variable.id === variable.id,
281
+ );
282
+ return paths.length === 1 ? paths[0] : undefined;
283
+ }
284
+
285
+ private site(
286
+ site: Omit<EventSite, "id" | "operands"> & { operands?: Operand[] },
287
+ ): number {
288
+ const id = this.events.length + 1;
289
+ this.events.push({ ...site, id, operands: site.operands ?? [] });
290
+ return id;
291
+ }
292
+
293
+ private findCarriers(): void {
294
+ const carries = (id: string): boolean => {
295
+ const block = this.tables.blockOf(id);
296
+ if (block.runtime?.kind === "http") {
297
+ return true;
298
+ }
299
+ return block.state.some((child) => {
300
+ const type = instancedBlock(child.type, this.tables.types);
301
+ return type !== undefined && carries(type.block);
302
+ });
303
+ };
304
+ for (const block of this.core.blocks) {
305
+ if (carries(block.id)) {
306
+ this.carriers.add(block.id);
307
+ }
308
+ }
309
+ }
310
+
311
+ private countCalls(items: readonly CoreStatement[], weight: number): void {
312
+ for (const item of items) {
313
+ if (item.kind === "invoke") {
314
+ this.callSites.set(
315
+ item.function,
316
+ (this.callSites.get(item.function) ?? 0) + weight,
317
+ );
318
+ }
319
+ for (const body of nestedBodies(item)) {
320
+ this.countCalls(body, item.kind === "for" ? callsInLoop : weight);
321
+ }
322
+ }
323
+ }
324
+
325
+ /** Storage a routine can assign, including through every routine it calls. */
326
+ private writes(routine: Routine): ReadonlySet<string> {
327
+ const cached = this.routineWrites.get(routine.id);
328
+ if (cached) {
329
+ return cached;
330
+ }
331
+ const result = new Set<string>();
332
+ this.routineWrites.set(routine.id, result);
333
+ for (const root of this.statementWrites(routine.body)) {
334
+ result.add(root);
335
+ }
336
+ return result;
337
+ }
338
+
339
+ private statementWrites(items: readonly CoreStatement[]): Set<string> {
340
+ const result = new Set<string>();
341
+ for (const item of items) {
342
+ for (const root of directWrites(item)) {
343
+ result.add(root);
344
+ }
345
+ const called = this.tables.calledRoutineOf(item);
346
+ if (called) {
347
+ for (const root of this.writes(called)) {
348
+ result.add(root);
349
+ }
350
+ }
351
+ for (const body of nestedBodies(item)) {
352
+ for (const root of this.statementWrites(body)) {
353
+ result.add(root);
354
+ }
355
+ }
356
+ }
357
+ return result;
358
+ }
359
+
360
+ /**
361
+ * Visit each statement with the statements that precede it on its path, one list per
362
+ * nesting level, and the `if`/`switch` guards enclosing it, innermost last.
363
+ */
364
+ private walk(
365
+ settings: ResolvedDebugConfig,
366
+ routine: Routine,
367
+ items: readonly CoreStatement[],
368
+ prefixes: readonly (readonly CoreStatement[])[],
369
+ guards: readonly { conditions: readonly CoreExpression[]; depth: number }[],
370
+ ): void {
371
+ for (const [index, item] of items.entries()) {
372
+ const here = [...prefixes, items.slice(0, index)];
373
+ this.probe(settings, routine, item, here, guards);
374
+ const guard = (conditions: readonly CoreExpression[]) => [
375
+ ...guards,
376
+ { conditions, depth: here.length },
377
+ ];
378
+ if (item.kind === "if") {
379
+ this.walk(settings, routine, item.then, here, guard([item.condition]));
380
+ this.walk(settings, routine, item.else, here, guard([item.condition]));
381
+ }
382
+ if (item.kind === "switch") {
383
+ for (const body of nestedBodies(item)) {
384
+ this.walk(settings, routine, body, here, guard([item.value]));
385
+ }
386
+ }
387
+ if (item.kind === "for") {
388
+ this.walk(settings, routine, item.body, here, guards);
389
+ }
390
+ }
391
+ }
392
+
393
+ private probe(
394
+ settings: ResolvedDebugConfig,
395
+ routine: Routine,
396
+ item: CoreStatement,
397
+ prefixes: readonly (readonly CoreStatement[])[],
398
+ guards: readonly { conditions: readonly CoreExpression[]; depth: number }[],
399
+ ): void {
400
+ const task = this.tasks.get(routine.id);
401
+ const probes: Probe[] = [];
402
+ const written = writtenPlace(item);
403
+ const reached =
404
+ written && settings.writers
405
+ ? this.outputs.flatMap((output, index) => {
406
+ const when = this.reaches(written.root, written.path, output);
407
+ return when ? [{ index, when }] : [];
408
+ })
409
+ : [];
410
+ if (reached.length) {
411
+ const site = ++this.writerSites;
412
+ for (const { index, when } of reached) {
413
+ required(this.writers[index]).push({
414
+ id: site,
415
+ routine: routine.id,
416
+ span: item.span,
417
+ statement: item,
418
+ });
419
+ probes.push({ kind: "writer", site, output: index, when });
420
+ }
421
+ }
422
+ if (settings.trace && task) {
423
+ if (item.kind === "assign") {
424
+ const root = this.tables.variableOf(item.root);
425
+ const type = this.tables.placeType(root.type, item.path ?? []);
426
+ const path =
427
+ root.storage === "module"
428
+ ? typescriptPath(root, item.path)
429
+ : undefined;
430
+ if (type?.kind === "enum" && path) {
431
+ const operands = this.operands(
432
+ routine,
433
+ prefixes,
434
+ guards,
435
+ settings.trace,
436
+ );
437
+ const site = this.site({
438
+ kind: "state",
439
+ path,
440
+ routine: routine.id,
441
+ type: type.id,
442
+ span: item.span,
443
+ task,
444
+ operands,
445
+ });
446
+ probes.push({ kind: "state", value: item.value, site, operands });
447
+ }
448
+ }
449
+ if (
450
+ item.kind === "return" &&
451
+ item.value &&
452
+ !isBlockRoutine(routine) &&
453
+ routine.result &&
454
+ this.callSites.get(routine.id) === 1
455
+ ) {
456
+ const type = this.tables.types.get(routine.result);
457
+ if (type?.kind === "enum") {
458
+ const slot = this.decisions.get(routine.id) ?? this.decisions.size;
459
+ this.decisions.set(routine.id, slot);
460
+ const path = routine.origin?.instance
461
+ ? `${routine.origin.instance}.${routine.origin.name.split(".").at(-1)}`
462
+ : (routine.origin?.name ?? routine.name);
463
+ const operands = this.operands(
464
+ routine,
465
+ prefixes,
466
+ guards,
467
+ settings.trace,
468
+ );
469
+ const site = this.site({
470
+ kind: "decision",
471
+ path,
472
+ routine: routine.id,
473
+ type: type.id,
474
+ span: item.span,
475
+ task,
476
+ operands,
477
+ });
478
+ probes.push({
479
+ kind: "decision",
480
+ value: item.value,
481
+ site,
482
+ slot,
483
+ operands,
484
+ });
485
+ }
486
+ }
487
+ }
488
+ if (probes.length) {
489
+ this.probes.set(item, probes);
490
+ }
491
+ }
492
+
493
+ /** Undefined when the write can't reach the output; otherwise the dynamic indexes it depends on. */
494
+ private reaches(root: string, path: CorePath, output: Output) {
495
+ if (root !== output.root.id) {
496
+ return undefined;
497
+ }
498
+ const when: { index: CoreExpression; value: number }[] = [];
499
+ for (const [index, written] of path.entries()) {
500
+ const bound = output.segments[index];
501
+ if (!bound) {
502
+ break;
503
+ }
504
+ if (written.kind === "field") {
505
+ if (bound.kind !== "field" || bound.name !== written.name) {
506
+ return undefined;
507
+ }
508
+ continue;
509
+ }
510
+ if (bound.kind !== "index") {
511
+ return undefined;
512
+ }
513
+ const value = constantIndex(written.value);
514
+ if (value === undefined) {
515
+ when.push({ index: written.value, value: bound.value });
516
+ } else if (value !== bound.value) {
517
+ return undefined;
518
+ }
519
+ }
520
+ return when;
521
+ }
522
+
523
+ private isTemporary(routine: Routine, root: string): boolean {
524
+ return isTemporary(routine.id, this.tables.variableOf(root));
525
+ }
526
+
527
+ /** The statements that assign each temporary of a routine. */
528
+ private definitions(
529
+ routine: Routine,
530
+ ): ReadonlyMap<string, readonly CoreStatement[]> {
531
+ const cached = this.temporaries.get(routine.id);
532
+ if (cached) {
533
+ return cached;
534
+ }
535
+ const definitions = new Map<string, CoreStatement[]>();
536
+ const define = (items: readonly CoreStatement[]): void => {
537
+ for (const item of items) {
538
+ const target = wholeTarget(item);
539
+ if (target && this.isTemporary(routine, target)) {
540
+ definitions.set(target, [...(definitions.get(target) ?? []), item]);
541
+ }
542
+ for (const body of nestedBodies(item)) {
543
+ define(body);
544
+ }
545
+ }
546
+ };
547
+ define(routine.body);
548
+ this.temporaries.set(routine.id, definitions);
549
+ return definitions;
550
+ }
551
+
552
+ /** The leaves of the enclosing guards, innermost first, as the site can still read them. */
553
+ private operands(
554
+ routine: Routine,
555
+ prefixes: readonly (readonly CoreStatement[])[],
556
+ guards: readonly { conditions: readonly CoreExpression[]; depth: number }[],
557
+ trace: Exclude<ResolvedDebugConfig["trace"], false>,
558
+ ): Operand[] {
559
+ const definitions = this.definitions(routine);
560
+ const result: Operand[] = [];
561
+ const seen = new Set<string>();
562
+ for (const guard of [...guards].reverse()) {
563
+ const executed = new Set(prefixes.slice(0, guard.depth).flat());
564
+ const between = this.statementWrites(prefixes.slice(guard.depth).flat());
565
+ /** `read` is the storage the leaf reads; a call result has none. */
566
+ const add = (
567
+ span: SourceSpan,
568
+ capture: CoreExpression,
569
+ read?: Load,
570
+ ): void => {
571
+ const kind = this.tables.types.get(capture.type)?.kind;
572
+ const key = `${span.file}:${span.start}:${span.end}`;
573
+ if (
574
+ seen.has(key) ||
575
+ !["bool", "enum", "integer", "bits"].includes(kind ?? "")
576
+ ) {
577
+ return;
578
+ }
579
+ seen.add(key);
580
+ const path =
581
+ read && typescriptPath(this.tables.variableOf(read.root), read.path);
582
+ result.push({
583
+ capture,
584
+ span,
585
+ ...(path && { path }),
586
+ stable: !read || !between.has(read.root),
587
+ });
588
+ };
589
+ // A leaf the guard may have skipped is read again at the site, when that has no effects.
590
+ const direct = (value: Load) =>
591
+ (value.path ?? []).every(
592
+ (segment) =>
593
+ segment.kind === "field" ||
594
+ constantIndex(segment.value) !== undefined,
595
+ );
596
+ const visit = (value: CoreExpression, evaluated: boolean): void => {
597
+ if (value.kind === "unary" || value.kind === "convert") {
598
+ visit(value.operand, evaluated);
599
+ }
600
+ if (value.kind === "binary") {
601
+ visit(value.left, evaluated);
602
+ visit(value.right, evaluated);
603
+ }
604
+ if (value.kind !== "load") {
605
+ return;
606
+ }
607
+ if (!this.isTemporary(routine, value.root)) {
608
+ if (evaluated || direct(value)) {
609
+ add(value.span, value, value);
610
+ }
611
+ return;
612
+ }
613
+ const defined = definitions.get(value.root) ?? [];
614
+ const [item] = defined;
615
+ if (!item || defined.length !== 1) {
616
+ for (const definition of defined) {
617
+ if (definition.kind === "assign") {
618
+ visit(definition.value, evaluated && executed.has(definition));
619
+ }
620
+ }
621
+ return;
622
+ }
623
+ const reached = evaluated && executed.has(item);
624
+ if (item.kind === "invoke") {
625
+ if (reached) {
626
+ add(item.span, value);
627
+ }
628
+ return;
629
+ }
630
+ if (item.kind !== "assign") {
631
+ return;
632
+ }
633
+ const source = item.value;
634
+ if (source.kind === "load" && !this.isTemporary(routine, source.root)) {
635
+ const read = {
636
+ ...source,
637
+ type: value.type,
638
+ path: [...(source.path ?? []), ...(value.path ?? [])],
639
+ };
640
+ if (reached) {
641
+ add(source.span, value, read);
642
+ } else if (direct(read)) {
643
+ add(source.span, read, read);
644
+ }
645
+ return;
646
+ }
647
+ visit(source, reached);
648
+ };
649
+ for (const condition of guard.conditions) {
650
+ visit(condition, true);
651
+ }
652
+ }
653
+ return result.slice(0, trace.operands);
654
+ }
655
+ }