@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,836 @@
1
+ import { basename } from "node:path";
2
+ import { pascalCase } from "@tsplc/compiler/ir";
3
+ import ts from "typescript";
4
+ import { hasModifier } from "../types";
5
+ import type { CapturedValue } from "./capture-protocol";
6
+ import type { EntryImports } from "./imports";
7
+ import {
8
+ arrayLayout,
9
+ type Layouts,
10
+ recordTypes,
11
+ statelessLayout,
12
+ } from "./layouts";
13
+ import {
14
+ children,
15
+ type Model,
16
+ type ModelNode,
17
+ type Owner,
18
+ ownerAt,
19
+ type Root,
20
+ type Step,
21
+ stepPath,
22
+ tsPath,
23
+ } from "./model";
24
+ import { referable, referenceLayout, referenceType } from "./references";
25
+ import { capturedPrimitive, type Value } from "./values";
26
+ import { ScanWrites } from "./writes";
27
+
28
+ /** A primitive scan code read from setup and folded, at its TypeScript path. */
29
+ interface FoldedField {
30
+ path: string;
31
+ value: CapturedValue;
32
+ /** The declaration of the field or array holding it, or its root's. */
33
+ declaration: ts.Node;
34
+ /** The IEC width that declaration names. */
35
+ iec?: string;
36
+ }
37
+
38
+ /** A stored field of a flattened root: a global of the root's storage module. */
39
+ export interface RootField {
40
+ name: string;
41
+ layout: string;
42
+ declaration: ts.Node | undefined;
43
+ }
44
+
45
+ /**
46
+ * Where the state setup built lives in the PLC, and how scan code reads it. A field is stored when
47
+ * scan code writes it or its root is exported; what setup fixed otherwise folds where it is read.
48
+ */
49
+ export class Storage {
50
+ private readonly readConstants = new Set<string>();
51
+ private readonly writes: ScanWrites;
52
+ private readonly storedRoots = new Set<Root>();
53
+ private readonly layoutNames = new Map<string, string>();
54
+
55
+ constructor(
56
+ private readonly model: Model,
57
+ private readonly checker: ts.TypeChecker,
58
+ private readonly layouts: Layouts,
59
+ private readonly imports: EntryImports,
60
+ sources: readonly ts.SourceFile[],
61
+ private readonly kept: (file: string) => boolean,
62
+ private readonly rootModule: (root: Root) => string,
63
+ ) {
64
+ this.writes = new ScanWrites(checker, sources);
65
+ this.typeNames = new Set(
66
+ sources.flatMap((source) =>
67
+ source.statements.flatMap((statement) =>
68
+ (ts.isInterfaceDeclaration(statement) ||
69
+ ts.isTypeAliasDeclaration(statement) ||
70
+ ts.isClassDeclaration(statement) ||
71
+ ts.isEnumDeclaration(statement)) &&
72
+ statement.name
73
+ ? [statement.name.text]
74
+ : [],
75
+ ),
76
+ ),
77
+ );
78
+ }
79
+
80
+ /** The program's own type names, which a root's namespace mustn't take: `line` and the `Line` interface. */
81
+ private readonly typeNames: ReadonlySet<string>;
82
+
83
+ /** The declaration symbol of a captured field, to ask whether scan code writes it. */
84
+ private fieldSymbol(holder: ModelNode, name: string): ts.Symbol | undefined {
85
+ if (holder.captured.kind === "instance") {
86
+ const member = this.model.member(this.model.classOf(holder), name);
87
+ return member && this.checker.getSymbolAtLocation(member.name);
88
+ }
89
+ if (!holder.type) {
90
+ return undefined;
91
+ }
92
+ return this.model.variant(holder.type, holder.captured).getProperty(name);
93
+ }
94
+
95
+ /** Whether a field holds state the PLC stores, rather than a value fixed at setup. */
96
+ stored(holder: ModelNode, name: string): boolean {
97
+ if (holder.owner?.root.exported) {
98
+ return true;
99
+ }
100
+ return this.written(holder, name);
101
+ }
102
+
103
+ /**
104
+ * Whether a stored field still reads as the value setup gave it: a readonly field scan code never
105
+ * assigns, as a collection's capacity is, which an exported root stores for the HMI to read. A
106
+ * root `io` reaches is the hardware's to write, so none of its fields is fixed.
107
+ */
108
+ private fixed(holder: ModelNode, name: string): boolean {
109
+ const declaration = this.fieldDeclaration(holder, name);
110
+ return (
111
+ holder.owner !== undefined &&
112
+ !holder.owner.root.bound &&
113
+ declaration !== undefined &&
114
+ ts.canHaveModifiers(declaration) &&
115
+ hasModifier(declaration, ts.SyntaxKind.ReadonlyKeyword) &&
116
+ !this.written(holder, name)
117
+ );
118
+ }
119
+
120
+ /** Whether scan code assigns the field itself. */
121
+ private written(holder: ModelNode, name: string): boolean {
122
+ const symbol = this.fieldSymbol(holder, name);
123
+ return symbol !== undefined && this.writes.includes(symbol);
124
+ }
125
+
126
+ /**
127
+ * Whether an instance's field stores a reference: one of a class's type that scan code assigns.
128
+ * The PLC keeps the id of the object it refers to, not a copy of the object.
129
+ */
130
+ referenceField(holder: ModelNode, name: string): boolean {
131
+ const key = `${holder.id}.${name}`;
132
+ const known = this.referenceFields.get(key);
133
+ if (known !== undefined) {
134
+ return known;
135
+ }
136
+ const type =
137
+ holder.captured.kind === "instance"
138
+ ? this.model.capturedFieldType(holder, name)
139
+ : undefined;
140
+ const found =
141
+ type !== undefined && referenceType(type) && this.written(holder, name);
142
+ this.referenceFields.set(key, found);
143
+ if (found) {
144
+ this.references.push({ holder, name });
145
+ }
146
+ return found;
147
+ }
148
+
149
+ /** The fields that store a reference, found while laying out instances. */
150
+ private readonly references: { holder: ModelNode; name: string }[] = [];
151
+
152
+ /**
153
+ * Where each referable object is, in the storage spelling the debugger names module storage
154
+ * with, and the storage paths of fields that store a reference: the debugger shows a reference's
155
+ * id as the object it is. Empty when no field stores a reference.
156
+ */
157
+ referenceTable(): {
158
+ references: { id: number; path: string }[];
159
+ referenceFields: string[];
160
+ } {
161
+ if (!this.references.length) {
162
+ return { references: [], referenceFields: [] };
163
+ }
164
+ return {
165
+ references: this.model.nodes.flatMap((node) =>
166
+ referable(node) && node.owner
167
+ ? [{ id: node.reference, path: this.storagePlace(node.owner) }]
168
+ : [],
169
+ ),
170
+ referenceFields: this.references.flatMap(({ holder, name }) =>
171
+ holder.owner ? [`${this.storagePlace(holder.owner)}.${name}`] : [],
172
+ ),
173
+ };
174
+ }
175
+
176
+ /** A place as module storage: its root's module, the root unless flattened, then fields and indexes. */
177
+ private storagePlace(owner: Owner): string {
178
+ const module = basename(this.rootModule(owner.root), ".ts");
179
+ const root = this.flattened(owner.root)
180
+ ? module
181
+ : `${module}.${owner.root.name}`;
182
+ return root + this.stepsText(owner, (_, key) => key);
183
+ }
184
+
185
+ /**
186
+ * The steps from a place's root down to it, as storage spells them: an element of a mixed-state
187
+ * array is a field of its record, and `key` spells a numeric key of the object holding it.
188
+ */
189
+ private stepsText(
190
+ owner: Owner,
191
+ key: (holder: ModelNode | undefined, key: string) => string,
192
+ ): string {
193
+ return owner.steps
194
+ .map((step, index) => {
195
+ const holder = this.model.at(owner.root, owner.steps.slice(0, index));
196
+ if (step.kind === "index" && holder && this.mixedStates(holder)) {
197
+ return `.${mixedItem(step.index)}`;
198
+ }
199
+ return stepPath(step, (name) => key(holder, name));
200
+ })
201
+ .join("");
202
+ }
203
+
204
+ /** Asked of every field each time an instance's layout is, so answered once. */
205
+ private readonly referenceFields = new Map<string, boolean>();
206
+
207
+ /** Array elements are stored when the field holding the array is, or its root is exported. */
208
+ private storedArray(array: ModelNode): boolean {
209
+ const owner = array.owner;
210
+ if (!owner) {
211
+ return false;
212
+ }
213
+ if (owner.root.exported) {
214
+ return true;
215
+ }
216
+ const last = owner.steps.at(-1);
217
+ if (!last) {
218
+ return false;
219
+ }
220
+ const holder = this.model.at(owner.root, owner.steps.slice(0, -1));
221
+ return (
222
+ last.kind === "field" &&
223
+ holder !== undefined &&
224
+ this.stored(holder, last.name)
225
+ );
226
+ }
227
+
228
+ /** Dialect text for a stored node's place. Generated code then reads its root's storage, so this stores the root. */
229
+ pathText(node: ModelNode): string {
230
+ const owner = node.owner;
231
+ if (!owner) {
232
+ throw new Error("An object with no owner has no storage.");
233
+ }
234
+ return this.placeText(owner);
235
+ }
236
+
237
+ /** Dialect text for a place, which stores its root; a `Record<Enum, T>` key indexes by its enum member. */
238
+ private placeText(owner: Owner): string {
239
+ const namespace = this.reach(owner.root);
240
+ const root = this.flattened(owner.root)
241
+ ? namespace
242
+ : `${namespace}.${owner.root.name}`;
243
+ return (
244
+ root +
245
+ this.stepsText(owner, (holder, key) =>
246
+ holder?.type ? this.keyText(holder.type, key) : key,
247
+ )
248
+ );
249
+ }
250
+
251
+ /** The enum member naming a key of a `Record<Enum, T>`. */
252
+ private keyText(type: ts.Type, key: string): string {
253
+ const keyType = recordTypes(type)?.key;
254
+ if (!keyType) {
255
+ return key;
256
+ }
257
+ return this.layouts.enumMember(keyType, Number(key)) ?? key;
258
+ }
259
+
260
+ /**
261
+ * A record or instance root becomes its own global list, one global per field. A table keyed by
262
+ * enum members or numbers is stored whole: its keys name no global.
263
+ */
264
+ flattened(root: Root): boolean {
265
+ const node = this.model.node(root.value);
266
+ if (node?.captured.kind === "instance") {
267
+ return true;
268
+ }
269
+ if (node?.captured.kind !== "object") {
270
+ return false;
271
+ }
272
+ const key = node.type && recordTypes(node.type)?.key;
273
+ return (
274
+ !key ||
275
+ (key.flags & (ts.TypeFlags.EnumLike | ts.TypeFlags.NumberLike)) === 0
276
+ );
277
+ }
278
+
279
+ /**
280
+ * Stores a root and has the entry module import its storage module, and returns the namespace
281
+ * generated code reads that module through.
282
+ */
283
+ private reach(root: Root): string {
284
+ const module = this.rootModule(root);
285
+ const pascal = pascalCase(basename(module, ".ts"));
286
+ this.storedRoots.add(root);
287
+ return this.imports.namespace(
288
+ module,
289
+ this.typeNames.has(pascal) ? `${pascal}Root` : pascal,
290
+ );
291
+ }
292
+
293
+ /** Stores a root whether or not scan code reads it, as exported data must be. */
294
+ use(root: Root): void {
295
+ this.reach(root);
296
+ }
297
+
298
+ /** Roots generated code reached, which need storage declarations. */
299
+ get roots(): ReadonlySet<Root> {
300
+ return this.storedRoots;
301
+ }
302
+
303
+ /** Whether anything inside a node is state the PLC stores. */
304
+ hasState(node: ModelNode): boolean {
305
+ const captured = node.captured;
306
+ if (node.owner?.root.exported) {
307
+ return true;
308
+ }
309
+ if (captured.kind === "instance") {
310
+ return this.instanceFields(node).length > 0;
311
+ }
312
+ if (captured.kind === "array") {
313
+ return (
314
+ this.storedArray(node) ||
315
+ captured.items.some((item, index) => {
316
+ const inner = this.model.node(item);
317
+ return (
318
+ inner !== undefined &&
319
+ this.owns(node, inner, { kind: "index", index }) &&
320
+ this.hasState(inner)
321
+ );
322
+ })
323
+ );
324
+ }
325
+ if (captured.kind === "object") {
326
+ return Object.entries(captured.fields).some(([name, value]) => {
327
+ if (this.stored(node, name)) {
328
+ return true;
329
+ }
330
+ const inner = this.model.node(value);
331
+ return (
332
+ inner !== undefined &&
333
+ this.owns(node, inner, { kind: "field", name }) &&
334
+ this.hasState(inner)
335
+ );
336
+ });
337
+ }
338
+ return false;
339
+ }
340
+
341
+ /**
342
+ * The stored layout of a node, or undefined when nothing in it is stored. Records and arrays
343
+ * keep their declared type; an instance stores a record of the fields that hold its state.
344
+ */
345
+ storageType(node: ModelNode): string | undefined {
346
+ const captured = node.captured;
347
+ if (!this.hasState(node)) {
348
+ return undefined;
349
+ }
350
+ if (captured.kind === "instance") {
351
+ const fields = this.instanceFields(node);
352
+ return this.layoutName(
353
+ `${captured.name}State`,
354
+ fields.map(([field, text]) => `${field}: ${text};`).join(" "),
355
+ this.model.classOf(node),
356
+ );
357
+ }
358
+ if (captured.kind === "array") {
359
+ const first = captured.items[0] && this.model.node(captured.items[0]);
360
+ const states = this.itemLayouts(node);
361
+ // Elements whose states differ, as instances of different subclasses do, are kept side by side.
362
+ if (states && new Set(states).size > 1) {
363
+ return this.layoutName(
364
+ "MixedStates",
365
+ states
366
+ .map(
367
+ (state, index) =>
368
+ `${mixedItem(index)}: ${state ?? statelessLayout};`,
369
+ )
370
+ .join(" "),
371
+ this.holderDeclaration(node),
372
+ );
373
+ }
374
+ const state = states?.[0];
375
+ if (first?.captured.kind === "instance" && state) {
376
+ return arrayLayout(state, captured.items.length).text;
377
+ }
378
+ }
379
+ if (!node.type) {
380
+ throw new Error("Stored state needs a declared type.");
381
+ }
382
+ return this.layouts.declaredText(this.holderDeclaration(node), node.type, {
383
+ kind: "node",
384
+ id: node.id,
385
+ });
386
+ }
387
+
388
+ /**
389
+ * Whether an array holds instances whose states differ, so it is stored as a record with a field
390
+ * per element; scan code reaches each element by an index known when it compiles.
391
+ */
392
+ mixedStates(node: ModelNode): boolean {
393
+ const known = this.mixed.get(node);
394
+ if (known !== undefined) {
395
+ return known;
396
+ }
397
+ const found = this.statesDiffer(node);
398
+ this.mixed.set(node, found);
399
+ return found;
400
+ }
401
+
402
+ /**
403
+ * Every path through an array asks this, and the answer walks all the array holds; setup and the
404
+ * fields scan code writes fix it, so it is worked out once.
405
+ */
406
+ private readonly mixed = new Map<ModelNode, boolean>();
407
+
408
+ private statesDiffer(node: ModelNode): boolean {
409
+ if (!this.hasState(node)) {
410
+ return false;
411
+ }
412
+ const layouts = this.itemLayouts(node);
413
+ return layouts !== undefined && new Set(layouts).size > 1;
414
+ }
415
+
416
+ /**
417
+ * Each element's stored layout, for an array of instances or of records: records holding instances
418
+ * can differ too, as when one instance owns objects the others only refer to.
419
+ */
420
+ private itemLayouts(node: ModelNode): (string | undefined)[] | undefined {
421
+ const captured = node.captured;
422
+ if (captured.kind !== "array") {
423
+ return undefined;
424
+ }
425
+ const items = captured.items.flatMap((item) => {
426
+ const inner = this.model.node(item);
427
+ return inner ? [inner] : [];
428
+ });
429
+ if (items.length !== captured.items.length) {
430
+ return undefined;
431
+ }
432
+ const element = node.type && this.model.elementType(node.type);
433
+ return items.map((item) => {
434
+ if (item.captured.kind === "instance") {
435
+ return this.storageType(item);
436
+ }
437
+ return element
438
+ ? this.layouts.text(element, { kind: "node", id: item.id })
439
+ : undefined;
440
+ });
441
+ }
442
+
443
+ /** Records stored as a whole: anything in them is state. */
444
+ private storedWhole(node: ModelNode): boolean {
445
+ return node.captured.kind !== "instance" && this.hasState(node);
446
+ }
447
+
448
+ /** An instance's stored fields: what scan code writes, and owned objects holding state. */
449
+ instanceFields(node: ModelNode): [string, string][] {
450
+ const captured = node.captured;
451
+ if (captured.kind !== "instance") {
452
+ return [];
453
+ }
454
+ const fields = this.model.fields(this.model.classOf(node));
455
+ return fields.flatMap((member): [string, string][] => {
456
+ const name = member.name.getText();
457
+ const value = this.model.field(node, name);
458
+ const inner = this.model.node(value);
459
+ const type = this.model.capturedFieldType(node, name);
460
+ if (!type) {
461
+ throw new Error(`${captured.name}.${name} has no declared type.`);
462
+ }
463
+ const owned =
464
+ inner !== undefined && this.owns(node, inner, { kind: "field", name });
465
+ if (this.referenceField(node, name)) {
466
+ // The object setup put there is stored through this field, which a reference would replace.
467
+ if (owned) {
468
+ throw new Error(
469
+ `${captured.name}.${name} is assigned in scan code, but it is where setup first put the object it starts with, so that object is stored there. Give the object another owner: a module constant, or a readonly field setup assigns before this one.`,
470
+ );
471
+ }
472
+ return [[name, referenceLayout]];
473
+ }
474
+ if (inner) {
475
+ if (callable(inner)) {
476
+ return [];
477
+ }
478
+ if (!owned) {
479
+ if (!this.stored(node, name)) {
480
+ return [];
481
+ }
482
+ // A stored field holds its own copy of the record setup gave it. A copied instance
483
+ // keeps the record its class's type describes, which emitted ST names `ST_<Class>`.
484
+ const layout =
485
+ inner.captured.kind === "instance"
486
+ ? this.layouts.text(type, value)
487
+ : this.layouts.declaredText(member, type, value);
488
+ return [[name, layout]];
489
+ }
490
+ if (inner.captured.kind !== "instance" && this.stored(node, name)) {
491
+ return [[name, this.layouts.declaredText(member, type, value)]];
492
+ }
493
+ const text = this.storageType(inner);
494
+ return text ? [[name, text]] : [];
495
+ }
496
+ if (!this.stored(node, name)) {
497
+ return [];
498
+ }
499
+ return [[name, this.layouts.declaredText(member, type, value)]];
500
+ });
501
+ }
502
+
503
+ /** A flattened root's stored fields, each a global of its storage module; an exported record stores every field. */
504
+ rootFields(root: Root): RootField[] {
505
+ const node = this.model.node(root.value);
506
+ if (node?.captured.kind === "instance") {
507
+ const declaration = this.model.classOf(node);
508
+ return this.instanceFields(node).map(([name, layout]) => ({
509
+ name,
510
+ layout,
511
+ declaration: this.model.member(declaration, name),
512
+ }));
513
+ }
514
+ if (node?.captured.kind !== "object") {
515
+ return [];
516
+ }
517
+ return Object.entries(node.captured.fields).flatMap(
518
+ ([name, value]): RootField[] => {
519
+ const declared = this.model.capturedFieldType(node, name);
520
+ if (!declared) {
521
+ return [];
522
+ }
523
+ const declaration = this.fieldDeclaration(node, name);
524
+ const inner = this.model.node(value);
525
+ if (inner && callable(inner)) {
526
+ return [];
527
+ }
528
+ if (root.exported || (!inner && this.stored(node, name))) {
529
+ const hint = name.charAt(0).toUpperCase() + name.slice(1);
530
+ return [
531
+ {
532
+ name,
533
+ layout: this.layouts.declaredText(
534
+ declaration,
535
+ declared,
536
+ value,
537
+ hint,
538
+ ),
539
+ declaration,
540
+ },
541
+ ];
542
+ }
543
+ if (!inner) {
544
+ return [];
545
+ }
546
+ // A record scan code assigns as a whole holds its own copy of what setup gave it.
547
+ const layout =
548
+ inner.captured.kind === "object" && this.stored(node, name)
549
+ ? this.layouts.declaredText(declaration, declared, value)
550
+ : this.storageType(inner);
551
+ return layout ? [{ name, layout, declaration }] : [];
552
+ },
553
+ );
554
+ }
555
+
556
+ private layoutName(
557
+ base: string,
558
+ body: string,
559
+ origin: ts.Node | undefined,
560
+ ): string {
561
+ const known = this.layoutNames.get(body);
562
+ if (known) {
563
+ return known;
564
+ }
565
+ const name = this.layouts.declare(base, body, origin);
566
+ this.layoutNames.set(body, name);
567
+ return name;
568
+ }
569
+
570
+ rootValue(root: Root): Value {
571
+ const value = root.value;
572
+ if (value.kind === "node") {
573
+ const node = this.model.node(value);
574
+ // Scan code calls a service client or a task, so it stays an object setup built.
575
+ if (
576
+ this.kept(root.file) &&
577
+ node.captured.kind !== "service" &&
578
+ node.captured.kind !== "task"
579
+ ) {
580
+ return this.keptRoot(root);
581
+ }
582
+ return { kind: "static", node };
583
+ }
584
+ if (
585
+ this.kept(root.file) ||
586
+ ts.getCombinedNodeFlags(root.declaration) & ts.NodeFlags.Const
587
+ ) {
588
+ return capturedPrimitive(value);
589
+ }
590
+ // A module `let` of a plain module is state in its own global list.
591
+ const namespace = this.reach(root);
592
+ const input = this.input({ root, steps: [] });
593
+ return {
594
+ kind: "code",
595
+ text: `${namespace}.${root.name}`,
596
+ declared: this.checker.getTypeAtLocation(root.declaration.name),
597
+ place: true,
598
+ iec: this.layouts.iecName(root.declaration),
599
+ ...(input && { input }),
600
+ };
601
+ }
602
+
603
+ /** A binding in a module the program keeps, read through the entry's import of it. */
604
+ private keptRoot(root: Root): Value {
605
+ return {
606
+ kind: "code",
607
+ text: this.imports.kept.add(root.file, root.name),
608
+ declared: this.checker.getTypeAtLocation(root.declaration.name),
609
+ place: !(ts.getCombinedNodeFlags(root.declaration) & ts.NodeFlags.Const),
610
+ };
611
+ }
612
+
613
+ /** A known node or primitive read from a captured object at one step. */
614
+ fromCaptured(value: CapturedValue, holder: ModelNode, step: Step): Value {
615
+ if (value.kind === "node") {
616
+ const node = this.model.node(value);
617
+ // A reference field is a place too, though it starts as an object: it holds that object's id.
618
+ if (step.kind === "field" && this.referenceField(holder, step.name)) {
619
+ return this.storedField(holder, step);
620
+ }
621
+ // A field scan code assigns as a whole is a place, holding its own copy of what setup gave it.
622
+ if (
623
+ (node.captured.kind === "object" || node.captured.kind === "array") &&
624
+ step.kind === "field" &&
625
+ this.written(holder, step.name)
626
+ ) {
627
+ return node.captured.kind === "array"
628
+ ? this.storedArrayField(holder, step.name, node)
629
+ : this.storedField(holder, step);
630
+ }
631
+ return { kind: "static", node };
632
+ }
633
+ const stored =
634
+ step.kind === "field"
635
+ ? this.stored(holder, step.name) && !this.fixed(holder, step.name)
636
+ : this.storedArray(holder);
637
+ if (stored) {
638
+ return this.storedField(holder, step);
639
+ }
640
+ if (holder.owner) {
641
+ this.readConstants.add(tsPath(ownerAt(holder.owner, step)));
642
+ }
643
+ return capturedPrimitive(value);
644
+ }
645
+
646
+ /** A captured field's declaration: a class member or a record's property. */
647
+ private fieldDeclaration(
648
+ holder: ModelNode,
649
+ name: string,
650
+ ): ts.Node | undefined {
651
+ return holder.captured.kind === "instance"
652
+ ? this.model.member(this.model.classOf(holder), name)
653
+ : this.fieldSymbol(holder, name)?.valueDeclaration;
654
+ }
655
+
656
+ /** The IEC width a captured field's declaration names. */
657
+ private fieldIec(holder: ModelNode, name: string): string | undefined {
658
+ return this.layouts.iecName(this.fieldDeclaration(holder, name));
659
+ }
660
+
661
+ /** The declaration of the field holding a record or array. */
662
+ private holderDeclaration(node: ModelNode): ts.Node | undefined {
663
+ const owner = node.owner;
664
+ const last = owner?.steps.at(-1);
665
+ if (!owner || last?.kind !== "field") {
666
+ return undefined;
667
+ }
668
+ const holder = this.model.at(owner.root, owner.steps.slice(0, -1));
669
+ return holder && this.fieldDeclaration(holder, last.name);
670
+ }
671
+
672
+ /** The IEC width of an array's elements, from the declaration holding the array. */
673
+ private arrayElementIec(array: ModelNode): string | undefined {
674
+ return this.layouts.elementIec(this.holderDeclaration(array));
675
+ }
676
+
677
+ /**
678
+ * Primitives setup stored in fields and arrays that scan code only reads. Specialization folds
679
+ * them into the code, so they have no storage; this is where their values remain known.
680
+ */
681
+ folded(): FoldedField[] {
682
+ const found: FoldedField[] = [];
683
+ const visit = (node: ModelNode, owner: Owner, whole: boolean): void => {
684
+ const captured = node.captured;
685
+ // A record or array stored as a whole stores everything in it; a flattened root stores fields.
686
+ const stores =
687
+ whole ||
688
+ (captured.kind === "object" &&
689
+ !(owner.steps.length === 0 && this.flattened(owner.root)) &&
690
+ this.storedWhole(node)) ||
691
+ (captured.kind === "array" && this.storedArray(node));
692
+ for (const [step, value] of children(captured)) {
693
+ const at = ownerAt(owner, step);
694
+ const inner = this.model.node(value);
695
+ if (inner) {
696
+ // Visit what this node owns; other places holding it refer to its owner.
697
+ if (this.model.ownsAt(inner, at)) {
698
+ visit(inner, at, stores);
699
+ }
700
+ continue;
701
+ }
702
+ if (
703
+ value.kind === "undefined" ||
704
+ stores ||
705
+ !this.readConstants.has(tsPath(at))
706
+ ) {
707
+ continue;
708
+ }
709
+ if (step.kind === "field" && this.stored(node, step.name)) {
710
+ continue;
711
+ }
712
+ const declaration =
713
+ step.kind === "field"
714
+ ? this.fieldDeclaration(node, step.name)
715
+ : this.holderDeclaration(node);
716
+ const iec =
717
+ step.kind === "field"
718
+ ? this.fieldIec(node, step.name)
719
+ : this.arrayElementIec(node);
720
+ found.push({
721
+ path: tsPath(at),
722
+ value,
723
+ declaration: declaration ?? owner.root.declaration,
724
+ ...(iec && { iec }),
725
+ });
726
+ }
727
+ };
728
+ for (const root of this.model.roots) {
729
+ const node = this.model.node(root.value);
730
+ if (
731
+ node?.owner?.root === root &&
732
+ !root.exported &&
733
+ !this.kept(root.file)
734
+ ) {
735
+ visit(node, { root, steps: [] }, false);
736
+ }
737
+ }
738
+ return found;
739
+ }
740
+
741
+ private storedField(holder: ModelNode, step: Step): Value {
742
+ const owner = holder.owner;
743
+ if (!owner) {
744
+ throw new Error("An object with no owner has no storage.");
745
+ }
746
+ const declared =
747
+ step.kind === "index"
748
+ ? holder.type && this.model.elementType(holder.type)
749
+ : this.model.capturedFieldType(holder, step.name);
750
+ const input = this.input(ownerAt(owner, step));
751
+ return {
752
+ kind: "code",
753
+ text: this.placeText(ownerAt(owner, step)),
754
+ declared,
755
+ place: true,
756
+ ...(input && { input }),
757
+ ...(step.kind === "field"
758
+ ? {
759
+ iec: this.fieldIec(holder, step.name),
760
+ elementIec: this.layouts.elementIec(
761
+ this.fieldDeclaration(holder, step.name),
762
+ ),
763
+ }
764
+ : { iec: this.arrayElementIec(holder) }),
765
+ };
766
+ }
767
+
768
+ /** An input the hardware writes at `place` or inside it, which scan code must not assign. */
769
+ private input(place: Owner): { path: string; address: string } | undefined {
770
+ const path = tsPath(place);
771
+ for (const [bound, address] of this.model.inputs) {
772
+ if (
773
+ bound === path ||
774
+ bound.startsWith(`${path}.`) ||
775
+ bound.startsWith(`${path}[`)
776
+ ) {
777
+ return { path: bound, address };
778
+ }
779
+ }
780
+ return undefined;
781
+ }
782
+
783
+ /** A stored array field, with the layout and length of the array setup put there, which an array parameter takes when the field is passed to one. */
784
+ private storedArrayField(
785
+ holder: ModelNode,
786
+ name: string,
787
+ array: ModelNode,
788
+ ): Value {
789
+ const stored = this.storedField(holder, { kind: "field", name });
790
+ if (
791
+ stored.kind !== "code" ||
792
+ !stored.declared ||
793
+ !this.checker.isArrayType(stored.declared) ||
794
+ array.captured.kind !== "array"
795
+ ) {
796
+ return stored;
797
+ }
798
+ return {
799
+ ...stored,
800
+ layout: this.layouts.declaredArray(
801
+ this.fieldDeclaration(holder, name),
802
+ stored.declared,
803
+ { kind: "node", id: array.id },
804
+ ),
805
+ length: array.captured.items.length,
806
+ };
807
+ }
808
+
809
+ /** Whether `holder` owns `node` at `step`. */
810
+ private owns(holder: ModelNode, node: ModelNode, step: Step): boolean {
811
+ return (
812
+ holder.owner !== undefined &&
813
+ this.model.ownsAt(node, ownerAt(holder.owner, step))
814
+ );
815
+ }
816
+
817
+ storedNode(node: ModelNode): boolean {
818
+ return node.captured.kind === "array"
819
+ ? this.storedArray(node)
820
+ : this.storedWhole(node);
821
+ }
822
+ }
823
+
824
+ /** Whether setup built a function, service client or task: scan code calls it, and the PLC stores nothing for it. */
825
+ const callable = (node: ModelNode): boolean =>
826
+ node.captured.kind === "function" ||
827
+ node.captured.kind === "closure" ||
828
+ node.captured.kind === "service" ||
829
+ node.captured.kind === "task";
830
+
831
+ /** The field of a mixed-state array's record that holds element `index`. */
832
+ const mixedItem = (index: number): string => `item${index}`;
833
+
834
+ /** A mixed-state array's record holding each element's value, given as text. */
835
+ export const mixedStateText = (items: readonly string[]): string =>
836
+ `{ ${items.map((item, index) => `${mixedItem(index)}: ${item}`).join(", ")} }`;