@tsplc/tmp-compiler 0.0.0-stage → 0.6.2

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 (184) 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 +6558 -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 +16076 -0
  12. package/dist/index.js.map +61 -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 +1078 -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-functions.ts +204 -0
  69. package/src/frontend/control-flow.ts +787 -0
  70. package/src/frontend/cooperative.ts +114 -0
  71. package/src/frontend/coroutines.ts +1336 -0
  72. package/src/frontend/dialect-names.ts +104 -0
  73. package/src/frontend/elaborate/array-searches.ts +224 -0
  74. package/src/frontend/elaborate/assignments.ts +343 -0
  75. package/src/frontend/elaborate/calls.ts +1342 -0
  76. package/src/frontend/elaborate/capture-protocol.ts +237 -0
  77. package/src/frontend/elaborate/capture.ts +388 -0
  78. package/src/frontend/elaborate/declarations.ts +124 -0
  79. package/src/frontend/elaborate/dialect.ts +473 -0
  80. package/src/frontend/elaborate/expressions.ts +2171 -0
  81. package/src/frontend/elaborate/filtered-arrays.ts +643 -0
  82. package/src/frontend/elaborate/frame.ts +145 -0
  83. package/src/frontend/elaborate/generics.ts +123 -0
  84. package/src/frontend/elaborate/graph.ts +141 -0
  85. package/src/frontend/elaborate/imports.ts +105 -0
  86. package/src/frontend/elaborate/index.ts +851 -0
  87. package/src/frontend/elaborate/initializers.ts +235 -0
  88. package/src/frontend/elaborate/iterators.ts +1541 -0
  89. package/src/frontend/elaborate/layouts.ts +1025 -0
  90. package/src/frontend/elaborate/model.ts +478 -0
  91. package/src/frontend/elaborate/names.ts +134 -0
  92. package/src/frontend/elaborate/reduce.ts +900 -0
  93. package/src/frontend/elaborate/references.ts +727 -0
  94. package/src/frontend/elaborate/retention.ts +284 -0
  95. package/src/frontend/elaborate/specialize.ts +1137 -0
  96. package/src/frontend/elaborate/statements.ts +1220 -0
  97. package/src/frontend/elaborate/storage.ts +836 -0
  98. package/src/frontend/elaborate/time-constructors.ts +34 -0
  99. package/src/frontend/elaborate/values.ts +200 -0
  100. package/src/frontend/elaborate/writes.ts +415 -0
  101. package/src/frontend/expressions.ts +1382 -0
  102. package/src/frontend/generated-names.ts +95 -0
  103. package/src/frontend/intrinsics.ts +382 -0
  104. package/src/frontend/lowering-key.ts +23 -0
  105. package/src/frontend/module-graph.ts +156 -0
  106. package/src/frontend/positions.ts +359 -0
  107. package/src/frontend/promise-chains.ts +872 -0
  108. package/src/frontend/promises.ts +419 -0
  109. package/src/frontend/routines.ts +239 -0
  110. package/src/frontend/sdk.ts +187 -0
  111. package/src/frontend/services.ts +609 -0
  112. package/src/frontend/statements.ts +871 -0
  113. package/src/frontend/tasks.ts +526 -0
  114. package/src/frontend/telemetry.ts +174 -0
  115. package/src/frontend/types.ts +1073 -0
  116. package/src/frontend/typescript.ts +651 -0
  117. package/src/index.ts +9 -0
  118. package/src/ir/aggregates.ts +291 -0
  119. package/src/ir/allocation.ts +96 -0
  120. package/src/ir/conditions.ts +855 -0
  121. package/src/ir/core-model.ts +289 -0
  122. package/src/ir/declarations.ts +281 -0
  123. package/src/ir/diagnostics.ts +68 -0
  124. package/src/ir/domains.ts +151 -0
  125. package/src/ir/fold.ts +279 -0
  126. package/src/ir/identity.ts +19 -0
  127. package/src/ir/index.ts +137 -0
  128. package/src/ir/job-errors.ts +69 -0
  129. package/src/ir/layouts.ts +211 -0
  130. package/src/ir/link.ts +302 -0
  131. package/src/ir/model.ts +394 -0
  132. package/src/ir/normalization-error.ts +10 -0
  133. package/src/ir/normalize.ts +52 -0
  134. package/src/ir/numeric.ts +163 -0
  135. package/src/ir/operands.ts +160 -0
  136. package/src/ir/ranges.ts +420 -0
  137. package/src/ir/routine.ts +1116 -0
  138. package/src/ir/scalars.ts +453 -0
  139. package/src/ir/share.ts +790 -0
  140. package/src/ir/short-circuit.ts +140 -0
  141. package/src/ir/tables.ts +111 -0
  142. package/src/ir/temporaries.ts +138 -0
  143. package/src/ir/types.ts +151 -0
  144. package/src/project/artifacts.ts +424 -0
  145. package/src/project/cli.ts +211 -0
  146. package/src/project/debugger.ts +111 -0
  147. package/src/project/deployments.ts +387 -0
  148. package/src/project/flags.ts +14 -0
  149. package/src/project/git.ts +35 -0
  150. package/src/project/plant.ts +629 -0
  151. package/src/project/project-commands.ts +507 -0
  152. package/src/project/project.ts +559 -0
  153. package/src/project/release.ts +152 -0
  154. package/src/project/server-check.ts +54 -0
  155. package/src/project/server.ts +165 -0
  156. package/src/project/terminal.ts +45 -0
  157. package/src/runtime/async.ts +207 -0
  158. package/src/runtime/launch.ts +59 -0
  159. package/src/runtime/main.ts +59 -0
  160. package/src/runtime/missing-file.ts +3 -0
  161. package/src/runtime/process.ts +177 -0
  162. package/src/runtime/program.ts +109 -0
  163. package/src/runtime/retain.ts +108 -0
  164. package/src/runtime/runtime.ts +324 -0
  165. package/src/runtime/settings.ts +27 -0
  166. package/src/runtime/storage.ts +456 -0
  167. package/src/runtime/symbols.ts +97 -0
  168. package/src/runtime/telemetry.ts +154 -0
  169. package/src/runtime/transport.ts +168 -0
  170. package/stdlib/clock.ts +8 -0
  171. package/stdlib/collections.ts +534 -0
  172. package/stdlib/plc-time.ts +2 -0
  173. package/stdlib/retain.ts +4 -0
  174. package/stdlib/signals.ts +142 -0
  175. package/stdlib/telemetry.ts +89 -0
  176. package/types/async.d.ts +87 -0
  177. package/types/clock.d.ts +8 -0
  178. package/types/config.d.ts +2 -0
  179. package/types/data-types.d.ts +31 -0
  180. package/types/dialect.d.ts +49 -0
  181. package/types/globals.d.ts +10 -0
  182. package/types/index.d.ts +212 -0
  183. package/types/retain.d.ts +12 -0
  184. package/types/telemetry.d.ts +47 -0
@@ -0,0 +1,104 @@
1
+ import { type Diagnostic, error } from "@tsplc/compiler/ir";
2
+ import ts from "typescript";
3
+ import { plcSources } from "./module-graph";
4
+ import type { Positions } from "./positions";
5
+ import { dialectFor, inSdk, sdkModules, unaliased } from "./sdk";
6
+
7
+ /** The SDK module of timers and edges, plain source a program imports like its own. */
8
+ const signals = "@tsplc/compiler/signals";
9
+
10
+ /** Dialect names a program has no use for, with what to write instead. */
11
+ const unsupported: Readonly<Record<string, string>> = {
12
+ FunctionBlock:
13
+ "write a plain class, whose instances keep their fields from one scan to the next",
14
+ Input:
15
+ "keep the input as a field of the program's state and bind its path in tsplc.config.ts io",
16
+ Output:
17
+ "keep the output as a field of the program's state and bind its path in tsplc.config.ts io",
18
+ InOut:
19
+ "pass the object that holds the value; a callee changes it through that object",
20
+ ref: "pass the object that holds the value; a callee changes it through that object",
21
+ OnDelayTimer: `import OnDelayTimer from ${signals}`,
22
+ OffDelayTimer: `import OffDelayTimer from ${signals}`,
23
+ PulseTimer: `import PulseTimer from ${signals}`,
24
+ RisingEdge: `import RisingEdge from ${signals}`,
25
+ FallingEdge: `import FallingEdge from ${signals}`,
26
+ Blinker:
27
+ "write it as a class, as the timers of @tsplc/compiler/signals are written",
28
+ UpCounter: "count in a field of a class",
29
+ DownCounter: "count in a field of a class",
30
+ UpDownCounter: "count in a field of a class",
31
+ };
32
+
33
+ /** The SDK's internal exports, which the compiler's own generated code calls. */
34
+ const internal = new Set(["cooperativeTasks", "opcuaCall"]);
35
+
36
+ /** The module a program imports a dialect global from, when it may use it at all. */
37
+ const importedFrom = (name: string): string =>
38
+ name === "retain" || name === "persist"
39
+ ? sdkModules.retain
40
+ : sdkModules.types;
41
+
42
+ /**
43
+ * Where a program's own source uses the tsPLC dialect: its function blocks, IO declarations,
44
+ * references and standard blocks, or a global that a plain program imports instead. The compiler
45
+ * lowers programs into the dialect; a program writes plain TypeScript.
46
+ */
47
+ export const dialectUses = (
48
+ program: ts.Program,
49
+ sdk: string,
50
+ positions: Positions,
51
+ ): Diagnostic[] => {
52
+ const checker = program.getTypeChecker();
53
+ const dialect = dialectFor(sdk);
54
+ const diagnostics: Diagnostic[] = [];
55
+ for (const source of plcSources(program)) {
56
+ if (inSdk(sdk, source.fileName)) {
57
+ continue;
58
+ }
59
+ const reported = new Set<string>();
60
+ const visit = (node: ts.Node): void => {
61
+ if (ts.isIdentifier(node) && !reported.has(node.text)) {
62
+ const message = dialectUse(checker, sdk, dialect, node);
63
+ if (message) {
64
+ reported.add(node.text);
65
+ diagnostics.push(error("PLC1015", message, positions.node(node)));
66
+ }
67
+ }
68
+ ts.forEachChild(node, visit);
69
+ };
70
+ visit(source);
71
+ }
72
+ return diagnostics;
73
+ };
74
+
75
+ const dialectUse = (
76
+ checker: ts.TypeChecker,
77
+ sdk: string,
78
+ dialect: string,
79
+ node: ts.Identifier,
80
+ ): string | undefined => {
81
+ const symbol = checker.getSymbolAtLocation(node);
82
+ const declaration = symbol?.declarations?.[0];
83
+ if (!symbol || !declaration) {
84
+ return undefined;
85
+ }
86
+ const ambient = declaration.getSourceFile().fileName === dialect;
87
+ const named = unaliased(checker, symbol).declarations?.[0];
88
+ const fromSdk =
89
+ ambient ||
90
+ (named !== undefined && inSdk(sdk, named.getSourceFile().fileName));
91
+ if (!fromSdk) {
92
+ return undefined;
93
+ }
94
+ const instead = unsupported[node.text];
95
+ if (instead) {
96
+ return `${node.text} is not part of PLC TypeScript: ${instead}.`;
97
+ }
98
+ if (internal.has(node.text)) {
99
+ return `${node.text} is the compiler's own; a program uses tasks, backgroundTasks and createServiceClient.`;
100
+ }
101
+ return ambient
102
+ ? `${node.text} is not a global: import it from ${importedFrom(node.text)}.`
103
+ : undefined;
104
+ };
@@ -0,0 +1,224 @@
1
+ import type ts from "typescript";
2
+ import { mapped } from "../positions";
3
+ import type { ExpressionSpecializer, SpecializeContext } from "./expressions";
4
+ import type { Frame } from "./frame";
5
+ import { constant, SpecializeError, type Value } from "./values";
6
+
7
+ /**
8
+ * Searches and writes over an array setup built, decided at run time. Setup fixed the array's
9
+ * length, so each runs as one test or store per element, in the order JavaScript visits them.
10
+ */
11
+ export class ArraySearches {
12
+ constructor(
13
+ private readonly context: SpecializeContext,
14
+ private readonly expressions: Pick<
15
+ ExpressionSpecializer,
16
+ "expression" | "held" | "localType" | "equality" | "assignments"
17
+ >,
18
+ ) {}
19
+
20
+ /** `indexOf(target)` and `lastIndexOf(target)`: the first or last index of an equal element, or -1. */
21
+ indexOf(
22
+ items: readonly Value[],
23
+ node: ts.CallExpression,
24
+ frame: Frame,
25
+ { last }: { last: boolean },
26
+ ): Value {
27
+ const target = searchTarget(node, frame, this.expressions);
28
+ return this.firstIndex(items, frame, { last }, (item) =>
29
+ this.expressions.equality(item, target, { negate: false }),
30
+ );
31
+ }
32
+
33
+ /** `findIndex(test)` and `findLastIndex(test)`: the test runs on elements until one passes. */
34
+ findIndex(
35
+ items: readonly Value[],
36
+ frame: Frame,
37
+ { last }: { last: boolean },
38
+ apply: (args: Value[]) => Value,
39
+ ): Value {
40
+ return this.firstIndex(items, frame, { last }, (item, index) =>
41
+ apply([item, constant(index)]),
42
+ );
43
+ }
44
+
45
+ /**
46
+ * `find(test)` and `findLast(test)`: the element that passed, or undefined. Among objects setup
47
+ * built the one that passes is chosen now; among values, at run time.
48
+ */
49
+ find(
50
+ items: readonly Value[],
51
+ node: ts.CallExpression,
52
+ frame: Frame,
53
+ { last }: { last: boolean },
54
+ apply: (args: Value[]) => Value,
55
+ ): Value {
56
+ if (
57
+ items.some((item) => item.kind === "static" || item.kind === "function")
58
+ ) {
59
+ return decidedFind(items, node, { last }, apply);
60
+ }
61
+ const { checker, dialect } = this.context;
62
+ const declared = checker.getTypeAtLocation(node);
63
+ const element = checker.getNonNullableType(declared);
64
+ const found = frame.emitter.temporary();
65
+ const result = frame.emitter.temporary();
66
+ frame.emitter.line(`let ${found}: boolean = false;`);
67
+ frame.emitter.line(
68
+ mapped`let ${result}: ${this.expressions.localType(declared)} = ${dialect.assignmentText(constant(undefined), declared, undefined)};`,
69
+ );
70
+ for (const [index, item] of ordered(items, { last })) {
71
+ frame.emitter.open(`if (!${found}) {`);
72
+ const test = apply([item, constant(index)]);
73
+ if (test.kind !== "const" || test.value) {
74
+ const passed =
75
+ test.kind === "const" ? "true" : dialect.condition(test, node);
76
+ frame.emitter.open(mapped`if (${passed}) {`);
77
+ frame.emitter.line(
78
+ mapped`${result} = ${dialect.wrapDefined(dialect.code(item, element), declared)};`,
79
+ );
80
+ frame.emitter.line(`${found} = true;`);
81
+ frame.emitter.close();
82
+ }
83
+ frame.emitter.close();
84
+ }
85
+ return { kind: "code", text: result, declared, place: true };
86
+ }
87
+
88
+ /** `fill(value, start?, end?)` stores the value in each element in range and is worth the array. */
89
+ fill(
90
+ receiver: Value,
91
+ items: readonly Value[],
92
+ node: ts.CallExpression,
93
+ frame: Frame,
94
+ ): Value {
95
+ const [valueNode, startNode, endNode] = node.arguments;
96
+ if (!valueNode) {
97
+ throw new SpecializeError(node, "fill needs a value.");
98
+ }
99
+ const value = this.expressions.held(
100
+ this.expressions.expression(valueNode, frame),
101
+ frame,
102
+ );
103
+ const [start, end] = [startNode, endNode].map((bound) =>
104
+ bound ? this.constantIndex(bound, items.length, frame) : undefined,
105
+ );
106
+ for (const item of items.slice(start ?? 0, end ?? items.length)) {
107
+ this.expressions.assignments.storeValue(item, value, node, frame);
108
+ }
109
+ return receiver;
110
+ }
111
+
112
+ /** `at(index)` with an index setup fixed, counting back from the end when negative. */
113
+ at(items: readonly Value[], node: ts.CallExpression, frame: Frame): Value {
114
+ const [indexNode] = node.arguments;
115
+ if (!indexNode) {
116
+ throw new SpecializeError(node, "at needs an index.");
117
+ }
118
+ const index = this.constantIndex(indexNode, items.length, frame);
119
+ return items[index] ?? constant(undefined);
120
+ }
121
+
122
+ /** The index of the first element whose test passes, or -1; tests stop once one has. */
123
+ private firstIndex(
124
+ items: readonly Value[],
125
+ frame: Frame,
126
+ { last }: { last: boolean },
127
+ test: (item: Value, index: number) => Value,
128
+ ): Value {
129
+ const result = frame.emitter.temporary();
130
+ frame.emitter.line(`let ${result}: number = -1;`);
131
+ for (const [index, item] of ordered(items, { last })) {
132
+ frame.emitter.open(`if (${result} === -1) {`);
133
+ const passed = test(item, index);
134
+ if (passed.kind === "const") {
135
+ if (passed.value) {
136
+ frame.emitter.line(`${result} = ${index};`);
137
+ }
138
+ } else {
139
+ frame.emitter.line(
140
+ mapped`if (${this.context.dialect.condition(passed, frame.emitter.origin)}) { ${result} = ${index}; }`,
141
+ );
142
+ }
143
+ frame.emitter.close();
144
+ }
145
+ return {
146
+ kind: "code",
147
+ text: result,
148
+ declared: this.context.checker.getNumberType(),
149
+ place: true,
150
+ };
151
+ }
152
+
153
+ private constantIndex(
154
+ node: ts.Expression,
155
+ length: number,
156
+ frame: Frame,
157
+ ): number {
158
+ const value = this.expressions.expression(node, frame);
159
+ if (value.kind !== "const" || typeof value.value !== "number") {
160
+ throw new SpecializeError(
161
+ node,
162
+ "Index with a value setup fixed; the element is chosen when the program compiles.",
163
+ );
164
+ }
165
+ return value.value < 0 ? length + value.value : value.value;
166
+ }
167
+ }
168
+
169
+ /** Elements with their indexes, first to last or, for a search from the end, last to first. */
170
+ export const ordered = <T>(
171
+ items: readonly T[],
172
+ { last }: { last: boolean },
173
+ ): [number, T][] => {
174
+ const indexed = [...items.entries()];
175
+ return last ? indexed.reverse() : indexed;
176
+ };
177
+
178
+ /** An array method's callback: its first argument, the test or step it runs on elements. */
179
+ export const callbackArgument = (
180
+ node: ts.CallExpression,
181
+ frame: Frame,
182
+ expressions: Pick<ExpressionSpecializer, "expression">,
183
+ ): Value => {
184
+ const [argument] = node.arguments;
185
+ if (!argument) {
186
+ throw new SpecializeError(node, "Pass a callback.");
187
+ }
188
+ return expressions.expression(argument, frame);
189
+ };
190
+
191
+ /** What `includes` and `indexOf` look for, held so each element is compared with the value it had at the call. */
192
+ export const searchTarget = (
193
+ node: ts.CallExpression,
194
+ frame: Frame,
195
+ expressions: Pick<ExpressionSpecializer, "expression" | "held">,
196
+ ): Value => {
197
+ const [argument] = node.arguments;
198
+ if (!argument) {
199
+ throw new SpecializeError(node, "Pass the value to look for.");
200
+ }
201
+ return expressions.held(expressions.expression(argument, frame), frame);
202
+ };
203
+
204
+ /** `find` and `findLast` among objects setup built, whose tests are known now: the object that passes, or undefined. */
205
+ const decidedFind = (
206
+ items: readonly Value[],
207
+ node: ts.CallExpression,
208
+ { last }: { last: boolean },
209
+ apply: (args: Value[]) => Value,
210
+ ): Value => {
211
+ for (const [index, item] of ordered(items, { last })) {
212
+ const test = apply([item, constant(index)]);
213
+ if (test.kind !== "const") {
214
+ throw new SpecializeError(
215
+ node,
216
+ "find picks one of the objects setup built, which scan code can't hold; use findIndex and index the array.",
217
+ );
218
+ }
219
+ if (test.value) {
220
+ return item;
221
+ }
222
+ }
223
+ return constant(undefined);
224
+ };
@@ -0,0 +1,343 @@
1
+ import ts from "typescript";
2
+ import { type Mapped, mapped, type Part } from "../positions";
3
+ import type { DialectText } from "./dialect";
4
+ import type { ExpressionSpecializer, SpecializeContext } from "./expressions";
5
+ import type { Frame } from "./frame";
6
+ import { constant, SpecializeError, type Value } from "./values";
7
+ import { isAssignment, isUpdate, occursOutsideFunctions } from "./writes";
8
+
9
+ /** The operator each compound assignment applies. */
10
+ const compoundOperators = new Map<ts.SyntaxKind, string>([
11
+ [ts.SyntaxKind.PlusEqualsToken, "+"],
12
+ [ts.SyntaxKind.MinusEqualsToken, "-"],
13
+ [ts.SyntaxKind.AsteriskEqualsToken, "*"],
14
+ [ts.SyntaxKind.BarEqualsToken, "|"],
15
+ [ts.SyntaxKind.AmpersandEqualsToken, "&"],
16
+ ]);
17
+
18
+ /** Whether evaluating the expression writes a place: an assignment or `++`/`--` in it, outside functions it declares. */
19
+ export const containsWrite = (node: ts.Node): boolean =>
20
+ occursOutsideFunctions(
21
+ node,
22
+ (inner) =>
23
+ (ts.isBinaryExpression(inner) &&
24
+ isAssignment(inner.operatorToken.kind)) ||
25
+ isUpdate(inner),
26
+ );
27
+
28
+ /** A statement storing `value` into `place`. */
29
+ export const storeStatement = (place: Part, value: Part): Mapped =>
30
+ mapped`${place} = ${value};`;
31
+
32
+ /**
33
+ * Assignments and steps. Structured Text assigns only in statements, so one used as a value is a
34
+ * statement first, and the expression reads the place afterwards.
35
+ */
36
+ export class AssignmentSpecializer {
37
+ constructor(
38
+ private readonly context: SpecializeContext,
39
+ private readonly expressions: ExpressionSpecializer,
40
+ ) {}
41
+
42
+ private get checker(): ts.TypeChecker {
43
+ return this.context.checker;
44
+ }
45
+
46
+ private get dialect(): DialectText {
47
+ return this.context.dialect;
48
+ }
49
+
50
+ /** Stores the assignment and returns what the target then holds. */
51
+ assign(node: ts.BinaryExpression, frame: Frame): Value {
52
+ if (
53
+ ts.isArrayLiteralExpression(node.left) ||
54
+ ts.isObjectLiteralExpression(node.left)
55
+ ) {
56
+ const value = this.expressions.expression(node.right, frame);
57
+ this.destructure(node.left, value, frame);
58
+ return value;
59
+ }
60
+ const target = this.expressions.references.target(node.left, frame);
61
+ if (target.kind === "each") {
62
+ this.expressions.references.each(target.choice, frame, (option) => {
63
+ this.assignTo(target.place(option), node, frame);
64
+ });
65
+ return constant(undefined);
66
+ }
67
+ return this.assignTo(target, node, frame);
68
+ }
69
+
70
+ private assignTo(
71
+ target: Value,
72
+ node: ts.BinaryExpression,
73
+ frame: Frame,
74
+ ): Value {
75
+ if (target.kind === "choice") {
76
+ return this.expressions.references.assign(target, node, frame);
77
+ }
78
+ const text = this.placeText(target, node.left);
79
+ const declared = target.kind === "code" ? target.declared : undefined;
80
+ const operator = node.operatorToken.kind;
81
+ if (operator === ts.SyntaxKind.QuestionQuestionEqualsToken) {
82
+ const value = this.expressions.expression(
83
+ node.right,
84
+ frame,
85
+ declared && this.checker.getNonNullableType(declared),
86
+ );
87
+ frame.emitter.open(
88
+ mapped`if (${this.dialect.isUndefinedText(text, declared)}) {`,
89
+ );
90
+ frame.emitter.line(
91
+ this.store(
92
+ target,
93
+ this.dialect.wrapDefined(
94
+ this.dialect.code(
95
+ value,
96
+ declared && this.checker.getNonNullableType(declared),
97
+ ),
98
+ declared,
99
+ ),
100
+ ),
101
+ );
102
+ frame.emitter.close();
103
+ return target;
104
+ }
105
+ const value = this.expressions.expression(node.right, frame, declared);
106
+ if (operator === ts.SyntaxKind.EqualsToken) {
107
+ frame.emitter.line(this.stored(target, value));
108
+ return target;
109
+ }
110
+ const binary = compoundOperators.get(operator);
111
+ if (!binary) {
112
+ throw new SpecializeError(
113
+ node,
114
+ `${node.operatorToken.getText()} is not supported.`,
115
+ );
116
+ }
117
+ frame.emitter.line(
118
+ this.store(
119
+ target,
120
+ mapped`${text} ${binary} ${this.dialect.code(value, declared)}`,
121
+ ),
122
+ );
123
+ return target;
124
+ }
125
+
126
+ /** Steps the place by one; `x++` is worth what the place held before, `++x` what it holds after. */
127
+ step(
128
+ node: ts.PrefixUnaryExpression | ts.PostfixUnaryExpression,
129
+ frame: Frame,
130
+ { used }: { used: boolean },
131
+ ): Value {
132
+ const target = this.expressions.references.target(node.operand, frame);
133
+ if (target.kind === "each") {
134
+ this.expressions.references.each(target.choice, frame, (option) => {
135
+ this.stepOn(target.place(option), node, frame, { used: false });
136
+ });
137
+ return constant(undefined);
138
+ }
139
+ return this.stepOn(target, node, frame, { used });
140
+ }
141
+
142
+ private stepOn(
143
+ target: Value,
144
+ node: ts.PrefixUnaryExpression | ts.PostfixUnaryExpression,
145
+ frame: Frame,
146
+ { used }: { used: boolean },
147
+ ): Value {
148
+ const text = this.placeText(target, node.operand);
149
+ const before =
150
+ used && ts.isPostfixUnaryExpression(node)
151
+ ? this.expressions.held(target, frame)
152
+ : target;
153
+ frame.emitter.line(
154
+ this.store(
155
+ target,
156
+ mapped`${text} ${node.operator === ts.SyntaxKind.PlusPlusToken ? "+" : "-"} 1`,
157
+ ),
158
+ );
159
+ return before;
160
+ }
161
+
162
+ /**
163
+ * Assigns each target of a pattern its part of `value`. Every part is read before any target is
164
+ * written, so `[a, b] = [b, a]` swaps.
165
+ */
166
+ private destructure(
167
+ pattern: ts.ArrayLiteralExpression | ts.ObjectLiteralExpression,
168
+ value: Value,
169
+ frame: Frame,
170
+ ): void {
171
+ const writes: (() => void)[] = [];
172
+ this.collect(pattern, value, frame, writes);
173
+ for (const write of writes) {
174
+ write();
175
+ }
176
+ }
177
+
178
+ private collect(
179
+ pattern: ts.Expression,
180
+ value: Value,
181
+ frame: Frame,
182
+ writes: (() => void)[],
183
+ ): void {
184
+ if (ts.isArrayLiteralExpression(pattern)) {
185
+ pattern.elements.forEach((element, index) => {
186
+ if (ts.isOmittedExpression(element)) {
187
+ return;
188
+ }
189
+ if (ts.isSpreadElement(element)) {
190
+ throw new SpecializeError(
191
+ element,
192
+ "Assign the rest of an array element by element.",
193
+ );
194
+ }
195
+ this.collectTarget(
196
+ element,
197
+ this.expressions.element(value, constant(index), element, frame),
198
+ frame,
199
+ writes,
200
+ );
201
+ });
202
+ return;
203
+ }
204
+ if (ts.isObjectLiteralExpression(pattern)) {
205
+ for (const property of pattern.properties) {
206
+ if (ts.isShorthandPropertyAssignment(property)) {
207
+ const part = this.expressions.member(
208
+ value,
209
+ property.name.text,
210
+ property,
211
+ frame,
212
+ );
213
+ this.collectTarget(
214
+ property.name,
215
+ this.expressions.defaulted(
216
+ part,
217
+ property.objectAssignmentInitializer,
218
+ frame,
219
+ ),
220
+ frame,
221
+ writes,
222
+ );
223
+ continue;
224
+ }
225
+ if (!ts.isPropertyAssignment(property)) {
226
+ throw new SpecializeError(
227
+ property,
228
+ "Assign each field of a pattern by name.",
229
+ );
230
+ }
231
+ this.collectTarget(
232
+ property.initializer,
233
+ this.expressions.member(
234
+ value,
235
+ property.name.getText(),
236
+ property,
237
+ frame,
238
+ ),
239
+ frame,
240
+ writes,
241
+ );
242
+ }
243
+ return;
244
+ }
245
+ throw new SpecializeError(pattern, "Not a pattern.");
246
+ }
247
+
248
+ /** One target of a pattern, with the default it takes when its part is undefined. */
249
+ private collectTarget(
250
+ target: ts.Expression,
251
+ part: Value,
252
+ frame: Frame,
253
+ writes: (() => void)[],
254
+ ): void {
255
+ if (
256
+ ts.isBinaryExpression(target) &&
257
+ target.operatorToken.kind === ts.SyntaxKind.EqualsToken
258
+ ) {
259
+ this.collectTarget(
260
+ target.left,
261
+ this.expressions.defaulted(part, target.right, frame),
262
+ frame,
263
+ writes,
264
+ );
265
+ return;
266
+ }
267
+ if (
268
+ ts.isArrayLiteralExpression(target) ||
269
+ ts.isObjectLiteralExpression(target)
270
+ ) {
271
+ this.collect(target, part, frame, writes);
272
+ return;
273
+ }
274
+ const read = this.expressions.held(part, frame);
275
+ writes.push(() => {
276
+ this.storeValue(
277
+ this.expressions.expression(target, frame),
278
+ read,
279
+ target,
280
+ frame,
281
+ );
282
+ });
283
+ }
284
+
285
+ /** Stores a value into a place, converting it as an IEC assignment does. */
286
+ storeValue(place: Value, value: Value, at: ts.Node, frame: Frame): void {
287
+ this.placeText(place, at);
288
+ frame.emitter.line(this.stored(place, value));
289
+ }
290
+
291
+ /** A statement storing a value into a place, converted as an IEC assignment does. */
292
+ private stored(place: Value, value: Value): Mapped {
293
+ return this.store(
294
+ place,
295
+ this.dialect.assignmentText(
296
+ value,
297
+ place.kind === "code" ? place.declared : undefined,
298
+ place.kind === "code" ? place.iec : undefined,
299
+ ),
300
+ );
301
+ }
302
+
303
+ /** A statement storing `text` into a place. */
304
+ private store(target: Value, text: Part): Mapped {
305
+ if (target.kind !== "code") {
306
+ throw new Error("Not a place.");
307
+ }
308
+ return storeStatement(target.text, text);
309
+ }
310
+
311
+ private placeText(value: Value, node: ts.Node): string | Mapped {
312
+ if (value.kind === "code" && value.copyOf) {
313
+ throw new SpecializeError(
314
+ node,
315
+ `This changes a copy: ${value.copyOf} returns stored state, which TypeScript would change in place but the PLC copies. Change it where it is stored, as a collection's update does.`,
316
+ );
317
+ }
318
+ if (value.kind === "code" && value.input) {
319
+ throw new SpecializeError(
320
+ node,
321
+ `${value.input.path} is bound to ${value.input.address}, and the hardware overwrites it every scan: keep what scan code computes in a field of its own.`,
322
+ );
323
+ }
324
+ if (value.kind === "code" && value.place) {
325
+ return value.text;
326
+ }
327
+ if (
328
+ value.kind === "function" ||
329
+ (value.kind === "static" &&
330
+ (value.node.captured.kind === "closure" ||
331
+ value.node.captured.kind === "function"))
332
+ ) {
333
+ throw new SpecializeError(
334
+ node,
335
+ "This assigns a function, and the PLC calls only functions known when the program compiles: keep one function, and choose what it does with an if.",
336
+ );
337
+ }
338
+ throw new SpecializeError(
339
+ node,
340
+ "Assign to stored state: a field scan code owns, or a let.",
341
+ );
342
+ }
343
+ }