@tsplc/compiler 0.5.13 → 0.5.15

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 (263) hide show
  1. package/README.md +33 -8
  2. package/dist/cli.js +794 -621
  3. package/dist/cli.js.map +19 -16
  4. package/dist/clock.js +5 -2
  5. package/dist/clock.js.map +5 -4
  6. package/dist/codesys.js +4162 -4157
  7. package/dist/codesys.js.map +43 -29
  8. package/dist/index.js +7852 -6549
  9. package/dist/index.js.map +53 -50
  10. package/dist/ir.js +2482 -2277
  11. package/dist/ir.js.map +28 -25
  12. package/dist/retain.js +3 -1
  13. package/dist/retain.js.map +3 -3
  14. package/dist/signals.js +115 -0
  15. package/dist/signals.js.map +10 -0
  16. package/dist/telemetry.js +25 -20
  17. package/dist/telemetry.js.map +6 -6
  18. package/package.json +19 -39
  19. package/src/codesys/config.ts +3 -3
  20. package/src/codesys/debug.ts +92 -108
  21. package/src/codesys/emit.ts +100 -88
  22. package/src/codesys/endpoints.ts +111 -0
  23. package/src/codesys/engineering.ts +30 -54
  24. package/src/codesys/explain/expressions.ts +445 -0
  25. package/src/codesys/explain/flags.ts +134 -0
  26. package/src/codesys/explain/parameters.ts +53 -0
  27. package/src/codesys/explain/rows.ts +182 -0
  28. package/src/codesys/explain/tables.ts +79 -0
  29. package/src/codesys/explain/tasks.ts +68 -0
  30. package/src/codesys/explain/writes.ts +497 -0
  31. package/src/codesys/explain.ts +85 -1401
  32. package/src/codesys/expressions.ts +41 -33
  33. package/src/codesys/global-lists.ts +114 -94
  34. package/src/codesys/global-names.ts +12 -14
  35. package/src/codesys/http.ts +428 -388
  36. package/src/codesys/instrumentation.ts +142 -148
  37. package/src/codesys/io-paths.ts +31 -23
  38. package/src/codesys/loops.ts +101 -0
  39. package/src/codesys/manifest.ts +269 -269
  40. package/src/codesys/names.ts +10 -33
  41. package/src/codesys/numeric.ts +89 -42
  42. package/src/codesys/plan.ts +202 -190
  43. package/src/codesys/programs.ts +23 -16
  44. package/src/codesys/publication.ts +13 -86
  45. package/src/codesys/required.ts +8 -0
  46. package/src/codesys/routines.ts +103 -489
  47. package/src/codesys/scheduling.ts +96 -0
  48. package/src/codesys/service-channels.ts +23 -0
  49. package/src/codesys/sources.ts +34 -28
  50. package/src/codesys/st-files.ts +112 -105
  51. package/src/codesys/statements.ts +409 -0
  52. package/src/codesys/storage.ts +41 -23
  53. package/src/codesys/symbols.ts +130 -119
  54. package/src/codesys/task-access.ts +65 -221
  55. package/src/codesys/telemetry-settings.ts +19 -0
  56. package/src/codesys/telemetry.ts +185 -148
  57. package/src/codesys/types.ts +69 -109
  58. package/src/codesys/vendor.ts +13 -50
  59. package/src/frontend/analyzer.ts +66 -111
  60. package/src/frontend/async.ts +316 -128
  61. package/src/frontend/blocks.ts +178 -154
  62. package/src/frontend/configuration.ts +49 -153
  63. package/src/frontend/const-functions.ts +50 -40
  64. package/src/frontend/control-flow.ts +164 -129
  65. package/src/frontend/cooperative.ts +17 -9
  66. package/src/frontend/coroutines.ts +539 -441
  67. package/src/frontend/dialect-names.ts +104 -0
  68. package/src/frontend/elaborate/array-searches.ts +77 -69
  69. package/src/frontend/elaborate/assignments.ts +68 -77
  70. package/src/frontend/elaborate/calls.ts +878 -512
  71. package/src/frontend/elaborate/capture-protocol.ts +118 -21
  72. package/src/frontend/elaborate/capture.ts +196 -109
  73. package/src/frontend/elaborate/declarations.ts +124 -0
  74. package/src/frontend/elaborate/dialect.ts +119 -46
  75. package/src/frontend/elaborate/expressions.ts +763 -442
  76. package/src/frontend/elaborate/filtered-arrays.ts +127 -91
  77. package/src/frontend/elaborate/frame.ts +50 -2
  78. package/src/frontend/elaborate/generics.ts +20 -34
  79. package/src/frontend/elaborate/graph.ts +13 -87
  80. package/src/frontend/elaborate/imports.ts +0 -5
  81. package/src/frontend/elaborate/index.ts +416 -169
  82. package/src/frontend/elaborate/initializers.ts +64 -42
  83. package/src/frontend/elaborate/iterators.ts +228 -364
  84. package/src/frontend/elaborate/layouts.ts +477 -116
  85. package/src/frontend/elaborate/model.ts +113 -55
  86. package/src/frontend/elaborate/references.ts +116 -138
  87. package/src/frontend/elaborate/retention.ts +137 -59
  88. package/src/frontend/elaborate/specialize.ts +617 -308
  89. package/src/frontend/elaborate/statements.ts +436 -247
  90. package/src/frontend/elaborate/storage.ts +280 -213
  91. package/src/frontend/elaborate/time-constructors.ts +34 -0
  92. package/src/frontend/elaborate/values.ts +77 -7
  93. package/src/frontend/elaborate/writes.ts +98 -84
  94. package/src/frontend/expressions.ts +149 -151
  95. package/src/frontend/generated-names.ts +3 -3
  96. package/src/frontend/intrinsics.ts +31 -17
  97. package/src/frontend/lowering-key.ts +23 -0
  98. package/src/frontend/module-graph.ts +105 -43
  99. package/src/frontend/positions.ts +43 -35
  100. package/src/frontend/promise-chains.ts +226 -266
  101. package/src/frontend/promises.ts +88 -67
  102. package/src/frontend/routines.ts +122 -65
  103. package/src/frontend/sdk.ts +104 -5
  104. package/src/frontend/services.ts +149 -102
  105. package/src/frontend/statements.ts +60 -64
  106. package/src/frontend/tasks.ts +151 -96
  107. package/src/frontend/telemetry.ts +1 -1
  108. package/src/frontend/types.ts +366 -181
  109. package/src/frontend/typescript.ts +239 -112
  110. package/src/index.ts +2 -1
  111. package/src/ir/aggregates.ts +90 -75
  112. package/src/ir/allocation.ts +29 -18
  113. package/src/ir/conditions.ts +38 -78
  114. package/src/ir/core-model.ts +128 -11
  115. package/src/ir/declarations.ts +18 -32
  116. package/src/ir/diagnostics.ts +25 -18
  117. package/src/ir/domains.ts +26 -23
  118. package/src/ir/fold.ts +55 -50
  119. package/src/ir/identity.ts +10 -0
  120. package/src/ir/index.ts +31 -7
  121. package/src/ir/job-errors.ts +30 -8
  122. package/src/ir/layouts.ts +63 -34
  123. package/src/ir/link.ts +11 -46
  124. package/src/ir/model.ts +25 -6
  125. package/src/ir/normalize.ts +3 -28
  126. package/src/ir/numeric.ts +45 -18
  127. package/src/ir/operands.ts +102 -0
  128. package/src/ir/ranges.ts +242 -67
  129. package/src/ir/routine.ts +126 -183
  130. package/src/ir/scalars.ts +29 -25
  131. package/src/ir/share.ts +323 -343
  132. package/src/ir/short-circuit.ts +140 -0
  133. package/src/ir/tables.ts +111 -0
  134. package/src/ir/temporaries.ts +15 -113
  135. package/src/ir/types.ts +32 -8
  136. package/src/project/artifacts.ts +143 -71
  137. package/src/project/cli.ts +104 -87
  138. package/src/project/debugger.ts +48 -34
  139. package/src/project/deployments.ts +12 -68
  140. package/src/project/flags.ts +14 -0
  141. package/src/project/plant.ts +293 -225
  142. package/src/project/project-commands.ts +254 -192
  143. package/src/project/project.ts +184 -141
  144. package/src/project/release.ts +22 -28
  145. package/src/project/server.ts +22 -26
  146. package/src/project/terminal.ts +13 -2
  147. package/src/runtime/async.ts +17 -13
  148. package/src/runtime/launch.ts +5 -2
  149. package/src/runtime/main.ts +8 -3
  150. package/src/runtime/missing-file.ts +3 -0
  151. package/src/runtime/process.ts +24 -19
  152. package/src/runtime/program.ts +20 -53
  153. package/src/runtime/retain.ts +18 -10
  154. package/src/runtime/runtime.ts +47 -60
  155. package/src/runtime/settings.ts +27 -0
  156. package/src/runtime/storage.ts +49 -74
  157. package/src/runtime/symbols.ts +19 -75
  158. package/src/runtime/telemetry.ts +37 -14
  159. package/src/runtime/transport.ts +26 -30
  160. package/stdlib/clock.ts +4 -2
  161. package/stdlib/plc-time.ts +2 -0
  162. package/stdlib/retain.ts +2 -0
  163. package/stdlib/signals.ts +142 -0
  164. package/stdlib/telemetry.ts +5 -12
  165. package/types/dialect.d.ts +49 -0
  166. package/types/globals.d.ts +2 -42
  167. package/types/index.d.ts +3 -1
  168. package/types/retain.d.ts +8 -2
  169. package/types/telemetry.d.ts +3 -0
  170. package/dist/bun-runtime.js +0 -1472
  171. package/dist/bun-runtime.js.map +0 -26
  172. package/dist/elaborate-capture.js +0 -304
  173. package/dist/elaborate-capture.js.map +0 -11
  174. package/dist/math.js +0 -24
  175. package/dist/math.js.map +0 -10
  176. package/dist/project.js +0 -626
  177. package/dist/project.js.map +0 -12
  178. package/dist/server-check.js +0 -59
  179. package/dist/server-check.js.map +0 -11
  180. package/src/frontend/exposure.ts +0 -181
  181. package/src/project/index.ts +0 -6
  182. package/src/runtime/.runtime-65O4JH/server/router.ts +0 -17
  183. package/src/runtime/.runtime-65O4JH/src/cell.ts +0 -45
  184. package/src/runtime/.runtime-65O4JH/src/controller.ts +0 -58
  185. package/src/runtime/.runtime-65O4JH/src/lane.ts +0 -6
  186. package/src/runtime/.runtime-65O4JH/src/main.ts +0 -11
  187. package/src/runtime/.runtime-65O4JH/src/services.ts +0 -8
  188. package/src/runtime/.runtime-65O4JH/tsconfig.json +0 -13
  189. package/src/runtime/.runtime-65O4JH/tsplc.config.ts +0 -31
  190. package/src/runtime/.runtime-Brw2kO/server/router.ts +0 -17
  191. package/src/runtime/.runtime-Brw2kO/src/cell.ts +0 -45
  192. package/src/runtime/.runtime-Brw2kO/src/controller.ts +0 -58
  193. package/src/runtime/.runtime-Brw2kO/src/lane.ts +0 -6
  194. package/src/runtime/.runtime-Brw2kO/src/main.ts +0 -11
  195. package/src/runtime/.runtime-Brw2kO/src/services.ts +0 -8
  196. package/src/runtime/.runtime-Brw2kO/tsconfig.json +0 -13
  197. package/src/runtime/.runtime-Brw2kO/tsplc.config.ts +0 -31
  198. package/src/runtime/.runtime-NHfu1D/server/router.ts +0 -17
  199. package/src/runtime/.runtime-NHfu1D/src/cell.ts +0 -45
  200. package/src/runtime/.runtime-NHfu1D/src/controller.ts +0 -58
  201. package/src/runtime/.runtime-NHfu1D/src/lane.ts +0 -6
  202. package/src/runtime/.runtime-NHfu1D/src/main.ts +0 -11
  203. package/src/runtime/.runtime-NHfu1D/src/services.ts +0 -8
  204. package/src/runtime/.runtime-NHfu1D/tsconfig.json +0 -13
  205. package/src/runtime/.runtime-NHfu1D/tsplc.config.ts +0 -31
  206. package/src/runtime/.runtime-VaUSOu/server/router.ts +0 -17
  207. package/src/runtime/.runtime-VaUSOu/src/cell.ts +0 -45
  208. package/src/runtime/.runtime-VaUSOu/src/controller.ts +0 -58
  209. package/src/runtime/.runtime-VaUSOu/src/lane.ts +0 -6
  210. package/src/runtime/.runtime-VaUSOu/src/main.ts +0 -11
  211. package/src/runtime/.runtime-VaUSOu/src/services.ts +0 -8
  212. package/src/runtime/.runtime-VaUSOu/tsconfig.json +0 -13
  213. package/src/runtime/.runtime-VaUSOu/tsplc.config.ts +0 -31
  214. package/src/runtime/.runtime-WbtNvR/server/router.ts +0 -17
  215. package/src/runtime/.runtime-WbtNvR/src/cell.ts +0 -45
  216. package/src/runtime/.runtime-WbtNvR/src/controller.ts +0 -58
  217. package/src/runtime/.runtime-WbtNvR/src/lane.ts +0 -6
  218. package/src/runtime/.runtime-WbtNvR/src/main.ts +0 -11
  219. package/src/runtime/.runtime-WbtNvR/src/services.ts +0 -8
  220. package/src/runtime/.runtime-WbtNvR/tsconfig.json +0 -13
  221. package/src/runtime/.runtime-WbtNvR/tsplc.config.ts +0 -31
  222. package/src/runtime/.runtime-opcua-GMPUt8/server/router.ts +0 -17
  223. package/src/runtime/.runtime-opcua-GMPUt8/src/cell.ts +0 -45
  224. package/src/runtime/.runtime-opcua-GMPUt8/src/controller.ts +0 -58
  225. package/src/runtime/.runtime-opcua-GMPUt8/src/lane.ts +0 -6
  226. package/src/runtime/.runtime-opcua-GMPUt8/src/main.ts +0 -11
  227. package/src/runtime/.runtime-opcua-GMPUt8/src/services.ts +0 -8
  228. package/src/runtime/.runtime-opcua-GMPUt8/tsconfig.json +0 -13
  229. package/src/runtime/.runtime-opcua-GMPUt8/tsplc.config.ts +0 -31
  230. package/src/runtime/.runtime-opcua-UwafxO/server/router.ts +0 -17
  231. package/src/runtime/.runtime-opcua-UwafxO/src/cell.ts +0 -45
  232. package/src/runtime/.runtime-opcua-UwafxO/src/controller.ts +0 -58
  233. package/src/runtime/.runtime-opcua-UwafxO/src/lane.ts +0 -6
  234. package/src/runtime/.runtime-opcua-UwafxO/src/main.ts +0 -11
  235. package/src/runtime/.runtime-opcua-UwafxO/src/services.ts +0 -8
  236. package/src/runtime/.runtime-opcua-UwafxO/tsconfig.json +0 -13
  237. package/src/runtime/.runtime-opcua-UwafxO/tsplc.config.ts +0 -31
  238. package/src/runtime/.runtime-opcua-ecaSee/server/router.ts +0 -17
  239. package/src/runtime/.runtime-opcua-ecaSee/src/cell.ts +0 -45
  240. package/src/runtime/.runtime-opcua-ecaSee/src/controller.ts +0 -58
  241. package/src/runtime/.runtime-opcua-ecaSee/src/lane.ts +0 -6
  242. package/src/runtime/.runtime-opcua-ecaSee/src/main.ts +0 -11
  243. package/src/runtime/.runtime-opcua-ecaSee/src/services.ts +0 -8
  244. package/src/runtime/.runtime-opcua-ecaSee/tsconfig.json +0 -13
  245. package/src/runtime/.runtime-opcua-ecaSee/tsplc.config.ts +0 -31
  246. package/src/runtime/.runtime-opcua-y91UCm/server/router.ts +0 -17
  247. package/src/runtime/.runtime-opcua-y91UCm/src/cell.ts +0 -45
  248. package/src/runtime/.runtime-opcua-y91UCm/src/controller.ts +0 -58
  249. package/src/runtime/.runtime-opcua-y91UCm/src/lane.ts +0 -6
  250. package/src/runtime/.runtime-opcua-y91UCm/src/main.ts +0 -11
  251. package/src/runtime/.runtime-opcua-y91UCm/src/services.ts +0 -8
  252. package/src/runtime/.runtime-opcua-y91UCm/tsconfig.json +0 -13
  253. package/src/runtime/.runtime-opcua-y91UCm/tsplc.config.ts +0 -31
  254. package/src/runtime/.runtime-ybIxYh/server/router.ts +0 -17
  255. package/src/runtime/.runtime-ybIxYh/src/cell.ts +0 -45
  256. package/src/runtime/.runtime-ybIxYh/src/controller.ts +0 -58
  257. package/src/runtime/.runtime-ybIxYh/src/lane.ts +0 -6
  258. package/src/runtime/.runtime-ybIxYh/src/main.ts +0 -11
  259. package/src/runtime/.runtime-ybIxYh/src/services.ts +0 -8
  260. package/src/runtime/.runtime-ybIxYh/tsconfig.json +0 -13
  261. package/src/runtime/.runtime-ybIxYh/tsplc.config.ts +0 -31
  262. package/stdlib/math.ts +0 -23
  263. package/types/plc.d.ts +0 -4
@@ -1,156 +1,23 @@
1
- import type {
2
- Constant,
3
- CoreExpression,
4
- CoreFunction,
5
- CoreFunctionBlock,
6
- CorePath,
7
- CoreStatement,
8
- PathCondition,
9
- PlcType,
10
- ReconstructedSegment,
11
- Reconstruction,
12
- RoutineConditions,
13
- SourceSpan,
14
- } from "@tsplc/compiler/ir";
15
- import {
16
- instancedBlock,
17
- nestedBodies,
18
- pathConditions,
19
- projectReconstruction,
20
- standardBlocks,
21
- } from "@tsplc/compiler/ir";
1
+ import { type CoreStatement, coreTables } from "@tsplc/compiler/ir";
22
2
  import { createExplainer } from "@tsplc/debug/explain";
23
- import type {
24
- ExplainAssignment,
25
- ExplainCall,
26
- ExplainCondition,
27
- ExplainExpression,
28
- ExplainFile,
29
- ExplainFlags,
30
- ExplainLocal,
31
- } from "@tsplc/debug/explain-file";
32
- import type { DebugManifest, SourceRange } from "@tsplc/debug/manifest";
33
- import { createPaths } from "@tsplc/debug/paths";
34
- import { serviceOfPath } from "@tsplc/server";
35
- import { blockInstances, type InstancePath, storagePath } from "./debug";
36
- import { publishedAccess } from "./global-lists";
37
- import { serviceBlock } from "./http";
38
- import { constantValue } from "./manifest";
3
+ import type { ExplainFile } from "@tsplc/debug/explain-file";
4
+ import type { DebugManifest } from "@tsplc/debug/manifest";
5
+ import { blockInstances } from "./debug";
6
+ import { explainEncoder } from "./explain/expressions";
7
+ import { explainFlags } from "./explain/flags";
8
+ import { writtenThroughParameters } from "./explain/parameters";
9
+ import { routineRows } from "./explain/rows";
10
+ import { explainTables } from "./explain/tables";
11
+ import { taskEntries } from "./explain/tasks";
12
+ import { explainWrites } from "./explain/writes";
13
+ import { required } from "./required";
39
14
  import type { Sources } from "./sources";
40
- import { moduleName } from "./storage";
41
15
  import type { EmissionContext } from "./symbols";
42
- import { variablesById } from "./task-access";
43
16
 
44
- type Routine = CoreFunction | CoreFunctionBlock;
45
- type Record = Pick<
46
- ExplainAssignment,
47
- "routine" | "position" | "conditions" | "site"
48
- >;
49
-
50
- /** One routine as one instance runs it: a function, or a block body or method on one block instance. */
51
- interface Row {
52
- readonly index: number;
53
- readonly routine: Routine;
54
- readonly conditions: RoutineConditions;
55
- /** The block instance's storage path. */
56
- readonly instance: string | null;
57
- /** The variables of the block the routine runs on, which are fields of `instance`. */
58
- readonly fields: ReadonlySet<string>;
59
- /** The manifest job this row's block instance is. */
60
- readonly job: number | null;
61
- /**
62
- * The paths, locals and calls its expressions name, each by its slot here: two instances of one
63
- * routine then share their expressions and conditions, and differ only in these tables.
64
- */
65
- readonly slots: { paths: Slots; locals: Slots; calls: Slots };
66
- }
67
-
68
- /** A row's table of global indexes; an expression names an entry by its position here. */
69
- class Slots {
70
- readonly items: number[] = [];
71
- private readonly positions = new Map<number, number>();
72
-
73
- of(global: number): number {
74
- const known = this.positions.get(global);
75
- if (known !== undefined) {
76
- return known;
77
- }
78
- this.positions.set(global, this.items.length);
79
- this.items.push(global);
80
- return this.items.length - 1;
81
- }
82
- }
83
-
84
- /** A place as the debugger names it: a storage path, with a `[*]` for each dynamic index. */
85
- interface Spelled {
86
- readonly text: string;
87
- readonly indexes: readonly number[];
88
- readonly type: PlcType | undefined;
89
- }
90
-
91
- const aggregateKinds: ReadonlySet<PlcType["kind"]> = new Set([
92
- "record",
93
- "array",
94
- "block",
95
- ]);
96
-
97
- /** The most source lines a statement's snippet shows; longer spans are shown by their range alone. */
98
- const maxSnippetLines = 8;
99
-
100
- /** The names along a path of fields and constant indexes, or nothing when an index is dynamic. */
101
- const staticNames = (
102
- path: readonly ReconstructedSegment[],
103
- ): string[] | undefined => {
104
- const names: string[] = [];
105
- for (const segment of path) {
106
- if (segment.kind === "field") {
107
- names.push(segment.name);
108
- } else if (
109
- segment.value.kind === "constant" &&
110
- segment.value.value.kind === "integer"
111
- ) {
112
- names.push(segment.value.value.value);
113
- } else {
114
- return undefined;
115
- }
116
- }
117
- return names;
118
- };
119
-
120
- /** The part of a constant at a path of record fields; an element of an array stays a read of the table. */
121
- const constantAt = (
122
- value: Constant,
123
- names: readonly string[],
124
- ): Constant | undefined => {
125
- const [name, ...rest] = names;
126
- if (name === undefined) {
127
- return value;
128
- }
129
- if (value.kind === "record") {
130
- const field = value.fields[name];
131
- return field && constantAt(field, rest);
132
- }
133
- return undefined;
134
- };
135
-
136
- /** A path with every index as `[*]`, so a pattern and each of its elements compare equal. */
137
- const anyIndex = (path: string): string => path.replace(/\[-?\d+\]/g, "[*]");
138
-
139
- /** An interning table: each distinct value once, by its JSON text. */
140
- class Table<Value> {
141
- readonly items: Value[] = [];
142
- private readonly keys = new Map<string, number>();
143
-
144
- add(value: Value): number {
145
- const key = JSON.stringify(value);
146
- const known = this.keys.get(key);
147
- if (known !== undefined) {
148
- return known;
149
- }
150
- this.keys.set(key, this.items.length);
151
- this.items.push(value);
152
- return this.items.length - 1;
153
- }
17
+ /** A build's `explain.json`, and the assignments of it each statement makes itself. */
18
+ export interface Explanations {
19
+ file: ExplainFile;
20
+ assignmentsOf(statement: CoreStatement): readonly number[];
154
21
  }
155
22
 
156
23
  /**
@@ -167,1260 +34,82 @@ export function explanations(
167
34
  ): Explanations {
168
35
  const { plan, instrumentation } = context;
169
36
  const program = plan.specialized;
170
- const types = new Map(program.types.map((type) => [type.id, type]));
171
- const variables = variablesById(program);
172
- const blocks = new Map(program.blocks.map((block) => [block.id, block]));
173
- const functions = new Map(program.functions.map((fn) => [fn.id, fn]));
37
+ const core = coreTables(program);
174
38
  const instances = blockInstances(program);
175
- const access = publishedAccess(plan);
176
-
177
- const paths = new Table<string>();
178
- const texts = new Table<string>();
179
- const expressions = new Table<ExplainExpression>();
180
- const conditionTree = new Table<ExplainFile["conditions"][number]>();
181
- /** The tree entry for a list of conditions, outermost first. */
182
- const conditionsIndex = (list: readonly ExplainCondition[]): number | null =>
183
- list.reduce<number | null>(
184
- (parent, condition) => conditionTree.add({ parent, condition }),
185
- null,
186
- );
187
- const sites = new Table<ExplainFile["sites"][number]>();
188
- const rows: Row[] = [];
189
- const routineRows: Omit<
190
- ExplainFile["routines"][number],
191
- "job" | "paths" | "locals" | "calls" | "loops"
192
- >[] = [];
193
- const loops: ExplainFile["loops"] = [];
194
- const assignments: ExplainAssignment[] = [];
195
- const locals: ExplainLocal[] = [];
196
- const returns: ExplainFile["returns"] = [];
197
- const calls: ExplainCall[] = [];
198
- const callIndexes = new Map<Row, Map<CoreStatement, number>>();
199
- /** The assignments each statement makes itself, in every instance that runs it. */
200
- const recorded = new Map<CoreStatement, number[]>();
201
- const localIndexes = new Map<string, number>();
202
- const loopBases = new Map<Row, number>();
203
- /** Fields that hold an object reference, with every index as `[*]`. */
204
- const referenceFields = new Set(
205
- (program.references?.fields ?? []).map(anyIndex),
206
- );
207
- /** Rows that read each path, for `writerTasks`. */
208
- const readers = new Map<string, Set<number>>();
209
-
210
- const range = (span: SourceSpan): SourceRange | null =>
211
- sources.range(span) ?? null;
212
- const text = (span: SourceSpan): number | null => {
213
- const source = sources.range(span) && sources.text(span);
214
- return source ? texts.add(source) : null;
215
- };
216
- const site = (span: SourceSpan): number | null => {
217
- const found = range(span);
218
- if (!found) {
219
- return null;
220
- }
221
- // Generated code is mapped to the whole declaration it came from, which is no snippet.
222
- const snippet =
223
- found.endLine - found.line < maxSnippetLines ? text(span) : null;
224
- return sites.add({ range: found, text: snippet });
225
- };
226
- const instanceText = (path: InstancePath): string =>
227
- path
228
- .map(({ variable, index }, position) => {
229
- const name =
230
- position === 0
231
- ? (storagePath(variable) ?? variable.name)
232
- : `.${variable.name}`;
233
- return index === undefined ? name : `${name}[${index}]`;
234
- })
235
- .join("");
236
- const jobInstances = instrumentation.jobs.map(({ block, path }) => ({
237
- block: block.id,
238
- instance: instanceText(path),
239
- }));
240
-
241
- // Routine instances: a function once, a block body or method once per block instance.
242
- const conditionsByRoutine = new Map<string, RoutineConditions>();
243
- const conditionsOf = (routine: Routine) => {
244
- const known = conditionsByRoutine.get(routine.id);
245
- if (known) {
246
- return known;
247
- }
248
- const analysed = pathConditions(routine, variables);
249
- conditionsByRoutine.set(routine.id, analysed);
250
- return analysed;
251
- };
252
- const addRow = (routine: Routine, path: InstancePath | null): void => {
253
- const block =
254
- "inputs" in routine ? routine : blocks.get(routine.owner?.block ?? "");
255
- const instance = path ? instanceText(path) : null;
256
- const job = jobInstances.findIndex(
257
- (item) => item.block === routine.id && item.instance === instance,
258
- );
259
- const row: Row = {
260
- index: rows.length,
261
- routine,
262
- conditions: conditionsOf(routine),
263
- instance,
264
- fields: new Set(
265
- block
266
- ? [...block.inputs, ...block.outputs, ...block.state].map(
267
- (variable) => variable.id,
268
- )
269
- : [],
270
- ),
271
- job: job < 0 ? null : job + 1,
272
- slots: { paths: new Slots(), locals: new Slots(), calls: new Slots() },
273
- };
274
- rows.push(row);
275
- const fn = "parameters" in routine ? routine : undefined;
276
- routineRows.push({
277
- key: routine.id,
278
- function: functionIds.get(routine.id) ?? null,
279
- instance: instance === null ? null : paths.add(instance),
280
- name:
281
- ("inputs" in routine ? routine.job?.name : undefined) ??
282
- fn?.origin?.name ??
283
- routine.name,
284
- declaration: range(
285
- ("inputs" in routine ? routine.job?.span : undefined) ?? routine.span,
286
- ),
287
- });
288
- };
289
- for (const fn of program.functions) {
290
- const owner = fn.owner?.block;
291
- if (owner === undefined) {
292
- addRow(fn, null);
293
- continue;
294
- }
295
- for (const path of instances.get(owner) ?? []) {
296
- addRow(fn, path);
297
- }
298
- }
299
- for (const block of program.blocks) {
300
- if (block.standard || serviceBlock(block) || !block.body.length) {
301
- continue;
302
- }
303
- for (const path of instances.get(block.id) ?? []) {
304
- addRow(block, path);
305
- }
306
- }
307
-
308
- /** The storage path of a place in a row, or nothing for a temporary, local or parameter. */
309
- const spell = (
310
- row: Row,
311
- root: string,
312
- path: readonly ReconstructedSegment[],
313
- ): Spelled | undefined => {
314
- const variable = variables.get(root);
315
- if (!variable) {
316
- return undefined;
317
- }
318
- const base = (): string | undefined => {
319
- if (row.fields.has(root)) {
320
- return row.instance === null
321
- ? undefined
322
- : `${row.instance}.${variable.name}`;
323
- }
324
- if (variable.storage === "constant") {
325
- return `${moduleName(variable)}.${variable.name}`;
326
- }
327
- return storagePath(variable);
328
- };
329
- const start = base();
330
- return start === undefined
331
- ? undefined
332
- : extend(
333
- row,
334
- { text: start, indexes: [], type: types.get(variable.type) },
335
- path,
336
- );
337
- };
338
-
339
- /** A spelled place followed further along a path evaluated in `row`. */
340
- const extend = (
341
- row: Row,
342
- spelled: Spelled,
343
- path: readonly ReconstructedSegment[],
344
- ): Spelled => {
345
- let { text: current, type } = spelled;
346
- const indexes = [...spelled.indexes];
347
- for (const segment of path) {
348
- if (segment.kind === "field") {
349
- if (type?.kind === "block") {
350
- // Block outputs are fields of the instance itself, so its `out` view adds no segment.
351
- if (segment.name === "out") {
352
- type = type.output ? types.get(type.output) : undefined;
353
- continue;
354
- }
355
- const block = blocks.get(type.block);
356
- const field = block
357
- ? [...block.inputs, ...block.outputs, ...block.state].find(
358
- (variable) => variable.name === segment.name,
359
- )
360
- : undefined;
361
- type = field ? types.get(field.type) : undefined;
362
- } else if (type?.kind === "record") {
363
- const field = type.fields.find((item) => item.name === segment.name);
364
- type = field ? types.get(field.type) : undefined;
365
- } else {
366
- type = undefined;
367
- }
368
- current += `.${segment.name}`;
369
- continue;
370
- }
371
- type = type?.kind === "array" ? types.get(type.element) : undefined;
372
- const value = segment.value;
373
- if (value.kind === "constant" && value.value.kind === "integer") {
374
- current += `[${value.value.value}]`;
375
- } else {
376
- current += "[*]";
377
- indexes.push(expression(row, value));
378
- }
379
- }
380
- return { text: current, indexes, type };
381
- };
382
-
383
- const localIndex = (row: Row, root: string): number => {
384
- const key = `${row.index}:${root}`;
385
- const known = localIndexes.get(key);
386
- if (known !== undefined) {
387
- return known;
388
- }
389
- const variable = variables.get(root);
390
- localIndexes.set(key, locals.length);
391
- locals.push({
392
- routine: row.index,
393
- name: variable?.name ?? root,
394
- parameter: variable?.storage === "parameter",
395
- reference: false,
396
- definitions: [],
397
- });
398
- return locals.length - 1;
399
- };
400
-
401
- const opaque = (
402
- reason: string,
403
- type: string,
404
- reads: readonly number[] = [],
405
- ): number =>
406
- expressions.add({
407
- kind: "opaque",
408
- text: texts.add(reason),
409
- reads: [...reads],
410
- type,
411
- });
412
-
413
- const expression = (row: Row, node: Reconstruction): number => {
414
- switch (node.kind) {
415
- case "read": {
416
- // A constant table read at fixed indexes is its value; there is nothing to read live.
417
- const table = variables.get(node.root);
418
- const names = staticNames(node.path);
419
- const fixed =
420
- table?.storage === "constant" && table.initial && names
421
- ? constantAt(table.initial, names)
422
- : undefined;
423
- if (fixed) {
424
- return expressions.add({
425
- kind: "constant",
426
- value: constantValue(fixed),
427
- type: node.type,
428
- });
429
- }
430
- const spelled = spell(row, node.root, node.path);
431
- if (!spelled) {
432
- return opaque("not stored", node.type);
433
- }
434
- const path = row.slots.paths.of(paths.add(spelled.text));
435
- const readBy = readers.get(spelled.text) ?? new Set<number>();
436
- readBy.add(row.index);
437
- readers.set(spelled.text, readBy);
438
- const read = expressions.add(
439
- spelled.indexes.length
440
- ? {
441
- kind: "pattern",
442
- path,
443
- indexes: [...spelled.indexes],
444
- capturedAt: node.capturedAt,
445
- ...(node.interleaved && { interleaved: true as const }),
446
- type: node.type,
447
- }
448
- : {
449
- kind: "read",
450
- path,
451
- capturedAt: node.capturedAt,
452
- ...(node.interleaved && { interleaved: true as const }),
453
- type: node.type,
454
- },
455
- );
456
- // A field holding an object reference holds the object's id: show the object.
457
- return referenceFields.has(anyIndex(spelled.text))
458
- ? expressions.add({ kind: "reference", operand: read })
459
- : read;
460
- }
461
- case "local": {
462
- const names = staticNames(node.path);
463
- return names
464
- ? expressions.add({
465
- kind: "local",
466
- local: row.slots.locals.of(localIndex(row, node.root)),
467
- path: names,
468
- at: node.at,
469
- type: node.type,
470
- })
471
- : opaque("a local at a dynamic index", node.type);
472
- }
473
- case "parameter": {
474
- const names = staticNames(node.path);
475
- if (!names) {
476
- return opaque("a parameter at a dynamic index", node.type);
477
- }
478
- const written = writesThrough.has(
479
- `${row.routine.id}#${node.parameter}`,
480
- );
481
- return expressions.add({
482
- kind: "parameter",
483
- parameter: node.parameter,
484
- path: names,
485
- at: node.at,
486
- local: written
487
- ? row.slots.locals.of(localIndex(row, node.root))
488
- : null,
489
- type: node.type,
490
- });
491
- }
492
- case "call": {
493
- const call = callIndexes.get(row)?.get(node.call);
494
- return call === undefined
495
- ? opaque("a call that isn't traced", node.type)
496
- : expressions.add({
497
- kind: "call",
498
- call: row.slots.calls.of(call),
499
- path: [...node.path],
500
- type: node.type,
501
- });
502
- }
503
- case "constant":
504
- return expressions.add({
505
- kind: "constant",
506
- value: constantValue(node.value),
507
- type: node.type,
508
- });
509
- case "clock":
510
- return expressions.add({ kind: "clock", type: node.type });
511
- case "unary":
512
- return expressions.add({
513
- kind: "unary",
514
- operator: node.operator,
515
- operand: expression(row, node.operand),
516
- type: node.type,
517
- });
518
- case "binary":
519
- return expressions.add({
520
- kind: "binary",
521
- operator: node.operator,
522
- ...(node.policy && { policy: node.policy }),
523
- left: expression(row, node.left),
524
- right: expression(row, node.right),
525
- type: node.type,
526
- });
527
- case "convert":
528
- return expressions.add({
529
- kind: "convert",
530
- policy: node.policy,
531
- operand: expression(row, node.operand),
532
- type: node.type,
533
- });
534
- case "logical":
535
- return expressions.add({
536
- kind: "logical",
537
- operator: node.operator,
538
- left: expression(row, node.left),
539
- right: expression(row, node.right),
540
- });
541
- case "select":
542
- return expressions.add({
543
- kind: "select",
544
- condition: expression(row, node.condition),
545
- // biome-ignore lint/suspicious/noThenProperty: a `?:` branch is data, not a thenable.
546
- then: expression(row, node.then),
547
- else: expression(row, node.else),
548
- type: node.type,
549
- });
550
- case "record":
551
- return expressions.add({
552
- kind: "record",
553
- fields: Object.fromEntries(
554
- Object.entries(node.fields).map(([name, value]) => [
555
- name,
556
- expression(row, value),
557
- ]),
558
- ),
559
- type: node.type,
560
- });
561
- case "array":
562
- return expressions.add({
563
- kind: "array",
564
- lower: node.lower,
565
- items: node.items.map((item) => expression(row, item)),
566
- type: node.type,
567
- });
568
- case "opaque":
569
- return opaque(
570
- node.reason,
571
- node.type,
572
- node.reads.map((read) => expression(row, read)),
573
- );
574
- }
575
- };
576
-
577
- const condition = (row: Row, item: PathCondition): ExplainCondition => {
578
- switch (item.kind) {
579
- case "test":
580
- return {
581
- kind: "test",
582
- test: expression(row, item.test),
583
- holds: item.holds,
584
- at: item.at,
585
- text: text(item.span),
586
- };
587
- case "cases":
588
- return {
589
- kind: "cases",
590
- test: expression(row, item.test),
591
- values: item.values.map(constantValue),
592
- member: item.member,
593
- at: item.at,
594
- text: text(item.span),
595
- };
596
- case "exits":
597
- return {
598
- kind: "exits",
599
- any: item.any.map((all) => all.map((part) => condition(row, part))),
600
- };
601
- case "loop":
602
- case "loopReturns":
603
- // A loop by its index among the row's loops.
604
- return { kind: item.kind, loop: item.loop };
605
- case "job":
606
- return { kind: "job", step: item.step };
607
- case "jobBusy":
608
- return { kind: "jobBusy" };
609
- }
610
- };
611
-
612
- // A routine writes through a by-reference parameter when it assigns it, or passes it on to a
613
- // routine that writes through the parameter it receives it as.
614
- const parameterIndex = (routine: Routine, root: string): number =>
615
- "parameters" in routine
616
- ? routine.parameters.findIndex((parameter) => parameter.id === root)
617
- : -1;
618
- const calleeParameters = (
619
- item: CoreStatement,
620
- ): { routine: string; arguments: readonly CoreExpression[] } | undefined => {
621
- if (item.kind === "invoke") {
622
- return { routine: item.function, arguments: item.arguments };
623
- }
624
- if (item.kind !== "blockUpdate") {
625
- return undefined;
626
- }
627
- const block = instancedBlock(
628
- variables.get(item.instance)?.type ?? "",
629
- types,
630
- );
631
- const called = block && blocks.get(block.block);
632
- return called
633
- ? {
634
- routine: called.id,
635
- arguments: called.inputs.flatMap((input) => {
636
- const value = item.inputs[input.name];
637
- return value ? [value] : [];
638
- }),
639
- }
640
- : undefined;
641
- };
642
- const statementsOf = (items: readonly CoreStatement[]): CoreStatement[] =>
643
- items.flatMap((item) => [
644
- item,
645
- ...nestedBodies(item).flatMap(statementsOf),
646
- ]);
647
- const writesThrough = new Set<string>();
648
- const allRoutines: Routine[] = [...program.functions, ...program.blocks];
649
- const propagate = (): boolean => {
650
- const added = allRoutines.flatMap((routine) =>
651
- statementsOf(routine.body).flatMap((item) => {
652
- const passed = calleeParameters(item);
653
- const indexes = [
654
- ...(item.kind === "assign"
655
- ? [parameterIndex(routine, item.root)]
656
- : []),
657
- ...(passed?.arguments ?? []).flatMap((argument, index) =>
658
- argument.kind === "borrow" &&
659
- writesThrough.has(`${passed?.routine}#${index}`)
660
- ? [parameterIndex(routine, argument.place.root)]
661
- : [],
662
- ),
663
- ];
664
- return indexes
665
- .filter((index) => index >= 0)
666
- .map((index) => `${routine.id}#${index}`)
667
- .filter((key) => !writesThrough.has(key));
668
- }),
669
- );
670
- for (const key of added) {
671
- writesThrough.add(key);
672
- }
673
- return added.length > 0;
674
- };
675
- while (propagate()) {
676
- // Each round adds the parameters that pass a written-through place on.
677
- }
678
-
679
- const segments = (
680
- row: Row,
681
- path: CorePath,
682
- at: number,
683
- ): ReconstructedSegment[] =>
684
- path.map((segment) =>
685
- segment.kind === "field"
686
- ? segment
687
- : {
688
- kind: "index",
689
- value: row.conditions.reconstruct(segment.value, at),
690
- },
691
- );
692
- const written = (spelled: Spelled): ExplainAssignment["writes"] =>
693
- spelled.indexes.length
694
- ? {
695
- kind: "pattern",
696
- path: paths.add(spelled.text),
697
- indexes: [...spelled.indexes],
698
- }
699
- : { kind: "path", path: paths.add(spelled.text) };
700
- const loopOf = (row: Row, loop: number | null): number | null =>
701
- loop === null ? null : (loopBases.get(row) ?? 0) + loop;
702
- const typeIsAggregate = (spelled: Spelled): boolean =>
703
- spelled.type !== undefined && aggregateKinds.has(spelled.type.kind);
704
-
705
- /** The receiver of a call in a row: a block instance's path, or none for a function. */
706
- const receiver = (
707
- row: Row,
708
- instance: string | undefined,
709
- index: CoreExpression | undefined,
710
- at: number,
711
- callee: string,
712
- ): ExplainCall["receiver"] => {
713
- if (instance === undefined) {
714
- return functions.get(callee)?.owner && row.instance !== null
715
- ? { kind: "path", path: paths.add(row.instance) }
716
- : { kind: "none" };
717
- }
718
- const spelled = spell(
719
- row,
720
- instance,
721
- index
722
- ? [{ kind: "index", value: row.conditions.reconstruct(index, at) }]
723
- : [],
724
- );
725
- if (!spelled) {
726
- return { kind: "none" };
727
- }
728
- return spelled.indexes.length
729
- ? {
730
- kind: "pattern",
731
- path: paths.add(spelled.text),
732
- indexes: [...spelled.indexes],
733
- }
734
- : { kind: "path", path: paths.add(spelled.text) };
735
- };
736
-
737
- // Calls get their indexes first, so expressions can name call results.
738
- for (const row of rows) {
739
- const indexes = new Map<CoreStatement, number>();
740
- for (const item of row.conditions.statements.keys()) {
741
- if (item.kind === "invoke" || item.kind === "blockUpdate") {
742
- indexes.set(item, indexes.size + calls.length);
743
- }
744
- }
745
- callIndexes.set(row, indexes);
746
- for (const call of indexes.values()) {
747
- row.slots.calls.of(call);
748
- }
749
- calls.push(
750
- ...[...indexes.keys()].map(
751
- (): ExplainCall => ({
752
- routine: row.index,
753
- position: 0,
754
- conditions: null,
755
- site: null,
756
- callee: "",
757
- receiver: { kind: "none" },
758
- arguments: [],
759
- loop: null,
760
- }),
761
- ),
762
- );
763
- loopBases.set(row, loops.length);
764
- for (const loop of row.conditions.loops) {
765
- loops.push({
766
- routine: row.index,
767
- position: loop.position,
768
- counter: 0,
769
- first: 0,
770
- limit: 0,
771
- exclusive: loop.exclusive,
772
- step: 0,
773
- maxIterations: loop.maxIterations,
774
- breaks: [],
775
- parent: null,
776
- site: site(loop.statement.span),
777
- });
778
- }
779
- }
780
-
781
- for (const row of rows) {
782
- const { routine, conditions } = row;
783
- const base = loopBases.get(row) ?? 0;
784
- conditions.loops.forEach((loop, index) => {
785
- const counter = variables.get(loop.counter);
786
- const slot = loops[base + index];
787
- if (!slot) {
788
- return;
789
- }
790
- loops[base + index] = {
791
- ...slot,
792
- counter: expression(
793
- row,
794
- conditions.reconstruct(
795
- {
796
- kind: "load",
797
- root: loop.counter,
798
- type: counter?.type ?? "DINT",
799
- span: loop.statement.span,
800
- },
801
- loop.position,
802
- ),
803
- ),
804
- first: expression(row, loop.first),
805
- limit: expression(row, loop.limit),
806
- step: expressions.add({
807
- kind: "constant",
808
- value: Number(loop.step),
809
- type: counter?.type ?? "DINT",
810
- }),
811
- breaks: loop.breaks.map((all) =>
812
- all.map((part) => condition(row, part)),
813
- ),
814
- parent: loop.parent === null ? null : base + loop.parent,
815
- };
816
- });
817
- const block = "inputs" in routine ? routine : undefined;
818
- for (const [item, flow] of conditions.statements) {
819
- const first = assignments.length;
820
- const at = flow.position;
821
- const record: Record = {
822
- routine: row.index,
823
- position: at,
824
- conditions: conditionsIndex(
825
- flow.conditions.map((part) => condition(row, part)),
826
- ),
827
- site: site(item.span),
828
- };
829
- const loop = loopOf(row, flow.loop);
830
- const reconstruct = (value: CoreExpression) =>
831
- expression(row, conditions.reconstruct(value, at));
832
- /** A write of `value` to `root`: stored, a local's definition, or nothing for a temporary. */
833
- const write = (
834
- root: string,
835
- path: CorePath,
836
- kind: "assign" | "call" | "counter",
837
- value: number | null,
838
- ): void => {
839
- const variable = variables.get(root);
840
- const parameter = parameterIndex(routine, root);
841
- const local =
842
- variable?.storage === "local" &&
843
- routine.locals.some((candidate) => candidate.id === root);
844
- const temporary = local && root.includes(":temporary:");
845
- if (temporary) {
846
- return;
847
- }
848
- if (local || parameter >= 0) {
849
- const names = staticNames(segments(row, path, at));
850
- const target = locals[localIndex(row, root)];
851
- target?.definitions.push({
852
- ...record,
853
- kind: kind === "counter" ? "counter" : "assign",
854
- path: names ?? [],
855
- value: names ? value : null,
856
- call: null,
857
- loop,
858
- });
859
- return;
860
- }
861
- const spelled = spell(row, root, segments(row, path, at));
862
- if (!spelled) {
863
- return;
864
- }
865
- assignments.push({
866
- ...record,
867
- kind,
868
- writes: written(spelled),
869
- whole: typeIsAggregate(spelled),
870
- value,
871
- block: null,
872
- via: [],
873
- loop,
874
- });
875
- };
876
- /** A local or temporary a call borrows, which the callee writes through. */
877
- const borrowed = (
878
- call: number,
879
- argument: CoreExpression,
880
- index: number,
881
- callee: string,
882
- ) => {
883
- if (
884
- argument.kind !== "borrow" ||
885
- !writesThrough.has(`${callee}#${index}`)
886
- ) {
887
- return;
888
- }
889
- const root = argument.place.root;
890
- const isLocal =
891
- routine.locals.some((candidate) => candidate.id === root) &&
892
- !root.includes(":temporary:");
893
- if (!isLocal && parameterIndex(routine, root) < 0) {
894
- return;
895
- }
896
- const names = staticNames(segments(row, argument.place.path, at));
897
- locals[localIndex(row, root)]?.definitions.push({
898
- ...record,
899
- kind: "borrowed",
900
- path: names ?? [],
901
- value: null,
902
- call,
903
- loop,
904
- });
905
- };
906
- switch (item.kind) {
907
- case "assign":
908
- write(item.root, item.path ?? [], "assign", reconstruct(item.value));
909
- break;
910
- case "invoke": {
911
- const call = callIndexes.get(row)?.get(item) ?? 0;
912
- calls[call] = {
913
- ...record,
914
- callee: item.function,
915
- receiver: receiver(
916
- row,
917
- item.instance,
918
- item.index,
919
- at,
920
- item.function,
921
- ),
922
- arguments: item.arguments.map((argument) => reconstruct(argument)),
923
- loop,
924
- };
925
- item.arguments.forEach((argument, index) => {
926
- borrowed(call, argument, index, item.function);
927
- });
928
- if (item.destination) {
929
- const result = functions.get(item.function)?.result ?? "BOOL";
930
- write(
931
- item.destination,
932
- [],
933
- "call",
934
- expressions.add({ kind: "call", call, path: [], type: result }),
935
- );
936
- }
937
- break;
938
- }
939
- case "blockUpdate": {
940
- const call = callIndexes.get(row)?.get(item) ?? 0;
941
- const instance = variables.get(item.instance);
942
- const type = instancedBlock(instance?.type ?? "", types);
943
- const called = type && blocks.get(type.block);
944
- const target = receiver(
945
- row,
946
- item.instance,
947
- item.index,
948
- at,
949
- called?.id ?? "",
950
- );
951
- const spelled = spell(
952
- row,
953
- item.instance,
954
- item.index
955
- ? [
956
- {
957
- kind: "index",
958
- value: conditions.reconstruct(item.index, at),
959
- },
960
- ]
961
- : [],
962
- );
963
- calls[call] = {
964
- ...record,
965
- callee: called?.id ?? "",
966
- receiver: target,
967
- arguments: (called?.inputs ?? []).flatMap((input) => {
968
- const value = item.inputs[input.name];
969
- return value ? [reconstruct(value)] : [];
970
- }),
971
- loop,
972
- };
973
- if (!called || !spelled) {
974
- break;
975
- }
976
- if (called.standard) {
977
- const native = standardBlocks[called.standard];
978
- const elapsed = native.outputs.some(([name]) => name === "elapsed")
979
- ? extend(row, spelled, [{ kind: "field", name: "elapsed" }])
980
- : undefined;
981
- assignments.push({
982
- ...record,
983
- kind: "block",
984
- writes: written(spelled),
985
- whole: true,
986
- value: null,
987
- block: {
988
- kind: called.standard,
989
- inputs: Object.fromEntries(
990
- Object.entries(item.inputs).map(([name, value]) => [
991
- name,
992
- reconstruct(value),
993
- ]),
994
- ),
995
- elapsed: elapsed
996
- ? expressions.add(
997
- elapsed.indexes.length
998
- ? {
999
- kind: "pattern",
1000
- path: row.slots.paths.of(paths.add(elapsed.text)),
1001
- indexes: [...elapsed.indexes],
1002
- capturedAt: at,
1003
- type: "TIME",
1004
- }
1005
- : {
1006
- kind: "read",
1007
- path: row.slots.paths.of(paths.add(elapsed.text)),
1008
- capturedAt: at,
1009
- type: "TIME",
1010
- },
1011
- )
1012
- : null,
1013
- },
1014
- via: [],
1015
- loop,
1016
- });
1017
- break;
1018
- }
1019
- called.inputs.forEach((input, index) => {
1020
- const value = item.inputs[input.name];
1021
- if (!value) {
1022
- return;
1023
- }
1024
- if (value.kind === "borrow") {
1025
- borrowed(call, value, index, called.id);
1026
- return;
1027
- }
1028
- const field = extend(row, spelled, [
1029
- { kind: "field", name: input.name },
1030
- ]);
1031
- assignments.push({
1032
- ...record,
1033
- kind: "input",
1034
- writes: written(field),
1035
- whole: typeIsAggregate(field),
1036
- value: reconstruct(value),
1037
- block: null,
1038
- via: [],
1039
- loop,
1040
- });
1041
- });
1042
- break;
1043
- }
1044
- case "for":
1045
- write(item.counter, [], "counter", null);
1046
- break;
1047
- case "return": {
1048
- returns.push({
1049
- ...record,
1050
- value: item.value ? reconstruct(item.value) : null,
1051
- });
1052
- const value = item.value;
1053
- if (!block || !value || row.instance === null) {
1054
- break;
1055
- }
1056
- // A block's return writes each output of its instance.
1057
- const returned = conditions.reconstruct(value, at);
1058
- for (const output of block.outputs) {
1059
- const field = spell(row, output.id, []);
1060
- if (!field) {
1061
- continue;
1062
- }
1063
- assignments.push({
1064
- ...record,
1065
- kind: "return",
1066
- writes: written(field),
1067
- whole: typeIsAggregate(field),
1068
- value: expression(
1069
- row,
1070
- projectReconstruction(
1071
- returned,
1072
- [{ kind: "field", name: output.name }],
1073
- output.type,
1074
- ),
1075
- ),
1076
- block: null,
1077
- via: [],
1078
- loop,
1079
- });
1080
- }
1081
- break;
1082
- }
1083
- default:
1084
- break;
1085
- }
1086
- if (assignments.length > first) {
1087
- recorded.set(item, [
1088
- ...(recorded.get(item) ?? []),
1089
- ...Array.from(
1090
- { length: assignments.length - first },
1091
- (_, offset) => first + offset,
1092
- ),
1093
- ]);
1094
- }
1095
- }
1096
- }
1097
-
1098
- // Writes through a by-reference parameter land in the storage each call site passes.
1099
- const calleeRows = (call: ExplainCall, caller: Row): Row[] =>
1100
- rows
1101
- .filter((row) => {
1102
- if (row.routine.id !== call.callee) {
1103
- return false;
1104
- }
1105
- if (call.receiver.kind === "none") {
1106
- return row.instance === null;
1107
- }
1108
- if (call.receiver.kind === "pattern") {
1109
- return false;
1110
- }
1111
- return paths.items[call.receiver.path] === row.instance;
1112
- })
1113
- .concat(
1114
- call.receiver.kind === "none" &&
1115
- caller.instance !== null &&
1116
- functions.get(call.callee)?.owner
1117
- ? rows.filter(
1118
- (row) =>
1119
- row.routine.id === call.callee &&
1120
- row.instance === caller.instance,
1121
- )
1122
- : [],
1123
- );
1124
- const throughParameter = (
1125
- target: Spelled,
1126
- callee: Row,
1127
- parameter: number,
1128
- via: readonly number[],
1129
- depth: number,
1130
- ): void => {
1131
- const root =
1132
- "parameters" in callee.routine
1133
- ? callee.routine.parameters[parameter]?.id
1134
- : undefined;
1135
- if (root === undefined || depth > 16) {
1136
- return;
1137
- }
1138
- for (const [item, flow] of callee.conditions.statements) {
1139
- const at = flow.position;
1140
- const record: Record = {
1141
- routine: callee.index,
1142
- position: at,
1143
- conditions: conditionsIndex(
1144
- flow.conditions.map((part) => condition(callee, part)),
1145
- ),
1146
- site: site(item.span),
1147
- };
1148
- // A written place's runtime indexes are evaluated where the place is named, in the
1149
- // outermost caller; one the callee computes itself isn't followed.
1150
- const fixed = (path: CorePath) =>
1151
- path.every(
1152
- (segment) =>
1153
- segment.kind === "field" || segment.value.kind === "constant",
1154
- );
1155
- if (
1156
- item.kind === "assign" &&
1157
- item.root === root &&
1158
- fixed(item.path ?? [])
1159
- ) {
1160
- const spelled = extend(
1161
- callee,
1162
- target,
1163
- segments(callee, item.path ?? [], at),
1164
- );
1165
- assignments.push({
1166
- ...record,
1167
- kind: "assign",
1168
- writes: written(spelled),
1169
- whole: typeIsAggregate(spelled),
1170
- value: expression(
1171
- callee,
1172
- callee.conditions.reconstruct(item.value, at),
1173
- ),
1174
- block: null,
1175
- via: [...via],
1176
- loop: loopOf(callee, flow.loop),
1177
- });
1178
- }
1179
- const passed = calleeParameters(item);
1180
- const call = callIndexes.get(callee)?.get(item);
1181
- const nested = call === undefined ? undefined : calls[call];
1182
- if (!passed || call === undefined || !nested) {
1183
- continue;
1184
- }
1185
- passed.arguments.forEach((argument, index) => {
1186
- if (
1187
- argument.kind !== "borrow" ||
1188
- argument.place.root !== root ||
1189
- !fixed(argument.place.path) ||
1190
- !writesThrough.has(`${passed.routine}#${index}`)
1191
- ) {
1192
- return;
1193
- }
1194
- const inner = extend(
1195
- callee,
1196
- target,
1197
- segments(callee, argument.place.path, at),
1198
- );
1199
- for (const next of calleeRows(nested, callee)) {
1200
- throughParameter(inner, next, index, [call, ...via], depth + 1);
1201
- }
1202
- });
1203
- }
1204
- };
1205
- for (const row of rows) {
1206
- for (const [item, call] of callIndexes.get(row) ?? []) {
1207
- const passed = calleeParameters(item);
1208
- const record = calls[call];
1209
- if (!passed || !record) {
1210
- continue;
1211
- }
1212
- const at = row.conditions.statements.get(item)?.position ?? 0;
1213
- passed.arguments.forEach((argument, index) => {
1214
- if (
1215
- argument.kind !== "borrow" ||
1216
- !writesThrough.has(`${passed.routine}#${index}`)
1217
- ) {
1218
- return;
1219
- }
1220
- const target = spell(
1221
- row,
1222
- argument.place.root,
1223
- segments(row, argument.place.path, at),
1224
- );
1225
- if (!target) {
1226
- return;
1227
- }
1228
- for (const callee of calleeRows(record, row)) {
1229
- throughParameter(target, callee, index, [call], 0);
1230
- }
1231
- });
1232
- }
1233
- }
1234
-
1235
- // The routines each task runs directly, and every row each task reaches through calls.
1236
- const entries: ExplainFile["entries"] = [];
1237
- const rowTasks = new Map<number, Set<string>>();
1238
- for (const task of plan.specializedTasks.tasks) {
1239
- const reached = new Set<number>();
1240
- const visit = (row: Row): void => {
1241
- if (reached.has(row.index)) {
1242
- return;
1243
- }
1244
- reached.add(row.index);
1245
- const tasks = rowTasks.get(row.index) ?? new Set<string>();
1246
- tasks.add(task.name);
1247
- rowTasks.set(row.index, tasks);
1248
- for (const call of callIndexes.get(row)?.values() ?? []) {
1249
- const record = calls[call];
1250
- if (!record) {
1251
- continue;
1252
- }
1253
- const targets =
1254
- record.receiver.kind === "pattern"
1255
- ? rows.filter((candidate) => candidate.routine.id === record.callee)
1256
- : calleeRows(record, row);
1257
- targets.forEach(visit);
1258
- }
1259
- };
1260
- task.programs.forEach((name) => {
1261
- const entry = program.programs.find((item) => item.name === name)?.entry;
1262
- const row = rows.find(
1263
- (candidate) =>
1264
- candidate.routine.id === entry && candidate.instance === null,
1265
- );
1266
- if (row) {
1267
- entries.push({
1268
- routine: row.index,
1269
- task: task.name,
1270
- order: entries.filter((item) => item.task === task.name).length,
1271
- });
1272
- visit(row);
1273
- }
1274
- });
1275
- }
1276
-
1277
- // Flags, stored at the shortest path they apply to.
1278
- const flags = new Map<string, ExplainFlags>();
1279
- const flag = (path: string): ExplainFlags => {
1280
- const known = flags.get(path);
1281
- if (known) {
1282
- return known;
1283
- }
1284
- const created: ExplainFlags = {
1285
- path: paths.add(path),
1286
- input: null,
1287
- clientWritable: false,
1288
- hmiControl: null,
1289
- retained: false,
1290
- constantTable: false,
1291
- writerTasks: [],
1292
- service: null,
1293
- initial: null,
1294
- reference: false,
1295
- };
1296
- flags.set(path, created);
1297
- return created;
1298
- };
1299
- const writtenPaths = new Set(
1300
- assignments.map((assignment) => paths.items[assignment.writes.path]),
1301
- );
1302
- for (const variable of program.variables) {
1303
- const path =
1304
- variable.storage === "constant"
1305
- ? `${moduleName(variable)}.${variable.name}`
1306
- : storagePath(variable);
1307
- if (path === undefined) {
1308
- continue;
1309
- }
1310
- const published = access(variable) === "readwrite";
1311
- const constant = variable.storage === "constant";
1312
- if (published || variable.retain || constant) {
1313
- const item = flag(path);
1314
- item.clientWritable = published;
1315
- item.retained = variable.retain;
1316
- item.constantTable = constant;
1317
- }
1318
- if (variable.initial && (constant || !writtenPaths.has(path))) {
1319
- flag(path).initial = constantValue(variable.initial);
1320
- }
1321
- }
1322
- manifest.io.forEach((io, index) => {
1323
- if (io.direction === "input") {
1324
- flag(io.path).input = index;
1325
- }
39
+ const tables = explainTables(sources);
40
+ const rows = routineRows({
41
+ program,
42
+ core,
43
+ instances,
44
+ tables,
45
+ jobs: instrumentation.jobs,
46
+ functionIds,
1326
47
  });
1327
- for (const block of program.blocks) {
1328
- const endpoint = plan.http[block.id];
1329
- if (!serviceBlock(block) || !endpoint) {
1330
- continue;
1331
- }
1332
- for (const path of instances.get(block.id) ?? []) {
1333
- const instance = instanceText(path);
1334
- const owner = jobInstances
1335
- .map((job, index) => ({ ...job, id: index + 1 }))
1336
- .filter((job) => instance.startsWith(`${job.instance}.`))
1337
- .sort((a, b) => b.instance.length - a.instance.length)[0];
1338
- flag(instance).service = {
1339
- job: owner?.id ?? 0,
1340
- service: serviceOfPath(endpoint.path) ?? endpoint.path,
1341
- };
1342
- }
1343
- }
1344
- for (const field of program.references?.fields ?? []) {
1345
- flag(field).reference = true;
1346
- }
1347
- // An HMI control names the published IEC symbol it writes.
1348
- const targets = createPaths(manifest);
1349
- for (const control of plan.project.hmi?.controls ?? []) {
1350
- const path = targets.fromTarget(control.target);
1351
- if (path) {
1352
- flag(path).hmiControl = control.label;
1353
- }
1354
- }
1355
- const writers = new Map<string, Set<string>>();
1356
- for (const assignment of assignments) {
1357
- const path = paths.items[assignment.writes.path];
1358
- if (path === undefined) {
1359
- continue;
1360
- }
1361
- const tasks = writers.get(path) ?? new Set<string>();
1362
- for (const task of rowTasks.get(assignment.routine) ?? []) {
1363
- tasks.add(task);
1364
- }
1365
- writers.set(path, tasks);
1366
- }
1367
- for (const [path, tasks] of writers) {
1368
- const readTasks = new Set(
1369
- [...(readers.get(path) ?? [])].flatMap((row) => [
1370
- ...(rowTasks.get(row) ?? []),
1371
- ]),
1372
- );
1373
- if (tasks.size > 1 || [...readTasks].some((task) => !tasks.has(task))) {
1374
- flag(path).writerTasks = [...tasks].sort();
1375
- }
1376
- }
48
+ const writesThrough = writtenThroughParameters([
49
+ ...program.functions,
50
+ ...program.blocks,
51
+ ]);
52
+ const encoder = explainEncoder(program, core, tables, writesThrough);
53
+ const { loops, calls, assignments, returns, recorded } = explainWrites({
54
+ rows,
55
+ core,
56
+ tables,
57
+ encoder,
58
+ writesThrough,
59
+ });
60
+ const { entries, rowTasks } = taskEntries({
61
+ program,
62
+ deployment: plan.specializedTasks,
63
+ rows,
64
+ calls,
65
+ core,
66
+ tables,
67
+ });
68
+ const flags = explainFlags({
69
+ plan,
70
+ program,
71
+ instances,
72
+ instrumentation,
73
+ manifest,
74
+ tables,
75
+ assignments,
76
+ readers: encoder.readers,
77
+ rowTasks,
78
+ });
79
+ const references = Object.fromEntries(
80
+ (program.references?.objects ?? []).map(({ id, path }) => [
81
+ String(id),
82
+ tables.paths.add(path),
83
+ ]),
84
+ );
1377
85
 
1378
86
  const file: ExplainFile = {
1379
87
  kind: "tsplc-explain",
1380
88
  version: 1,
1381
- paths: paths.items,
1382
- texts: texts.items,
1383
- expressions: expressions.items,
1384
- conditions: conditionTree.items,
1385
- sites: sites.items,
1386
- routines: routineRows.map((routine, index) => {
1387
- const row = rows[index];
1388
- const base = row ? (loopBases.get(row) ?? 0) : 0;
1389
- return {
1390
- ...routine,
1391
- job: row?.job ?? null,
1392
- paths: row?.slots.paths.items ?? [],
1393
- locals: row?.slots.locals.items ?? [],
1394
- calls: row?.slots.calls.items ?? [],
1395
- loops: Array.from(
1396
- { length: row?.conditions.loops.length ?? 0 },
1397
- (_, loop) => base + loop,
1398
- ),
1399
- };
1400
- }),
89
+ paths: tables.paths.items,
90
+ texts: tables.texts.items,
91
+ expressions: tables.expressions.items,
92
+ conditions: tables.conditions.items,
93
+ sites: tables.sites.items,
94
+ routines: rows.map((row) => ({
95
+ ...row.entry,
96
+ paths: row.slots.paths.items,
97
+ locals: row.slots.locals.items,
98
+ calls: row.slots.calls.items,
99
+ loops: row.conditions.loops.map((_, loop) => row.firstLoop + loop),
100
+ })),
1401
101
  loops,
1402
102
  assignments,
1403
- locals,
103
+ locals: encoder.locals,
1404
104
  returns,
1405
105
  calls,
1406
106
  entries,
1407
- flags: [...flags.values()],
1408
- references: Object.fromEntries(
1409
- (program.references?.objects ?? []).map(({ id, path }) => [
1410
- String(id),
1411
- paths.add(path),
1412
- ]),
1413
- ),
107
+ flags,
108
+ references,
1414
109
  };
1415
110
  return { file, assignmentsOf: (statement) => recorded.get(statement) ?? [] };
1416
111
  }
1417
112
 
1418
- /** A build's `explain.json`, and the assignments of it each statement makes itself. */
1419
- export interface Explanations {
1420
- file: ExplainFile;
1421
- assignmentsOf(statement: CoreStatement): readonly number[];
1422
- }
1423
-
1424
113
  /**
1425
114
  * The manifest's last-writer slots with the assignments each site stands for, and whether the slot
1426
115
  * names its path's writer exactly: when every statement that can write the path writes it directly,
@@ -1433,15 +122,18 @@ export function explainedWriters(
1433
122
  ): DebugManifest["writers"] {
1434
123
  const explainer = createExplainer(manifest, explained.file);
1435
124
  return manifest.writers.map((writer, index) => {
1436
- const probed = sites[index] ?? [];
1437
- const exact = explainer.explain(writer.output).writers.every((item) => {
1438
- const assignment = explained.file.assignments[item.assignment];
125
+ const probed = required(sites[index]);
126
+ const { writers } = explainer.explain(writer.output);
127
+ const exact = writers.every((item) => {
128
+ const assignment = required(explained.file.assignments[item.assignment]);
1439
129
  return (
1440
- assignment !== undefined &&
1441
130
  (assignment.kind === "assign" || assignment.kind === "call") &&
1442
131
  !assignment.via.length
1443
132
  );
1444
133
  });
134
+ const explainedAssignments = new Set(
135
+ writers.map((item) => item.assignment),
136
+ );
1445
137
  return {
1446
138
  ...writer,
1447
139
  exact,
@@ -1450,15 +142,7 @@ export function explainedWriters(
1450
142
  assignments: probed
1451
143
  .filter((item) => item.id === site.id)
1452
144
  .flatMap((item) => [...explained.assignmentsOf(item.statement)])
1453
- .filter((assignment) => {
1454
- const written = explained.file.assignments[assignment];
1455
- return (
1456
- written !== undefined &&
1457
- explainer
1458
- .explain(writer.output)
1459
- .writers.some((item) => item.assignment === assignment)
1460
- );
1461
- }),
145
+ .filter((assignment) => explainedAssignments.has(assignment)),
1462
146
  })),
1463
147
  };
1464
148
  });