@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,2177 @@
1
+ import {
2
+ constantFits,
3
+ identityDigest,
4
+ integerType,
5
+ literalOutsideType,
6
+ optionalRecord,
7
+ primitiveTypes,
8
+ } from "@tsplc/compiler/ir";
9
+ import ts from "typescript";
10
+ import { from, joined, type Mapped, mapped, type Part } from "../positions";
11
+ import { sdkModules, unaliased, valueSymbol } from "../sdk";
12
+ import { defaultNumericTypes } from "../types";
13
+ import { AssignmentSpecializer, containsWrite } from "./assignments";
14
+ import { CallSpecializer, floatIec } from "./calls";
15
+ import {
16
+ isGlobal,
17
+ namedElements,
18
+ namedFields,
19
+ parameterDefault,
20
+ symbolOf,
21
+ } from "./declarations";
22
+ import type { DialectText } from "./dialect";
23
+ import { FilteredArrays } from "./filtered-arrays";
24
+ import type { Emitter, Frame } from "./frame";
25
+ import type { EntryImports } from "./imports";
26
+ import type { Initializers } from "./initializers";
27
+ import { Iterators } from "./iterators";
28
+ import {
29
+ type ArrayLayout,
30
+ arrayLayout,
31
+ isAbsent,
32
+ type Layouts,
33
+ optionalValue,
34
+ recordTypes,
35
+ } from "./layouts";
36
+ import type { Model, ModelNode } from "./model";
37
+ import { References, referenceType } from "./references";
38
+ import type { Storage } from "./storage";
39
+ import {
40
+ capturedPrimitive,
41
+ constant,
42
+ type Env,
43
+ type FunctionLike,
44
+ finite,
45
+ holdsSetupObjects,
46
+ repeatable,
47
+ restoring,
48
+ SpecializeError,
49
+ unwrapped,
50
+ type Value,
51
+ } from "./values";
52
+ import {
53
+ isAssignment,
54
+ isUpdate,
55
+ replacedWhileAliased,
56
+ stableAlias,
57
+ writesThrough,
58
+ } from "./writes";
59
+
60
+ /** What every part of scan-code specialization shares. */
61
+ export interface SpecializeContext {
62
+ model: Model;
63
+ checker: ts.TypeChecker;
64
+ layouts: Layouts;
65
+ storage: Storage;
66
+ initializers: Initializers;
67
+ imports: EntryImports;
68
+ dialect: DialectText;
69
+ /** The SDK's globals declaration; its other declarations sit beside it. */
70
+ sdkFile: string;
71
+ /** The program's runtime sources, where the functions setup stored are declared. */
72
+ sources: readonly ts.SourceFile[];
73
+ /** Whether the compiled program keeps `file` as written instead of compiling it from setup. */
74
+ isKept: (file: string) => boolean;
75
+ }
76
+
77
+ /** A call to a specialized routine: its name, the runtime arguments it takes and its result type. */
78
+ export interface RoutineCall {
79
+ name: string;
80
+ args: (string | Mapped)[];
81
+ returns: ts.Type | undefined;
82
+ /** The IEC width the routine's declaration gives its result, as `(): UINT` does. */
83
+ iec?: string;
84
+ /** An array result's layout, at the length the routine returns. */
85
+ layout?: ArrayLayout;
86
+ length?: number;
87
+ /** Whether the routine returns stored state, which its caller gets a copy of. */
88
+ returnsStored?: boolean;
89
+ /** For a result that is a reference: the objects it can be, and whether it can be undefined. */
90
+ referents?: { options: readonly ModelNode[]; optional: boolean };
91
+ }
92
+
93
+ /** Specializes a called function for its receiver and known arguments. */
94
+ export interface RoutineTable {
95
+ routine(
96
+ declaration: FunctionLike,
97
+ self: ModelNode | undefined,
98
+ args: Value[],
99
+ closure?: Closure,
100
+ ): RoutineCall;
101
+ /** Runs `run`, then forgets the routines it specialized. */
102
+ speculatively<T>(run: () => T): T;
103
+ /** The routine that cancels the pending async calls of an instance's methods. */
104
+ canceller(self: ModelNode): string;
105
+ }
106
+
107
+ /** What a local function captured, and the routine calling it, whose locals those values can read. */
108
+ export interface Closure {
109
+ env: Env;
110
+ caller: Emitter;
111
+ }
112
+
113
+ type Code = Extract<Value, { kind: "code" }>;
114
+
115
+ /** How a runtime value's PLC type is read where it is held or passed on. */
116
+ export interface Typing {
117
+ /** Whether an IEC width the value carries types it, and stays with what holds it. */
118
+ width: boolean;
119
+ /** Whether a literal type widens to its base type, as a local's does. */
120
+ widen: boolean;
121
+ /** The type of a value with no declared type. */
122
+ untyped: "number" | "boolean";
123
+ }
124
+
125
+ /** How `hold` keeps a runtime value in a const. */
126
+ export interface Holding extends Typing {
127
+ /** Whether a place or literal, which reads the same however often it is repeated, is held too. */
128
+ repeatable: boolean;
129
+ }
130
+
131
+ /** Evaluates expressions against the setup graph, and writes what remains as dialect text. */
132
+ export class ExpressionSpecializer {
133
+ private readonly calls: CallSpecializer;
134
+ readonly assignments: AssignmentSpecializer;
135
+ readonly references: References;
136
+ readonly filteredArrays: FilteredArrays;
137
+ readonly iterators: Iterators;
138
+ private readonly services = new Map<string, ModelNode>();
139
+ private readonly tables = new Map<number, string>();
140
+ readonly tableDeclarations: Mapped[] = [];
141
+
142
+ constructor(
143
+ private readonly context: SpecializeContext,
144
+ private readonly routineTable: RoutineTable,
145
+ ) {
146
+ this.calls = new CallSpecializer(context, this);
147
+ this.assignments = new AssignmentSpecializer(context, this);
148
+ this.references = new References(context, this);
149
+ this.filteredArrays = new FilteredArrays(context, this);
150
+ this.iterators = new Iterators(context, this);
151
+ }
152
+
153
+ expression(node: ts.Expression, frame: Frame, expected?: ts.Type): Value {
154
+ const value = this.evaluate(node, frame, expected);
155
+ if (value.kind !== "code") {
156
+ return value;
157
+ }
158
+ // A name maps to where it is read, not to where its value came from.
159
+ return {
160
+ ...value,
161
+ text: from(node, ts.isIdentifier(node) ? String(value.text) : value.text),
162
+ };
163
+ }
164
+
165
+ private evaluate(
166
+ node: ts.Expression,
167
+ frame: Frame,
168
+ expected?: ts.Type,
169
+ ): Value {
170
+ // `x!` reads an optional's value, as `x` reads where TypeScript narrowed undefined out.
171
+ if (ts.isNonNullExpression(node)) {
172
+ return this.narrowed(
173
+ this.expression(node.expression, frame, expected),
174
+ node,
175
+ );
176
+ }
177
+ const inner = unwrapped(node);
178
+ if (inner !== node) {
179
+ return this.expression(inner, frame, expected);
180
+ }
181
+ if (ts.isNumericLiteral(node)) {
182
+ return constant(Number(node.text));
183
+ }
184
+ if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) {
185
+ return constant(node.text);
186
+ }
187
+ if (node.kind === ts.SyntaxKind.TrueKeyword) {
188
+ return constant(true);
189
+ }
190
+ if (node.kind === ts.SyntaxKind.FalseKeyword) {
191
+ return constant(false);
192
+ }
193
+ // null is the PLC's one empty value, as undefined is.
194
+ if (node.kind === ts.SyntaxKind.NullKeyword) {
195
+ return constant(undefined);
196
+ }
197
+ if (ts.isBigIntLiteral(node)) {
198
+ return constant(BigInt(node.text.slice(0, -1)));
199
+ }
200
+ if (node.kind === ts.SyntaxKind.ThisKeyword) {
201
+ if (!frame.self) {
202
+ throw new SpecializeError(node, "`this` outside a method.");
203
+ }
204
+ return { kind: "static", node: frame.self };
205
+ }
206
+ if (ts.isIdentifier(node)) {
207
+ return this.identifier(node, frame);
208
+ }
209
+ if (ts.isPropertyAccessExpression(node)) {
210
+ const member = this.context.checker.getSymbolAtLocation(
211
+ node.name,
212
+ )?.valueDeclaration;
213
+ if (member && ts.isEnumMember(member)) {
214
+ return constant(this.context.checker.getConstantValue(member));
215
+ }
216
+ if (node.expression.kind === ts.SyntaxKind.SuperKeyword) {
217
+ return this.superMember(node, frame);
218
+ }
219
+ const mathConstant = mathConstants.get(node.name.text);
220
+ if (
221
+ mathConstant !== undefined &&
222
+ isGlobal(this.context.checker, node.expression, "Math")
223
+ ) {
224
+ return constant(mathConstant);
225
+ }
226
+ if (
227
+ node.name.text === "length" &&
228
+ this.filteredArrays.isFilter(node.expression)
229
+ ) {
230
+ return this.filteredArrays.count(node.expression, frame);
231
+ }
232
+ return this.property(
233
+ this.expression(node.expression, frame),
234
+ node,
235
+ frame,
236
+ );
237
+ }
238
+ if (ts.isElementAccessExpression(node)) {
239
+ const object = this.expression(node.expression, frame);
240
+ const index = this.expression(node.argumentExpression, frame);
241
+ return this.element(object, index, node, frame);
242
+ }
243
+ if (ts.isCallExpression(node)) {
244
+ return this.calls.call(node, frame, expected);
245
+ }
246
+ if (ts.isAwaitExpression(node)) {
247
+ const value = this.expression(node.expression, frame);
248
+ // A `.then` or `.catch` link awaited its promise itself, and gives the value.
249
+ if (isPromiseLink(unwrapped(node.expression)) || value.kind !== "code") {
250
+ return value;
251
+ }
252
+ return {
253
+ kind: "code",
254
+ text: mapped`await ${this.context.dialect.code(value, undefined)}`,
255
+ declared: this.context.checker.getTypeAtLocation(node),
256
+ iec: value.kind === "code" ? value.iec : undefined,
257
+ awaited: true,
258
+ };
259
+ }
260
+ if (isUpdate(node)) {
261
+ return this.assignments.step(node, frame, { used: true });
262
+ }
263
+ if (ts.isTypeOfExpression(node)) {
264
+ return this.typeOf(this.expression(node.expression, frame));
265
+ }
266
+ if (ts.isPrefixUnaryExpression(node)) {
267
+ return this.unary(node, frame);
268
+ }
269
+ if (ts.isBinaryExpression(node)) {
270
+ return this.binary(node, frame, expected);
271
+ }
272
+ if (ts.isConditionalExpression(node)) {
273
+ const condition = this.expression(node.condition, frame);
274
+ if (condition.kind === "const") {
275
+ return this.expression(
276
+ condition.value ? node.whenTrue : node.whenFalse,
277
+ frame,
278
+ expected,
279
+ );
280
+ }
281
+ const own = this.context.checker.getTypeAtLocation(node);
282
+ if (referenceType(own)) {
283
+ return this.references.branch(
284
+ this.context.dialect.condition(condition, node.condition),
285
+ [
286
+ () => this.expression(node.whenTrue, frame),
287
+ () => this.expression(node.whenFalse, frame),
288
+ ],
289
+ node,
290
+ frame,
291
+ );
292
+ }
293
+ // A choice between defined values stored into an optional is wrapped where it is stored.
294
+ const declared =
295
+ expected &&
296
+ !(
297
+ this.context.layouts.isOptionalRecord(expected) &&
298
+ !this.context.layouts.isOptionalRecord(own)
299
+ )
300
+ ? expected
301
+ : own;
302
+ if (
303
+ this.isAggregate(declared) ||
304
+ this.runsWhenNeeded(node.whenTrue, frame) ||
305
+ this.runsWhenNeeded(node.whenFalse, frame)
306
+ ) {
307
+ return this.branched(
308
+ declared,
309
+ this.context.dialect.condition(condition, node.condition),
310
+ [node.whenTrue, node.whenFalse],
311
+ frame,
312
+ );
313
+ }
314
+ const whenTrue = this.expression(node.whenTrue, frame, declared);
315
+ const whenFalse = this.expression(node.whenFalse, frame, declared);
316
+ return {
317
+ kind: "code",
318
+ text: mapped`(${this.context.dialect.condition(condition, node.condition)} ? ${this.context.dialect.assignmentText(whenTrue, declared, undefined)} : ${this.context.dialect.assignmentText(whenFalse, declared, undefined)})`,
319
+ declared,
320
+ copyOf: [whenTrue, whenFalse].find(
321
+ (branch): branch is Value & { kind: "code" } =>
322
+ branch.kind === "code" && branch.copyOf !== undefined,
323
+ )?.copyOf,
324
+ };
325
+ }
326
+ if (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) {
327
+ return {
328
+ kind: "function",
329
+ declaration: node,
330
+ self: frame.self,
331
+ env: frame.env,
332
+ };
333
+ }
334
+ if (ts.isObjectLiteralExpression(node)) {
335
+ return this.objectLiteral(node, frame);
336
+ }
337
+ if (ts.isArrayLiteralExpression(node)) {
338
+ const items: Value[] = [];
339
+ for (const element of node.elements) {
340
+ if (ts.isSpreadElement(element)) {
341
+ const spread = this.items(this.expression(element.expression, frame));
342
+ if (!spread) {
343
+ throw new SpecializeError(element, "Spread an array setup built.");
344
+ }
345
+ items.push(...spread);
346
+ } else {
347
+ items.push(this.expression(element, frame));
348
+ }
349
+ }
350
+ return { kind: "virtual", items };
351
+ }
352
+ if (ts.isTemplateExpression(node)) {
353
+ throw new SpecializeError(
354
+ node,
355
+ "Template strings are not supported in scan code.",
356
+ );
357
+ }
358
+ throw new SpecializeError(
359
+ node,
360
+ `${ts.SyntaxKind[node.kind]} is not supported in scan code.`,
361
+ );
362
+ }
363
+
364
+ /** `object.name` once the object is known: its member, through `?.` and what TypeScript narrowed. */
365
+ property(
366
+ object: Value,
367
+ node: ts.PropertyAccessExpression,
368
+ frame: Frame,
369
+ ): Value {
370
+ if (
371
+ node.questionDotToken &&
372
+ object.kind === "const" &&
373
+ object.value === undefined
374
+ ) {
375
+ return constant(undefined);
376
+ }
377
+ if (
378
+ node.questionDotToken &&
379
+ object.kind === "code" &&
380
+ object.declared &&
381
+ this.context.layouts.isOptionalRecord(object.declared)
382
+ ) {
383
+ return this.optionalMember(object, object.declared, node, frame);
384
+ }
385
+ if (node.questionDotToken && object.kind === "choice" && object.optional) {
386
+ return this.chained(
387
+ object,
388
+ () => this.member(object, node.name.text, node, frame),
389
+ node,
390
+ frame,
391
+ );
392
+ }
393
+ if (
394
+ node.questionDotToken &&
395
+ object.kind === "code" &&
396
+ object.declared &&
397
+ this.context.checker.getNonNullableType(object.declared) !==
398
+ object.declared
399
+ ) {
400
+ throw new SpecializeError(
401
+ node,
402
+ "?. reads only an optional record or object here: test this value with !== undefined first, and read it inside the if.",
403
+ );
404
+ }
405
+ return this.narrowed(
406
+ this.member(object, node.name.text, node, frame),
407
+ node,
408
+ );
409
+ }
410
+
411
+ private identifier(node: ts.Identifier, frame: Frame): Value {
412
+ if (node.text === "undefined") {
413
+ return constant(undefined);
414
+ }
415
+ const symbol = symbolOf(this.context.checker, node);
416
+ const local = frame.env.get(symbol);
417
+ if (local) {
418
+ return this.narrowed(local, node);
419
+ }
420
+ const target = unaliased(this.context.checker, symbol);
421
+ const own = frame.env.get(target);
422
+ if (own) {
423
+ return own;
424
+ }
425
+ const declaration = target.valueDeclaration ?? target.declarations?.[0];
426
+ if (!declaration) {
427
+ throw new SpecializeError(node, `${node.text} has no declaration.`);
428
+ }
429
+ if (ts.isFunctionDeclaration(declaration)) {
430
+ return { kind: "function", declaration };
431
+ }
432
+ const initializer =
433
+ ts.isVariableDeclaration(declaration) && declaration.initializer;
434
+ if (
435
+ initializer &&
436
+ (ts.isArrowFunction(initializer) || ts.isFunctionExpression(initializer))
437
+ ) {
438
+ return { kind: "function", declaration: initializer };
439
+ }
440
+ // A module constant named by a destructuring declaration is a root of its own too.
441
+ const root = this.context.model.roots.find(
442
+ (item) => item.declaration === declaration,
443
+ );
444
+ if (root) {
445
+ const value = this.context.storage.rootValue(root);
446
+ this.refuseOutsideWidth(
447
+ value,
448
+ this.context.layouts.iecName(root.declaration),
449
+ root.declaration,
450
+ );
451
+ return value;
452
+ }
453
+ if (
454
+ initializer &&
455
+ ts.isVariableStatement(declaration.parent.parent) &&
456
+ declaration.parent.parent.parent &&
457
+ ts.isSourceFile(declaration.parent.parent.parent)
458
+ ) {
459
+ return this.expression(initializer, { ...frame, env: new Map() });
460
+ }
461
+ if (ts.isEnumMember(declaration)) {
462
+ return constant(this.context.checker.getConstantValue(declaration));
463
+ }
464
+ if (ts.isParameter(declaration)) {
465
+ throw new SpecializeError(
466
+ node,
467
+ `${node.text} is a parameter of a scan function, which its task calls with no arguments: read the value from the program's state instead.`,
468
+ );
469
+ }
470
+ throw new SpecializeError(
471
+ node,
472
+ `${node.text} is not available in scan code.`,
473
+ );
474
+ }
475
+
476
+ member(object: Value, name: string, at: ts.Node, frame: Frame): Value {
477
+ if (object.kind === "counted") {
478
+ return this.iterators.member(object, name, at);
479
+ }
480
+ if (object.kind === "choice") {
481
+ return this.references.member(object, name, at, frame);
482
+ }
483
+ if (object.kind === "masked") {
484
+ return this.filteredArrays.member(object, name, at, frame);
485
+ }
486
+ if (object.kind === "static") {
487
+ const node = object.node;
488
+ const captured = node.captured;
489
+ if (captured.kind === "service") {
490
+ return {
491
+ kind: "static",
492
+ node: this.serviceNode(
493
+ captured.path ? `${captured.path}.${name}` : name,
494
+ ),
495
+ };
496
+ }
497
+ if (captured.kind === "instance") {
498
+ const members = this.context.model.members(
499
+ this.context.model.classOf(node),
500
+ );
501
+ const accessor = getterNamed(members, name);
502
+ if (accessor) {
503
+ // A getter that only returns an expression reads it in place, as a field is read, so one
504
+ // naming an object setup built is that object rather than a routine's copy of it.
505
+ const returned = onlyReturned(accessor);
506
+ if (returned) {
507
+ return this.expression(returned, {
508
+ ...frame,
509
+ env: new Map(),
510
+ self: node,
511
+ returns: undefined,
512
+ generator: undefined,
513
+ });
514
+ }
515
+ return this.invoke(
516
+ { kind: "function", declaration: accessor, self: node },
517
+ [],
518
+ at,
519
+ frame,
520
+ );
521
+ }
522
+ const method = methodNamed(members, name);
523
+ if (method) {
524
+ return { kind: "function", declaration: method, self: node };
525
+ }
526
+ }
527
+ if (captured.kind === "array" && name === "length") {
528
+ return constant(captured.items.length);
529
+ }
530
+ if (captured.kind === "object" || captured.kind === "instance") {
531
+ const field = captured.fields[name];
532
+ if (!field) {
533
+ if (captured.kind === "object") {
534
+ return constant(undefined);
535
+ }
536
+ throw new SpecializeError(at, `${name} is not set during setup.`);
537
+ }
538
+ return this.references.field(
539
+ this.context.storage.fromCaptured(field, node, {
540
+ kind: "field",
541
+ name,
542
+ }),
543
+ node,
544
+ name,
545
+ );
546
+ }
547
+ throw new SpecializeError(at, `${name} cannot be read from this value.`);
548
+ }
549
+ if (object.kind === "virtual") {
550
+ if (name === "length" && object.items) {
551
+ return constant(object.items.length);
552
+ }
553
+ if (object.fields) {
554
+ return object.fields.get(name) ?? constant(undefined);
555
+ }
556
+ throw new SpecializeError(at, `${name} is not set.`);
557
+ }
558
+ if (object.kind === "code") {
559
+ const declared =
560
+ object.declared && this.fieldDeclared(object.declared, name, at);
561
+ const property =
562
+ object.declared &&
563
+ this.context.checker.getPropertyOfType(
564
+ this.context.checker.getNonNullableType(object.declared),
565
+ name,
566
+ );
567
+ const pinnedObject = object.pinned;
568
+ return {
569
+ kind: "code",
570
+ text: mapped`${object.text}.${name}`,
571
+ declared,
572
+ place: object.place,
573
+ copyOf: object.copyOf,
574
+ ...(pinnedObject && {
575
+ pinned: (pinFrame: Frame) =>
576
+ this.member(pinnedObject(pinFrame), name, at, pinFrame),
577
+ }),
578
+ iec: this.context.layouts.iecName(property?.valueDeclaration),
579
+ elementIec: this.context.layouts.elementIec(property?.valueDeclaration),
580
+ layout:
581
+ property && declared && this.context.checker.isArrayType(declared)
582
+ ? this.context.layouts.fieldArray(property)
583
+ : undefined,
584
+ };
585
+ }
586
+ if (object.kind === "const" && object.value === undefined) {
587
+ throw new SpecializeError(
588
+ at,
589
+ `Reading ${name} of undefined: this is undefined wherever the program runs, as setup leaves it and scan code never assigns it.`,
590
+ );
591
+ }
592
+ throw new SpecializeError(at, `${name} cannot be read from this value.`);
593
+ }
594
+
595
+ /** An optional's value, or a reference known defined, where TypeScript has narrowed out undefined, as `x` reads after `x !== undefined`. */
596
+ private narrowed(value: Value, at: ts.Node): Value {
597
+ if (value.kind === "choice") {
598
+ return value.optional && this.narrowedOut(at)
599
+ ? { ...value, narrowed: true }
600
+ : value;
601
+ }
602
+ if (
603
+ value.kind !== "code" ||
604
+ !value.declared ||
605
+ !this.context.layouts.isOptionalRecord(value.declared) ||
606
+ !this.narrowedOut(at)
607
+ ) {
608
+ return value;
609
+ }
610
+ return {
611
+ kind: "code",
612
+ text: optionalValue(value.text),
613
+ declared: this.context.checker.getNonNullableType(value.declared),
614
+ place: value.place,
615
+ copyOf: value.copyOf,
616
+ };
617
+ }
618
+
619
+ /** Whether TypeScript has narrowed undefined out of what `at` reads. */
620
+ private narrowedOut(at: ts.Node): boolean {
621
+ const type = this.context.checker.getTypeAtLocation(at);
622
+ return !isAbsent(type) && !(type.isUnion() && type.types.some(isAbsent));
623
+ }
624
+
625
+ /** The declared type of a field of a runtime record, through optionals and tagged unions. */
626
+ private fieldDeclared(
627
+ type: ts.Type,
628
+ name: string,
629
+ at: ts.Node,
630
+ ): ts.Type | undefined {
631
+ const defined = this.context.checker.getNonNullableType(type);
632
+ const tagged = this.context.layouts.tagged(defined);
633
+ if (tagged) {
634
+ return name === tagged.tag
635
+ ? this.context.layouts.tagType(defined, tagged)
636
+ : this.context.layouts.taggedFieldType(defined, tagged, name);
637
+ }
638
+ const property = this.context.checker.getPropertyOfType(defined, name);
639
+ if (!property) {
640
+ throw new SpecializeError(
641
+ at,
642
+ `${name} is not a field of ${this.context.checker.typeToString(type)}.`,
643
+ );
644
+ }
645
+ return this.context.checker.getTypeOfSymbol(property);
646
+ }
647
+
648
+ private serviceNode(path: string): ModelNode {
649
+ const known = this.services.get(path);
650
+ if (known) {
651
+ return known;
652
+ }
653
+ const id = -1 - this.services.size;
654
+ // A service is called, never held, so no reference holds its id.
655
+ const node: ModelNode = {
656
+ id,
657
+ reference: id,
658
+ captured: { kind: "service", path },
659
+ };
660
+ this.services.set(path, node);
661
+ return node;
662
+ }
663
+
664
+ element(object: Value, index: Value, at: ts.Node, frame: Frame): Value {
665
+ if (object.kind === "counted") {
666
+ return this.iterators.element(object, index, at, frame);
667
+ }
668
+ if (object.kind === "choice") {
669
+ return this.references.element(object, index, at, frame);
670
+ }
671
+ if (object.kind === "masked") {
672
+ return this.filteredArrays.element(object, index, at, frame);
673
+ }
674
+ if (index.kind === "const" && typeof index.value === "number") {
675
+ if (object.kind === "virtual" && object.items) {
676
+ const item = object.items[index.value];
677
+ if (!item) {
678
+ throw new SpecializeError(
679
+ at,
680
+ `Index ${index.value} is past the end.`,
681
+ );
682
+ }
683
+ return item;
684
+ }
685
+ if (object.kind === "static" && object.node.captured.kind === "array") {
686
+ const item = object.node.captured.items[index.value];
687
+ if (!item) {
688
+ return constant(undefined);
689
+ }
690
+ return this.context.storage.fromCaptured(item, object.node, {
691
+ kind: "index",
692
+ index: index.value,
693
+ });
694
+ }
695
+ if (object.kind === "static" && object.node.captured.kind === "object") {
696
+ const field = object.node.captured.fields[String(index.value)];
697
+ if (!field) {
698
+ return constant(undefined);
699
+ }
700
+ return this.context.storage.fromCaptured(field, object.node, {
701
+ kind: "field",
702
+ name: String(index.value),
703
+ });
704
+ }
705
+ }
706
+ if (object.kind === "static") {
707
+ const node = object.node;
708
+ const declared =
709
+ node.type &&
710
+ (node.captured.kind === "array"
711
+ ? this.context.model.elementType(node.type)
712
+ : recordTypes(node.type)?.value);
713
+ const text = this.context.storage.storedNode(node)
714
+ ? this.context.storage.pathText(node)
715
+ : this.table(node, at);
716
+ return {
717
+ kind: "code",
718
+ text: mapped`${text}[${this.context.dialect.code(index, node.type && recordTypes(node.type)?.key)}]`,
719
+ declared,
720
+ place: true,
721
+ ...(index.kind === "code" && {
722
+ pinned: (pinFrame: Frame) =>
723
+ this.element(object, this.held(index, pinFrame), at, pinFrame),
724
+ }),
725
+ };
726
+ }
727
+ if (object.kind === "code") {
728
+ const declared =
729
+ object.declared &&
730
+ (this.context.model.elementType(object.declared) ??
731
+ recordTypes(object.declared)?.value);
732
+ // A key setup fixed reads as a number; an enum-keyed record takes its enum's member.
733
+ const key = object.declared && recordTypes(object.declared)?.key;
734
+ return {
735
+ kind: "code",
736
+ text: mapped`${object.text}[${this.context.dialect.code(index, key)}]`,
737
+ declared,
738
+ place: object.place,
739
+ iec: object.elementIec,
740
+ copyOf: object.copyOf,
741
+ ...((index.kind === "code" || object.pinned) && {
742
+ pinned: (pinFrame: Frame) =>
743
+ this.element(
744
+ object.pinned ? object.pinned(pinFrame) : object,
745
+ this.held(index, pinFrame),
746
+ at,
747
+ pinFrame,
748
+ ),
749
+ }),
750
+ };
751
+ }
752
+ if (object.kind === "virtual" && object.items) {
753
+ const chosen = this.filteredArrays.indexed(
754
+ object.items,
755
+ index,
756
+ { fromEnd: false },
757
+ at,
758
+ frame,
759
+ );
760
+ if (chosen) {
761
+ return chosen;
762
+ }
763
+ const text = this.materialize(object.items, at, frame);
764
+ return {
765
+ kind: "code",
766
+ text: mapped`${text}[${this.context.dialect.code(index, undefined)}]`,
767
+ declared: this.context.checker.getTypeAtLocation(at),
768
+ };
769
+ }
770
+ throw new SpecializeError(at, "This value cannot be indexed.");
771
+ }
772
+
773
+ /** A fixed table setup built, emitted once, where scan code first indexes it at runtime. */
774
+ private table(node: ModelNode, at: ts.Node): string {
775
+ const known = this.tables.get(node.id);
776
+ if (known) {
777
+ return known;
778
+ }
779
+ if (!node.type) {
780
+ throw new SpecializeError(
781
+ at,
782
+ "This array has no declared type to index it by at run time.",
783
+ );
784
+ }
785
+ // Named for where setup put it: numbered by first read, two tables swapped names under one type.
786
+ const identity = this.context.model.identity(node);
787
+ const name = identity
788
+ ? `tsplcTable_${identityDigest(identity)}`
789
+ : `tsplcTable${this.tables.size + 1}`;
790
+ this.tables.set(node.id, name);
791
+ const type = this.context.layouts.text(node.type, {
792
+ kind: "node",
793
+ id: node.id,
794
+ });
795
+ this.tableDeclarations.push(
796
+ from(
797
+ at,
798
+ `const ${name}: ${type} = ${this.context.initializers.valueText({ kind: "node", id: node.id }, node.type, type)};`,
799
+ ),
800
+ );
801
+ return name;
802
+ }
803
+
804
+ /** Stores a scan-built array in a local, for indexing at runtime. */
805
+ private materialize(
806
+ items: readonly Value[],
807
+ at: ts.Node,
808
+ frame: Frame,
809
+ ): string {
810
+ const type = this.context.checker.getTypeAtLocation(at);
811
+ const element = this.context.model.elementType(type);
812
+ if (!element) {
813
+ throw new SpecializeError(at, "Not an array.");
814
+ }
815
+ const local = frame.emitter.temporary();
816
+ frame.emitter.line(
817
+ mapped`const ${local}: ${arrayLayout(this.context.layouts.text(element), items.length).text} = [${joined(
818
+ items.map((item) => this.context.dialect.code(item, element)),
819
+ ", ",
820
+ )}];`,
821
+ );
822
+ return local;
823
+ }
824
+
825
+ private objectLiteral(node: ts.ObjectLiteralExpression, frame: Frame): Value {
826
+ const fields = new Map<string, Value>();
827
+ for (const property of node.properties) {
828
+ if (ts.isPropertyAssignment(property)) {
829
+ fields.set(
830
+ property.name.getText(),
831
+ this.expression(
832
+ property.initializer,
833
+ frame,
834
+ this.context.checker.getContextualType(property.initializer),
835
+ ),
836
+ );
837
+ } else if (ts.isShorthandPropertyAssignment(property)) {
838
+ fields.set(property.name.text, this.shorthand(property, frame));
839
+ } else if (ts.isSpreadAssignment(property)) {
840
+ for (const [name, value] of this.recordFields(
841
+ property.expression,
842
+ frame,
843
+ )) {
844
+ fields.set(name, value);
845
+ }
846
+ } else {
847
+ throw new SpecializeError(property, "Write each field of a record.");
848
+ }
849
+ }
850
+ return { kind: "virtual", fields };
851
+ }
852
+
853
+ /** What `{ name }` gives its field: the local the name reads, not the property it declares. */
854
+ shorthand(property: ts.ShorthandPropertyAssignment, frame: Frame): Value {
855
+ const symbol = valueSymbol(this.context.checker, property.name);
856
+ const local = symbol && frame.env.get(symbol);
857
+ return local ?? this.expression(property.name, frame);
858
+ }
859
+
860
+ private unary(node: ts.PrefixUnaryExpression, frame: Frame): Value {
861
+ const operand = this.expression(node.operand, frame);
862
+ switch (node.operator) {
863
+ case ts.SyntaxKind.ExclamationToken:
864
+ if (operand.kind === "const") {
865
+ return constant(!operand.value);
866
+ }
867
+ if (operand.kind === "static" || operand.kind === "function") {
868
+ return constant(false);
869
+ }
870
+ return {
871
+ kind: "code",
872
+ text: mapped`!${this.context.dialect.condition(operand, node.operand)}`,
873
+ declared: this.context.checker.getBooleanType(),
874
+ };
875
+ case ts.SyntaxKind.MinusToken:
876
+ if (operand.kind === "const" && typeof operand.value === "number") {
877
+ return constant(-operand.value);
878
+ }
879
+ return {
880
+ kind: "code",
881
+ text: mapped`-${this.context.dialect.code(operand, undefined)}`,
882
+ declared: this.context.checker.getTypeAtLocation(node),
883
+ };
884
+ case ts.SyntaxKind.PlusToken:
885
+ return operand;
886
+ default:
887
+ throw new SpecializeError(
888
+ node,
889
+ `${ts.tokenToString(node.operator)} is not supported.`,
890
+ );
891
+ }
892
+ }
893
+
894
+ private binary(
895
+ node: ts.BinaryExpression,
896
+ frame: Frame,
897
+ expected?: ts.Type,
898
+ ): Value {
899
+ const kind = node.operatorToken.kind;
900
+ if (
901
+ kind === ts.SyntaxKind.AmpersandAmpersandToken ||
902
+ kind === ts.SyntaxKind.BarBarToken
903
+ ) {
904
+ const left = this.expression(node.left, frame);
905
+ const and = kind === ts.SyntaxKind.AmpersandAmpersandToken;
906
+ if (left.kind === "const") {
907
+ if (Boolean(left.value) !== and) {
908
+ return left;
909
+ }
910
+ return this.expression(node.right, frame, expected);
911
+ }
912
+ if (left.kind === "static" || left.kind === "function") {
913
+ return and ? this.expression(node.right, frame, expected) : left;
914
+ }
915
+ if (left.kind === "choice" && !and) {
916
+ return this.references.fallback(
917
+ left,
918
+ () => this.expression(node.right, frame, expected),
919
+ node,
920
+ frame,
921
+ );
922
+ }
923
+ if (
924
+ left.kind === "choice" &&
925
+ referenceType(this.context.checker.getTypeAtLocation(node))
926
+ ) {
927
+ return this.references.branch(
928
+ this.context.dialect.condition(left, node.left),
929
+ [
930
+ () => this.expression(node.right, frame, expected),
931
+ () => constant(undefined),
932
+ ],
933
+ node,
934
+ frame,
935
+ );
936
+ }
937
+ if (
938
+ !and &&
939
+ left.kind === "code" &&
940
+ this.isNumber(node.left) &&
941
+ !this.runsWhenNeeded(node.right, frame)
942
+ ) {
943
+ return this.firstNonZero(left, node, frame);
944
+ }
945
+ if (this.runsWhenNeeded(node.right, frame)) {
946
+ // The right operand's writes happen only when it is evaluated.
947
+ const result = frame.emitter.temporary();
948
+ frame.emitter.line(
949
+ mapped`let ${result}: boolean = ${this.context.dialect.condition(left, node.left)};`,
950
+ );
951
+ frame.emitter.open(and ? `if (${result}) {` : `if (!${result}) {`);
952
+ const right = this.expression(node.right, frame, expected);
953
+ frame.emitter.line(
954
+ mapped`${result} = ${this.context.dialect.condition(right, node.right)};`,
955
+ );
956
+ frame.emitter.close();
957
+ return {
958
+ kind: "code",
959
+ text: result,
960
+ declared: this.context.checker.getBooleanType(),
961
+ place: true,
962
+ };
963
+ }
964
+ const right = this.expression(node.right, frame, expected);
965
+ if (right.kind === "const") {
966
+ if (Boolean(right.value) === and) {
967
+ return {
968
+ kind: "code",
969
+ text: this.context.dialect.condition(left, node.left),
970
+ declared: this.context.checker.getBooleanType(),
971
+ };
972
+ }
973
+ return constant(!and);
974
+ }
975
+ return {
976
+ kind: "code",
977
+ text: mapped`(${this.context.dialect.condition(left, node.left)} ${and ? "&&" : "||"} ${this.context.dialect.condition(right, node.right)})`,
978
+ declared: this.context.checker.getBooleanType(),
979
+ };
980
+ }
981
+ if (kind === ts.SyntaxKind.QuestionQuestionToken) {
982
+ return this.orElse(
983
+ this.expression(node.left, frame),
984
+ node.right,
985
+ frame,
986
+ expected,
987
+ );
988
+ }
989
+ if (isAssignment(kind)) {
990
+ return this.assignments.assign(node, frame);
991
+ }
992
+ const equality = [
993
+ ts.SyntaxKind.EqualsEqualsEqualsToken,
994
+ ts.SyntaxKind.ExclamationEqualsEqualsToken,
995
+ ts.SyntaxKind.EqualsEqualsToken,
996
+ ts.SyntaxKind.ExclamationEqualsToken,
997
+ ].includes(kind);
998
+ const read = this.expression(node.left, frame);
999
+ // A left operand read before the right one writes keeps the value it had.
1000
+ const left = containsWrite(node.right) ? this.held(read, frame) : read;
1001
+ const right = this.expression(
1002
+ node.right,
1003
+ frame,
1004
+ read.kind === "code" ? read.declared : undefined,
1005
+ );
1006
+ const negate =
1007
+ kind === ts.SyntaxKind.ExclamationEqualsEqualsToken ||
1008
+ kind === ts.SyntaxKind.ExclamationEqualsToken;
1009
+ if (equality) {
1010
+ this.references.identities(left, right, node);
1011
+ return this.equality(left, right, { negate });
1012
+ }
1013
+ if (
1014
+ left.kind === "const" &&
1015
+ right.kind === "const" &&
1016
+ typeof left.value === "number" &&
1017
+ typeof right.value === "number"
1018
+ ) {
1019
+ const folded = foldNumber(kind, left.value, right.value);
1020
+ if (folded !== undefined) {
1021
+ return constant(finite(folded, node));
1022
+ }
1023
+ }
1024
+ if (kind === ts.SyntaxKind.AsteriskAsteriskToken) {
1025
+ return this.calls.floatMath("pow", [left, right], node, frame);
1026
+ }
1027
+ const declared = this.context.checker.getTypeAtLocation(node);
1028
+ const comparison = comparisonOperators.get(kind);
1029
+ if (comparison) {
1030
+ const [leftText, rightText] = this.context.dialect.comparable(
1031
+ left,
1032
+ right,
1033
+ undefined,
1034
+ );
1035
+ return {
1036
+ kind: "code",
1037
+ text: mapped`(${leftText} ${comparison} ${rightText})`,
1038
+ declared,
1039
+ };
1040
+ }
1041
+ if (
1042
+ kind === ts.SyntaxKind.SlashToken &&
1043
+ !floatIec(left) &&
1044
+ !floatIec(right)
1045
+ ) {
1046
+ throw new SpecializeError(
1047
+ node,
1048
+ "/ on integers gives a fraction, which no integer holds: divide with div<T>(a, b) from @tsplc/compiler/types, which truncates toward zero, or make an operand REAL or LREAL.",
1049
+ );
1050
+ }
1051
+ const operator = arithmeticOperators.get(kind);
1052
+ if (!operator) {
1053
+ throw new SpecializeError(
1054
+ node,
1055
+ `${node.operatorToken.getText()} is not supported.`,
1056
+ );
1057
+ }
1058
+ const { texts, iec } = this.context.dialect.arithmetic(left, right);
1059
+ return {
1060
+ kind: "code",
1061
+ text: mapped`(${texts[0]} ${operator} ${texts[1]})`,
1062
+ declared,
1063
+ iec,
1064
+ };
1065
+ }
1066
+
1067
+ /** A plain number: an enum's members are numbers to TypeScript, but the PLC's enum is no integer. */
1068
+ private isNumber(node: ts.Expression): boolean {
1069
+ const flags = this.context.checker.getTypeAtLocation(node).flags;
1070
+ return (
1071
+ Boolean(flags & (ts.TypeFlags.Number | ts.TypeFlags.NumberLiteral)) &&
1072
+ !(flags & ts.TypeFlags.EnumLike)
1073
+ );
1074
+ }
1075
+
1076
+ /**
1077
+ * `left || right` between numbers is a number, as a comparator's `byLoad || byId` is: the left
1078
+ * one unless it is zero. A right operand that writes keeps the boolean form, whose branch holds it.
1079
+ */
1080
+ private firstNonZero(
1081
+ left: Value & { kind: "code" },
1082
+ node: ts.BinaryExpression,
1083
+ frame: Frame,
1084
+ ): Value {
1085
+ const once = this.temporaryOf(left, frame);
1086
+ const right = this.expression(node.right, frame);
1087
+ const first = this.context.dialect.code(once, undefined);
1088
+ return {
1089
+ kind: "code",
1090
+ text: mapped`(${first} !== 0 ? ${first} : ${this.context.dialect.code(right, undefined)})`,
1091
+ declared: this.context.checker.getTypeAtLocation(node),
1092
+ iec: left.iec,
1093
+ };
1094
+ }
1095
+
1096
+ /** `left === right`, or `!==` when negated: known now when it can be, otherwise a comparison. */
1097
+ equality(left: Value, right: Value, { negate }: { negate: boolean }): Value {
1098
+ const referred = this.references.equality(left, right, { negate });
1099
+ if (referred) {
1100
+ return referred;
1101
+ }
1102
+ const folded = this.equal(left, right);
1103
+ if (folded !== undefined) {
1104
+ return constant(negate ? !folded : folded);
1105
+ }
1106
+ const [code, other] = left.kind === "code" ? [left, right] : [right, left];
1107
+ if (
1108
+ code.kind === "code" &&
1109
+ other.kind === "const" &&
1110
+ other.value === undefined
1111
+ ) {
1112
+ // A value whose storage can't hold undefined never is, as an index setup filled isn't.
1113
+ if (
1114
+ !code.declared ||
1115
+ (!this.context.layouts.isOptionalRecord(code.declared) &&
1116
+ !this.context.layouts.literals(code.declared)?.optional)
1117
+ ) {
1118
+ return constant(negate);
1119
+ }
1120
+ const test = this.context.dialect.isUndefinedText(
1121
+ code.text,
1122
+ code.declared,
1123
+ );
1124
+ return {
1125
+ kind: "code",
1126
+ text: negate ? mapped`!(${test})` : test,
1127
+ declared: this.context.checker.getBooleanType(),
1128
+ };
1129
+ }
1130
+ const declared = code.kind === "code" ? code.declared : undefined;
1131
+ const [leftText, rightText] = this.context.dialect.comparable(
1132
+ left,
1133
+ right,
1134
+ declared,
1135
+ );
1136
+ return {
1137
+ kind: "code",
1138
+ text: mapped`(${leftText} ${negate ? "!==" : "==="} ${rightText})`,
1139
+ declared: this.context.checker.getBooleanType(),
1140
+ };
1141
+ }
1142
+
1143
+ /** Equality known now: two known objects, or a known object against undefined. */
1144
+ private equal(left: Value, right: Value): boolean | undefined {
1145
+ if (left.kind === "const" && right.kind === "const") {
1146
+ return left.value === right.value;
1147
+ }
1148
+ if (left.kind === "static" && right.kind === "static") {
1149
+ return left.node === right.node;
1150
+ }
1151
+ if (
1152
+ (left.kind === "static" && right.kind === "const") ||
1153
+ (left.kind === "const" && right.kind === "static")
1154
+ ) {
1155
+ return false;
1156
+ }
1157
+ return undefined;
1158
+ }
1159
+
1160
+ /** Calls a function value: specializes it, or inlines a one-expression arrow. */
1161
+ invoke(
1162
+ target: Value,
1163
+ args: Value[],
1164
+ at: ts.Node,
1165
+ frame: Frame,
1166
+ expected?: ts.Type,
1167
+ ): Value {
1168
+ if (target.kind === "static" && target.node.captured.kind === "closure") {
1169
+ return this.invoke(
1170
+ this.closure(target.node.captured, at),
1171
+ args,
1172
+ at,
1173
+ frame,
1174
+ expected,
1175
+ );
1176
+ }
1177
+ if (target.kind !== "function") {
1178
+ throw new SpecializeError(at, "Only functions can be called.");
1179
+ }
1180
+ const declaration = target.declaration;
1181
+ if (!declaration.body && declaration.getSourceFile().isDeclarationFile) {
1182
+ const name = declaration.name?.getText() ?? "This function";
1183
+ throw new SpecializeError(
1184
+ at,
1185
+ `${name} is declared without a body, as JavaScript's own functions are: scan code calls functions the program writes and the SDK's, so compute the value in the program, or in setup.`,
1186
+ );
1187
+ }
1188
+ if (
1189
+ target.env &&
1190
+ ts.isArrowFunction(declaration) &&
1191
+ !ts.isBlock(declaration.body)
1192
+ ) {
1193
+ const inline: Frame = {
1194
+ ...frame,
1195
+ env: new Map(target.env),
1196
+ self: target.self ?? frame.self,
1197
+ };
1198
+ declaration.parameters.forEach((parameter, index) => {
1199
+ const given = args[index] ?? constant(undefined);
1200
+ const fallback = parameterDefault(
1201
+ this.context.checker,
1202
+ given,
1203
+ parameter,
1204
+ );
1205
+ const arg = fallback ? this.expression(fallback, inline) : given;
1206
+ const value =
1207
+ arg.kind === "code" && !arg.place
1208
+ ? this.temporaryOf(arg, frame)
1209
+ : arg;
1210
+ this.bind(
1211
+ parameter.name,
1212
+ value,
1213
+ inline,
1214
+ this.context.checker.getTypeAtLocation(parameter),
1215
+ { mutable: false, iec: this.context.layouts.iecName(parameter) },
1216
+ );
1217
+ });
1218
+ const result = this.expression(declaration.body, inline, expected);
1219
+ const iec = this.context.layouts.iecName(declaration);
1220
+ this.refuseOutsideWidth(result, iec, declaration.body);
1221
+ if (iec === undefined || result.kind !== "code") {
1222
+ return result;
1223
+ }
1224
+ const signature =
1225
+ this.context.checker.getSignatureFromDeclaration(declaration);
1226
+ const declared =
1227
+ signature && this.context.checker.getReturnTypeOfSignature(signature);
1228
+ return {
1229
+ kind: "code",
1230
+ text: this.context.dialect.assignmentText(result, declared, iec),
1231
+ declared,
1232
+ iec,
1233
+ };
1234
+ }
1235
+ const called = this.routineTable.routine(
1236
+ declaration,
1237
+ target.self,
1238
+ args,
1239
+ target.env && { env: target.env, caller: frame.emitter },
1240
+ );
1241
+ const text = mapped`${called.name}(${joined(called.args, ", ")})`;
1242
+ const returns = called.returns;
1243
+ if (!returns || returns.flags & ts.TypeFlags.Void) {
1244
+ const statement = ts.isAwaitExpression(at.parent) ? at.parent : at;
1245
+ if (ts.isExpressionStatement(statement.parent) || linksPromise(at)) {
1246
+ return { kind: "code", text, declared: returns };
1247
+ }
1248
+ frame.emitter.line(mapped`${text};`);
1249
+ return constant(undefined);
1250
+ }
1251
+ if (referenceType(returns)) {
1252
+ return this.references.result(text, called.referents, returns, frame);
1253
+ }
1254
+ return {
1255
+ kind: "code",
1256
+ text,
1257
+ declared: returns,
1258
+ iec: called.iec,
1259
+ layout: called.layout,
1260
+ length: called.length,
1261
+ ...(called.returnsStored && { copyOf: sourceName(target) }),
1262
+ };
1263
+ }
1264
+
1265
+ /**
1266
+ * `super.name`: the member the class around the expression inherits, on the same instance. Every
1267
+ * instance's class is known when the program compiles, so this resolves then.
1268
+ */
1269
+ superMember(node: ts.PropertyAccessExpression, frame: Frame): Value {
1270
+ const owner = ts.findAncestor(node, ts.isClassDeclaration);
1271
+ if (!owner || !frame.self) {
1272
+ throw new SpecializeError(node, "`super` outside a method.");
1273
+ }
1274
+ const name = node.name.text;
1275
+ const inherited = this.context.model
1276
+ .ancestry(owner)
1277
+ .slice(1)
1278
+ .flatMap((base) => [...base.members]);
1279
+ const accessor = getterNamed(inherited, name);
1280
+ if (accessor) {
1281
+ return this.invoke(
1282
+ { kind: "function", declaration: accessor, self: frame.self },
1283
+ [],
1284
+ node,
1285
+ frame,
1286
+ );
1287
+ }
1288
+ const method = methodNamed(inherited, name);
1289
+ if (!method) {
1290
+ throw new SpecializeError(node, `The base class has no ${name}.`);
1291
+ }
1292
+ return { kind: "function", declaration: method, self: frame.self };
1293
+ }
1294
+
1295
+ /** Each field of a record-valued expression: a known record's, or each property its type declares. */
1296
+ recordFields(expression: ts.Expression, frame: Frame): [string, Value][] {
1297
+ const evaluated = this.expression(expression, frame);
1298
+ if (evaluated.kind === "virtual" && evaluated.fields) {
1299
+ return [...evaluated.fields];
1300
+ }
1301
+ // A runtime record is read once, so a call in it runs once.
1302
+ const source =
1303
+ evaluated.kind === "code"
1304
+ ? this.temporaryOf(evaluated, frame)
1305
+ : evaluated;
1306
+ const type = this.context.checker.getTypeAtLocation(expression);
1307
+ return this.context.checker
1308
+ .getPropertiesOfType(this.context.checker.getNonNullableType(type))
1309
+ .map((symbol): [string, Value] => [
1310
+ symbol.name,
1311
+ this.member(source, symbol.name, expression, frame),
1312
+ ]);
1313
+ }
1314
+
1315
+ /**
1316
+ * A record or array literal stays a value known now, unless the code changes it through its name or
1317
+ * lends it to a call: then it is a local, as a new object is. One holding objects setup built stays known.
1318
+ */
1319
+ private heldAsLocal(
1320
+ value: Value & { kind: "virtual" },
1321
+ name: ts.Identifier,
1322
+ symbol: ts.Symbol,
1323
+ ): boolean {
1324
+ if (holdsSetupObjects(value)) {
1325
+ return false;
1326
+ }
1327
+ return writesThrough(scopeOf(name), symbol, this.context.checker);
1328
+ }
1329
+
1330
+ /** `typeof`, known when the program compiles: from a value setup fixed, or from runtime storage's declared type. */
1331
+ private typeOf(value: Value): Value {
1332
+ if (value.kind === "const") {
1333
+ return constant(typeof value.value);
1334
+ }
1335
+ if (value.kind === "function") {
1336
+ return constant("function");
1337
+ }
1338
+ if (value.kind !== "code" || !value.declared) {
1339
+ return constant("object");
1340
+ }
1341
+ const declared = value.declared;
1342
+ const kinds: [ts.TypeFlags, string][] = [
1343
+ [ts.TypeFlags.NumberLike, "number"],
1344
+ [ts.TypeFlags.StringLike, "string"],
1345
+ [ts.TypeFlags.BooleanLike, "boolean"],
1346
+ [ts.TypeFlags.BigIntLike, "bigint"],
1347
+ ];
1348
+ const found = kinds.find(([flag]) => declared.flags & flag);
1349
+ return constant(found ? found[1] : "object");
1350
+ }
1351
+
1352
+ /**
1353
+ * A function setup made inside another and stored: its declaration, with the values it captured
1354
+ * as its closure, and the object it was made in as its `this`.
1355
+ */
1356
+ private closure(
1357
+ captured: Extract<ModelNode["captured"], { kind: "closure" }>,
1358
+ at: ts.Node,
1359
+ ): Value {
1360
+ const source = this.context.model.sourceFile(captured.file);
1361
+ const declaration = findClosure(source, captured.start);
1362
+ if (!declaration) {
1363
+ throw new SpecializeError(
1364
+ at,
1365
+ "The function setup stored isn't in the program.",
1366
+ );
1367
+ }
1368
+ const symbols = closureSymbols(declaration, this.context.checker);
1369
+ const env: Env = new Map(
1370
+ captured.captures.flatMap(({ name, value }): [ts.Symbol, Value][] => {
1371
+ const known: Value =
1372
+ value.kind === "node"
1373
+ ? { kind: "static", node: this.context.model.node(value) }
1374
+ : capturedPrimitive(value);
1375
+ return (symbols.get(name) ?? []).map((symbol): [ts.Symbol, Value] => [
1376
+ symbol,
1377
+ known,
1378
+ ]);
1379
+ }),
1380
+ );
1381
+ const made = captured.captures.find(({ name }) => name === "this");
1382
+ const self = made && this.context.model.node(made.value);
1383
+ return { kind: "function", declaration, self, env };
1384
+ }
1385
+
1386
+ /**
1387
+ * `reference?.name` or `reference?.method()`: what `read` gives when the reference holds an
1388
+ * object, and undefined when it holds none, as JavaScript gives, never the read's empty value.
1389
+ */
1390
+ chained(
1391
+ object: Extract<Value, { kind: "choice" }>,
1392
+ read: () => Value,
1393
+ node: ts.Expression,
1394
+ frame: Frame,
1395
+ ): Value {
1396
+ const result = this.context.checker.getTypeAtLocation(node);
1397
+ const present = this.context.dialect.condition(object, node);
1398
+ if (referenceType(result)) {
1399
+ return this.references.branch(
1400
+ present,
1401
+ [read, () => constant(undefined)],
1402
+ node,
1403
+ frame,
1404
+ );
1405
+ }
1406
+ // A call for its effect alone runs only when the reference holds an object, and gives nothing.
1407
+ const defined = this.context.checker.getNonNullableType(result);
1408
+ if (
1409
+ result.flags & ts.TypeFlags.Void ||
1410
+ defined.flags & (ts.TypeFlags.Void | ts.TypeFlags.Never)
1411
+ ) {
1412
+ return read();
1413
+ }
1414
+ if (
1415
+ !this.context.layouts.isOptionalRecord(result) &&
1416
+ !this.context.layouts.literals(result)?.optional
1417
+ ) {
1418
+ throw new SpecializeError(
1419
+ node,
1420
+ "?. through this reference gives a value the PLC can't hold as optional: test the reference with !== undefined first, and read it inside the if.",
1421
+ );
1422
+ }
1423
+ return this.branched(
1424
+ result,
1425
+ present,
1426
+ [read, () => constant(undefined)],
1427
+ frame,
1428
+ );
1429
+ }
1430
+
1431
+ /** `record?.field` on an optional record: the field as an optional, or the empty value when the record is. */
1432
+ private optionalMember(
1433
+ object: Code,
1434
+ declared: ts.Type,
1435
+ node: ts.PropertyAccessExpression,
1436
+ frame: Frame,
1437
+ ): Value {
1438
+ const held = this.temporaryOf(object, frame);
1439
+ const defined: Value = {
1440
+ kind: "code",
1441
+ text: optionalValue(held.text),
1442
+ declared: this.context.checker.getNonNullableType(declared),
1443
+ place: held.place,
1444
+ };
1445
+ const field = this.member(defined, node.name.text, node, frame);
1446
+ const result = this.context.checker.getTypeAtLocation(node);
1447
+ return {
1448
+ kind: "code",
1449
+ text: mapped`(${this.context.dialect.isUndefinedText(held.text, declared)} ? ${this.context.dialect.assignmentText(constant(undefined), result, undefined)} : ${this.context.dialect.assignmentText(field, result, undefined)})`,
1450
+ declared: result,
1451
+ };
1452
+ }
1453
+
1454
+ /**
1455
+ * Evaluates operands left to right. A runtime value read before a later operand writes is held in
1456
+ * a const first, so it is the value JavaScript reads then.
1457
+ */
1458
+ inOrder<T extends ts.Node>(
1459
+ nodes: readonly T[],
1460
+ evaluate: (node: T, index: number) => Value,
1461
+ frame: Frame,
1462
+ ): Value[] {
1463
+ return nodes.map((node, index) => {
1464
+ const value = evaluate(node, index);
1465
+ return nodes.slice(index + 1).some(containsWrite)
1466
+ ? this.held(value, frame)
1467
+ : value;
1468
+ });
1469
+ }
1470
+
1471
+ /** A runtime scalar's current value, in a const of its own; aggregates and known values stay as they are. */
1472
+ held(value: Value, frame: Frame): Value {
1473
+ if (value.kind === "choice") {
1474
+ return this.references.held(value, frame);
1475
+ }
1476
+ if (
1477
+ value.kind !== "code" ||
1478
+ (value.declared && this.isAggregate(value.declared))
1479
+ ) {
1480
+ return value;
1481
+ }
1482
+ return this.hold(value, frame, {
1483
+ width: true,
1484
+ widen: true,
1485
+ untyped: "number",
1486
+ repeatable: true,
1487
+ });
1488
+ }
1489
+
1490
+ /** A runtime value in a const of its own, so code after reads the const rather than running the value again. */
1491
+ hold(value: Code, frame: Frame, holding: Holding): Code {
1492
+ if (!holding.repeatable && repeatable(value.text)) {
1493
+ return value;
1494
+ }
1495
+ const local = frame.emitter.temporary();
1496
+ frame.emitter.line(
1497
+ mapped`const ${local}: ${this.heldType(value, holding)} = ${value.text};`,
1498
+ );
1499
+ return {
1500
+ kind: "code",
1501
+ text: local,
1502
+ declared: value.declared,
1503
+ place: true,
1504
+ ...(holding.width && { iec: value.iec }),
1505
+ };
1506
+ }
1507
+
1508
+ /** A runtime value's PLC type, as `typing` reads it. */
1509
+ heldType(value: Code, { width, widen, untyped }: Typing): string {
1510
+ const iec = width ? value.iec : undefined;
1511
+ if (iec) {
1512
+ return iec;
1513
+ }
1514
+ if (!value.declared) {
1515
+ return untyped;
1516
+ }
1517
+ return widen
1518
+ ? this.localType(value.declared)
1519
+ : this.context.layouts.text(value.declared);
1520
+ }
1521
+
1522
+ /** `.value` for an optional record, whose defined value sits in a field. */
1523
+ optionalValueSuffix(declared: ts.Type): string {
1524
+ return this.context.layouts.isOptionalRecord(declared)
1525
+ ? `.${optionalRecord.value}`
1526
+ : "";
1527
+ }
1528
+
1529
+ /**
1530
+ * A choice whose branches write, as an if statement storing each branch's value in a local, so a
1531
+ * branch's writes happen only when it is taken.
1532
+ */
1533
+ private branched(
1534
+ declared: ts.Type,
1535
+ condition: Part,
1536
+ branches: readonly [
1537
+ ts.Expression | (() => Value),
1538
+ ts.Expression | (() => Value),
1539
+ ],
1540
+ frame: Frame,
1541
+ ): Value {
1542
+ const result = frame.emitter.temporary();
1543
+ frame.emitter.line(
1544
+ `let ${result}: ${this.localType(declared)} = ${this.context.initializers.defaultOf(declared)};`,
1545
+ );
1546
+ const evaluate = (branch: ts.Expression | (() => Value)): Value =>
1547
+ typeof branch === "function"
1548
+ ? branch()
1549
+ : this.expression(branch, frame, declared);
1550
+ const [yes, no] = branches;
1551
+ frame.emitter.open(mapped`if (${condition}) {`);
1552
+ frame.emitter.line(
1553
+ mapped`${result} = ${this.context.dialect.assignmentText(evaluate(yes), declared, undefined)};`,
1554
+ );
1555
+ frame.emitter.reopen("} else {");
1556
+ frame.emitter.line(
1557
+ mapped`${result} = ${this.context.dialect.assignmentText(evaluate(no), declared, undefined)};`,
1558
+ );
1559
+ frame.emitter.close();
1560
+ return { kind: "code", text: result, declared, place: true };
1561
+ }
1562
+
1563
+ /**
1564
+ * Whether an operand JavaScript evaluates only when it needs it is written as statements: it
1565
+ * writes a place, or runs a generator or a snapshot's loop. Those go in the branch that needs them.
1566
+ */
1567
+ private runsWhenNeeded(node: ts.Expression, frame: Frame): boolean {
1568
+ return containsWrite(node) || this.iterators.traverses(node, frame);
1569
+ }
1570
+
1571
+ /** The routine that cancels the pending async calls of an instance's methods, as `cancelAsync(this)` does. */
1572
+ canceller(self: ModelNode): string {
1573
+ return this.routineTable.canceller(self);
1574
+ }
1575
+
1576
+ /**
1577
+ * Evaluates `run` only to learn what it gives: the routines, tables and service nodes it makes
1578
+ * belong to code nothing keeps, so they are forgotten after.
1579
+ */
1580
+ speculatively<T>(run: () => T): T {
1581
+ const declarations = this.tableDeclarations.length;
1582
+ const restored = [restoring(this.tables), restoring(this.services)];
1583
+ try {
1584
+ return this.routineTable.speculatively(run);
1585
+ } finally {
1586
+ this.tableDeclarations.splice(declarations);
1587
+ for (const restore of restored) {
1588
+ restore();
1589
+ }
1590
+ }
1591
+ }
1592
+
1593
+ /**
1594
+ * A known number named under an IEC integer annotation obeys the rule a literal stored there
1595
+ * obeys: one the type cannot hold is refused.
1596
+ */
1597
+ private refuseOutsideWidth(
1598
+ value: Value,
1599
+ iec: string | undefined,
1600
+ at: ts.Node,
1601
+ ): void {
1602
+ const type = primitiveTypes.find((primitive) => primitive.id === iec);
1603
+ if (
1604
+ type === undefined ||
1605
+ !integerType(type) ||
1606
+ value.kind !== "const" ||
1607
+ (typeof value.value !== "number" && typeof value.value !== "bigint")
1608
+ ) {
1609
+ return;
1610
+ }
1611
+ if (!constantFits({ kind: "integer", value: String(value.value) }, type)) {
1612
+ throw new SpecializeError(at, literalOutsideType);
1613
+ }
1614
+ }
1615
+
1616
+ /**
1617
+ * `left`, or `fallback` when it is undefined, as `??` and a pattern's default give: the fallback
1618
+ * runs only when it is needed.
1619
+ */
1620
+ private orElse(
1621
+ left: Value,
1622
+ fallback: ts.Expression,
1623
+ frame: Frame,
1624
+ expected: ts.Type | undefined,
1625
+ ): Value {
1626
+ if (left.kind === "const") {
1627
+ return left.value === undefined
1628
+ ? this.expression(fallback, frame, expected)
1629
+ : left;
1630
+ }
1631
+ if (left.kind === "static") {
1632
+ return left;
1633
+ }
1634
+ if (left.kind === "choice") {
1635
+ return this.references.fallback(
1636
+ left,
1637
+ () => this.expression(fallback, frame, expected),
1638
+ fallback.parent,
1639
+ frame,
1640
+ );
1641
+ }
1642
+ if (
1643
+ left.kind !== "code" ||
1644
+ !left.declared ||
1645
+ this.context.checker.getNonNullableType(left.declared) === left.declared
1646
+ ) {
1647
+ return left;
1648
+ }
1649
+ const declared = left.declared;
1650
+ const defined = this.context.checker.getNonNullableType(declared);
1651
+ // A record or array result is chosen by statements: PLC code loads one only into storage.
1652
+ if (this.runsWhenNeeded(fallback, frame) || this.isAggregate(defined)) {
1653
+ // Read once to test and once to give, so a call on the left runs once, into a const.
1654
+ const held = this.isAggregate(declared)
1655
+ ? this.temporaryOf(left, frame)
1656
+ : this.held(left, frame);
1657
+ return this.branched(
1658
+ defined,
1659
+ this.context.dialect.isUndefinedText(
1660
+ this.context.dialect.code(held, declared),
1661
+ declared,
1662
+ ),
1663
+ [
1664
+ fallback,
1665
+ () => ({
1666
+ kind: "code",
1667
+ text: mapped`${this.context.dialect.code(held, undefined)}${this.optionalValueSuffix(declared)}`,
1668
+ declared: defined,
1669
+ }),
1670
+ ],
1671
+ frame,
1672
+ );
1673
+ }
1674
+ // The left operand is read twice, so a call in it runs once, into a const.
1675
+ const once = this.temporaryOf(left, frame);
1676
+ const right = this.expression(fallback, frame, defined);
1677
+ return {
1678
+ kind: "code",
1679
+ text: mapped`(${this.context.dialect.isUndefinedText(this.context.dialect.code(once, declared), declared)} ? ${this.context.dialect.code(right, defined)} : ${this.context.dialect.code(once, undefined)}${this.optionalValueSuffix(declared)})`,
1680
+ declared: defined,
1681
+ };
1682
+ }
1683
+
1684
+ /** What a pattern's part is worth: `fallback` when the part is undefined, as `{ x = 7 }` defaults. */
1685
+ defaulted(
1686
+ part: Value,
1687
+ fallback: ts.Expression | undefined,
1688
+ frame: Frame,
1689
+ ): Value {
1690
+ return fallback === undefined
1691
+ ? part
1692
+ : this.orElse(part, fallback, frame, undefined);
1693
+ }
1694
+
1695
+ /** A runtime value held in a const, so inlining doesn't evaluate it twice. */
1696
+ temporaryOf(value: Code, frame: Frame): Code {
1697
+ return this.hold(value, frame, {
1698
+ width: false,
1699
+ widen: true,
1700
+ untyped: "number",
1701
+ repeatable: false,
1702
+ });
1703
+ }
1704
+
1705
+ /** Binds a local, or each name of a destructuring pattern, to a value. */
1706
+ bind(
1707
+ name: ts.BindingName,
1708
+ value: Value,
1709
+ frame: Frame,
1710
+ declared: ts.Type,
1711
+ {
1712
+ mutable,
1713
+ iec,
1714
+ }: {
1715
+ mutable: boolean;
1716
+ /** The IEC width the binding's annotation names, as `const slot: UINT` does. */
1717
+ iec: string | undefined;
1718
+ },
1719
+ ): void {
1720
+ // A pattern reads its value once per name, so a computed value is held first.
1721
+ const bound =
1722
+ !ts.isIdentifier(name) && value.kind === "code" && !value.place
1723
+ ? this.temporaryOf(value, frame)
1724
+ : value;
1725
+ if (ts.isObjectBindingPattern(name)) {
1726
+ for (const { element, field } of namedFields(name, "pattern")) {
1727
+ const inner = this.defaulted(
1728
+ this.member(bound, field, element, frame),
1729
+ element.initializer,
1730
+ frame,
1731
+ );
1732
+ this.bind(
1733
+ element.name,
1734
+ inner,
1735
+ frame,
1736
+ this.context.checker.getTypeAtLocation(element.name),
1737
+ { mutable, iec: undefined },
1738
+ );
1739
+ }
1740
+ return;
1741
+ }
1742
+ if (ts.isArrayBindingPattern(name)) {
1743
+ for (const { element, index } of namedElements(name, "pattern")) {
1744
+ const inner = this.defaulted(
1745
+ this.element(bound, constant(index), element, frame),
1746
+ element.initializer,
1747
+ frame,
1748
+ );
1749
+ this.bind(
1750
+ element.name,
1751
+ inner,
1752
+ frame,
1753
+ this.context.checker.getTypeAtLocation(element.name),
1754
+ { mutable, iec: undefined },
1755
+ );
1756
+ }
1757
+ return;
1758
+ }
1759
+ const symbol = symbolOf(this.context.checker, name);
1760
+ if (this.context.checker.getAwaitedType(declared) !== declared) {
1761
+ throw new SpecializeError(
1762
+ name,
1763
+ `${name.text} would keep a promise, and the PLC runs an async call only where it is awaited: write const ${name.text} = await call(); where the call is made.`,
1764
+ );
1765
+ }
1766
+ const reference = this.references.local(name.text, bound, declared, frame, {
1767
+ mutable,
1768
+ });
1769
+ if (reference) {
1770
+ frame.env.set(symbol, reference);
1771
+ return;
1772
+ }
1773
+ if (
1774
+ bound.kind === "virtual" &&
1775
+ !isReadonly(declared, this.context.checker) &&
1776
+ this.heldAsLocal(bound, name, symbol)
1777
+ ) {
1778
+ const local = frame.emitter.local(name.text);
1779
+ frame.emitter.line(
1780
+ mapped`let ${local}: ${this.localType(declared)} = ${this.context.dialect.assignmentText(bound, declared, undefined)};`,
1781
+ );
1782
+ frame.env.set(symbol, {
1783
+ kind: "code",
1784
+ text: local,
1785
+ declared,
1786
+ place: true,
1787
+ });
1788
+ return;
1789
+ }
1790
+ if (mutable && bound.kind === "function" && ts.isIdentifier(name)) {
1791
+ throw new SpecializeError(
1792
+ name,
1793
+ `${name.text} is a let that holds a function, and the PLC calls only functions known when the program compiles: declare it with const, or choose which function to call with an if.`,
1794
+ );
1795
+ }
1796
+ if (!mutable && bound.kind !== "code") {
1797
+ this.refuseOutsideWidth(bound, iec, name);
1798
+ frame.env.set(symbol, bound);
1799
+ return;
1800
+ }
1801
+ if (
1802
+ !mutable &&
1803
+ bound.kind === "code" &&
1804
+ bound.place &&
1805
+ ts.isIdentifier(name) &&
1806
+ this.isAggregate(this.context.checker.getNonNullableType(declared)) &&
1807
+ replacedWhileAliased(name, this.context.checker)
1808
+ ) {
1809
+ this.snapshot(name, symbol, bound, declared, frame);
1810
+ return;
1811
+ }
1812
+ if (!mutable && bound.kind === "code" && bound.place) {
1813
+ // A const naming a place is an alias, as an object binding is in TypeScript. Its runtime
1814
+ // indexes are held now, so it keeps naming that element when they change; an index read
1815
+ // again at each use stays a value the PLC's bounds proof can follow.
1816
+ if (this.isAggregate(declared)) {
1817
+ const pin = bound.pinned;
1818
+ const repeats =
1819
+ ts.isIdentifier(name) &&
1820
+ pureRead(bound.text) &&
1821
+ stableAlias(name, this.context.checker);
1822
+ frame.env.set(symbol, pin && !repeats ? pin(frame) : bound);
1823
+ return;
1824
+ }
1825
+ }
1826
+ // A record an await gives, annotated with another record type, such as a narrower one, is
1827
+ // copied field by field from the awaited value, which keeps the call's own type.
1828
+ if (
1829
+ bound.kind === "code" &&
1830
+ bound.awaited &&
1831
+ bound.declared &&
1832
+ bound.declared !== declared &&
1833
+ this.isAggregate(declared) &&
1834
+ !this.context.checker.isArrayType(declared) &&
1835
+ ts.isVariableDeclaration(name.parent) &&
1836
+ name.parent.type !== undefined
1837
+ ) {
1838
+ const reply = frame.emitter.temporary();
1839
+ frame.emitter.line(mapped`const ${reply} = ${bound.text};`);
1840
+ const held: Value = {
1841
+ kind: "code",
1842
+ text: reply,
1843
+ declared: bound.declared,
1844
+ place: true,
1845
+ };
1846
+ const fields = new Map(
1847
+ this.context.checker
1848
+ .getPropertiesOfType(declared)
1849
+ .map((property): [string, Value] => [
1850
+ property.name,
1851
+ this.member(held, property.name, name, frame),
1852
+ ]),
1853
+ );
1854
+ this.bind(name, { kind: "virtual", fields }, frame, declared, {
1855
+ mutable,
1856
+ iec,
1857
+ });
1858
+ return;
1859
+ }
1860
+ const local = frame.emitter.local(name.text);
1861
+ // A const record changed through its name, or lent to a call that may, is a variable to the PLC:
1862
+ // TypeScript's const fixes the binding, not the object.
1863
+ const changes =
1864
+ !mutable &&
1865
+ this.isAggregate(declared) &&
1866
+ writesThrough(scopeOf(name), symbol, this.context.checker);
1867
+ const width = iec ?? (bound.kind === "code" ? bound.iec : undefined);
1868
+ const layout = bound.kind === "code" ? bound.layout : undefined;
1869
+ const length = bound.kind === "code" ? bound.length : undefined;
1870
+ if (declared.flags & ts.TypeFlags.Void) {
1871
+ throw new SpecializeError(
1872
+ name,
1873
+ `${name.text} holds what a call that answers nothing returns, which is no value; make the call a statement of its own.`,
1874
+ );
1875
+ }
1876
+ const type = width ?? layout?.text ?? this.localType(declared);
1877
+ // The async lowering suspends only at a bare await, so an awaited value cannot be converted in place.
1878
+ if (
1879
+ iec !== undefined &&
1880
+ bound.kind === "code" &&
1881
+ bound.awaited &&
1882
+ this.context.dialect.converts(bound, declared, iec)
1883
+ ) {
1884
+ throw new SpecializeError(
1885
+ name,
1886
+ `An awaited value keeps its routine's result type, ${bound.iec ?? defaultNumericTypes.number}; store it in a local of that type, then convert it.`,
1887
+ );
1888
+ }
1889
+ // An annotated width converts the value as IEC assignment does.
1890
+ const text = iec
1891
+ ? this.context.dialect.assignmentText(bound, declared, iec)
1892
+ : this.context.dialect.code(bound, declared);
1893
+ // What an await gives is typed by the call awaited, which the async lowering reads itself, and
1894
+ // what a task returns by the task's declaration, whose IEC result type no TypeScript type keeps.
1895
+ const typedByCall =
1896
+ bound.kind === "code" &&
1897
+ (bound.awaited || bound.typedByTask) &&
1898
+ !iec &&
1899
+ // A record the program annotates keeps that layout: no width conversion stands between it
1900
+ // and the call, and the call alone may not name it, as fetch's type argument doesn't.
1901
+ !(
1902
+ bound.awaited &&
1903
+ this.isAggregate(declared) &&
1904
+ ts.isVariableDeclaration(name.parent) &&
1905
+ name.parent.type !== undefined
1906
+ );
1907
+ const annotation = typedByCall ? "" : `: ${type}`;
1908
+ frame.emitter.line(
1909
+ mapped`${mutable || changes ? "let" : "const"} ${local}${annotation} = ${text};`,
1910
+ );
1911
+ frame.env.set(symbol, {
1912
+ kind: "code",
1913
+ text: local,
1914
+ declared,
1915
+ place: true,
1916
+ iec: width,
1917
+ layout,
1918
+ length,
1919
+ copyOf: bound.kind === "code" ? bound.copyOf : undefined,
1920
+ });
1921
+ }
1922
+
1923
+ /** A local's dialect type: a literal union keeps its enum; a lone literal widens to its base type. */
1924
+ localType(declared: ts.Type): string {
1925
+ if (this.context.layouts.literalEnum(declared)) {
1926
+ return this.context.layouts.text(declared);
1927
+ }
1928
+ return this.context.layouts.text(
1929
+ this.context.checker.getBaseTypeOfLiteralType(declared),
1930
+ );
1931
+ }
1932
+
1933
+ /**
1934
+ * A const record whose place is assigned anew while it is read keeps what the place held, as the
1935
+ * object TypeScript's const names does. The PLC reads a record const from its place at each use, so
1936
+ * it is a copy instead, which can't also pass writes through to the place.
1937
+ */
1938
+ private snapshot(
1939
+ name: ts.Identifier,
1940
+ symbol: ts.Symbol,
1941
+ bound: Value & { kind: "code" },
1942
+ declared: ts.Type,
1943
+ frame: Frame,
1944
+ ): void {
1945
+ if (writesThrough(scopeOf(name), symbol, this.context.checker)) {
1946
+ throw new SpecializeError(
1947
+ name,
1948
+ "This const is changed through, and the place it names is assigned anew while it is still used: the PLC can't keep both. Take a structuredClone of it, or change the place through its own path.",
1949
+ );
1950
+ }
1951
+ const local = frame.emitter.local(name.text);
1952
+ const type = bound.layout?.text ?? this.localType(declared);
1953
+ this.context.imports.addSdk(sdkModules.types, "copy");
1954
+ frame.emitter.line(
1955
+ mapped`const ${local}: ${type} = copy(${this.context.dialect.code(bound, declared)});`,
1956
+ );
1957
+ frame.env.set(symbol, {
1958
+ kind: "code",
1959
+ text: local,
1960
+ declared,
1961
+ place: true,
1962
+ layout: bound.layout,
1963
+ length: bound.length,
1964
+ });
1965
+ }
1966
+
1967
+ private isAggregate(type: ts.Type): boolean {
1968
+ return (
1969
+ Boolean(type.flags & ts.TypeFlags.Object) &&
1970
+ !this.context.layouts.literalEnum(type)
1971
+ );
1972
+ }
1973
+
1974
+ /**
1975
+ * The elements of an array setup built or scan code assembled from known parts; undefined for
1976
+ * a runtime array. Known arrays unroll, so each element's identity stays known.
1977
+ */
1978
+ items(value: Value): Value[] | undefined {
1979
+ if (value.kind === "virtual" && value.items) {
1980
+ return value.items;
1981
+ }
1982
+ if (value.kind === "code" && value.length !== undefined) {
1983
+ const declared =
1984
+ value.declared && this.context.model.elementType(value.declared);
1985
+ return Array.from(
1986
+ { length: value.length },
1987
+ (_, index): Value => ({
1988
+ kind: "code",
1989
+ text: mapped`${value.text}[${index}]`,
1990
+ declared,
1991
+ place: value.place,
1992
+ iec: value.elementIec,
1993
+ }),
1994
+ );
1995
+ }
1996
+ if (value.kind !== "static") {
1997
+ return undefined;
1998
+ }
1999
+ const array = value.node;
2000
+ const captured = array.captured;
2001
+ if (captured.kind !== "array") {
2002
+ return undefined;
2003
+ }
2004
+ return captured.items.map((item, index) =>
2005
+ this.context.storage.fromCaptured(item, array, { kind: "index", index }),
2006
+ );
2007
+ }
2008
+ }
2009
+
2010
+ /** Comparisons the dialect writes as TypeScript does. */
2011
+ const comparisonOperators = new Map<ts.SyntaxKind, string>([
2012
+ [ts.SyntaxKind.LessThanToken, "<"],
2013
+ [ts.SyntaxKind.LessThanEqualsToken, "<="],
2014
+ [ts.SyntaxKind.GreaterThanToken, ">"],
2015
+ [ts.SyntaxKind.GreaterThanEqualsToken, ">="],
2016
+ ]);
2017
+
2018
+ /** Arithmetic and bit operators the dialect writes as TypeScript does. */
2019
+ const arithmeticOperators = new Map<ts.SyntaxKind, string>([
2020
+ [ts.SyntaxKind.PlusToken, "+"],
2021
+ [ts.SyntaxKind.MinusToken, "-"],
2022
+ [ts.SyntaxKind.AsteriskToken, "*"],
2023
+ [ts.SyntaxKind.SlashToken, "/"],
2024
+ [ts.SyntaxKind.PercentToken, "%"],
2025
+ [ts.SyntaxKind.AmpersandToken, "&"],
2026
+ [ts.SyntaxKind.BarToken, "|"],
2027
+ [ts.SyntaxKind.CaretToken, "^"],
2028
+ [ts.SyntaxKind.LessThanLessThanToken, "<<"],
2029
+ [ts.SyntaxKind.GreaterThanGreaterThanToken, ">>"],
2030
+ ]);
2031
+
2032
+ const foldNumber = (
2033
+ kind: ts.SyntaxKind,
2034
+ left: number,
2035
+ right: number,
2036
+ ): number | boolean | undefined => {
2037
+ switch (kind) {
2038
+ case ts.SyntaxKind.PlusToken:
2039
+ return left + right;
2040
+ case ts.SyntaxKind.MinusToken:
2041
+ return left - right;
2042
+ case ts.SyntaxKind.AsteriskToken:
2043
+ return left * right;
2044
+ case ts.SyntaxKind.AsteriskAsteriskToken:
2045
+ return left ** right;
2046
+ case ts.SyntaxKind.SlashToken:
2047
+ return left / right;
2048
+ case ts.SyntaxKind.PercentToken:
2049
+ return right === 0 ? undefined : left % right;
2050
+ case ts.SyntaxKind.LessThanToken:
2051
+ return left < right;
2052
+ case ts.SyntaxKind.LessThanEqualsToken:
2053
+ return left <= right;
2054
+ case ts.SyntaxKind.GreaterThanToken:
2055
+ return left > right;
2056
+ case ts.SyntaxKind.GreaterThanEqualsToken:
2057
+ return left >= right;
2058
+ default:
2059
+ return undefined;
2060
+ }
2061
+ };
2062
+
2063
+ const mathConstants = new Map([
2064
+ ["E", Math.E],
2065
+ ["LN10", Math.LN10],
2066
+ ["LN2", Math.LN2],
2067
+ ["LOG10E", Math.LOG10E],
2068
+ ["LOG2E", Math.LOG2E],
2069
+ ["PI", Math.PI],
2070
+ ["SQRT1_2", Math.SQRT1_2],
2071
+ ["SQRT2", Math.SQRT2],
2072
+ ]);
2073
+
2074
+ /** A function as its source names it, for a message: `Class.method`, or the function's name. */
2075
+ const sourceName = (target: Extract<Value, { kind: "function" }>): string => {
2076
+ const own = target.declaration.name?.getText() ?? "this function";
2077
+ return target.self?.captured.kind === "instance"
2078
+ ? `${target.self.captured.name}.${own}`
2079
+ : own;
2080
+ };
2081
+
2082
+ /** Whether a call is a `.then` or `.catch` link on a promise. */
2083
+ export const isPromiseLink = (node: ts.Node): node is ts.CallExpression =>
2084
+ ts.isCallExpression(node) &&
2085
+ ts.isPropertyAccessExpression(node.expression) &&
2086
+ promiseLinks.has(node.expression.name.text);
2087
+
2088
+ const promiseLinks: ReadonlySet<string> = new Set(["then", "catch"]);
2089
+
2090
+ /** Whether an expression is the promise a `.then` or `.catch` link is called on. */
2091
+ const linksPromise = (node: ts.Node): boolean =>
2092
+ ts.isPropertyAccessExpression(node.parent) &&
2093
+ node.parent.expression === node &&
2094
+ isPromiseLink(node.parent.parent);
2095
+
2096
+ /** The function, or else the module, a name is declared in. */
2097
+ const scopeOf = (name: ts.Identifier): ts.Node =>
2098
+ ts.findAncestor(name.parent, ts.isFunctionLike) ?? name.getSourceFile();
2099
+
2100
+ const getterNamed = (
2101
+ members: readonly ts.ClassElement[],
2102
+ name: string,
2103
+ ): ts.GetAccessorDeclaration | undefined =>
2104
+ members.find(
2105
+ (member): member is ts.GetAccessorDeclaration =>
2106
+ ts.isGetAccessorDeclaration(member) && member.name.getText() === name,
2107
+ );
2108
+
2109
+ const methodNamed = (
2110
+ members: readonly ts.ClassElement[],
2111
+ name: string,
2112
+ ): ts.MethodDeclaration | undefined =>
2113
+ members.find(
2114
+ (member): member is ts.MethodDeclaration =>
2115
+ ts.isMethodDeclaration(member) && member.name.getText() === name,
2116
+ );
2117
+
2118
+ /** A readonly array or record: what holds it can't change it, so a literal given to it stays a value. */
2119
+ const isReadonly = (type: ts.Type, checker: ts.TypeChecker): boolean =>
2120
+ (!checker.isArrayType(type) && type.getSymbol()?.name === "ReadonlyArray") ||
2121
+ type.aliasSymbol?.name === "Readonly" ||
2122
+ checker.typeToString(type).startsWith("readonly ");
2123
+
2124
+ /** The arrow or function expression written at `start`. */
2125
+ const findClosure = (
2126
+ source: ts.SourceFile,
2127
+ start: number,
2128
+ ): ts.ArrowFunction | ts.FunctionExpression | undefined => {
2129
+ const visit = (
2130
+ node: ts.Node,
2131
+ ): ts.ArrowFunction | ts.FunctionExpression | undefined => {
2132
+ if (
2133
+ (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) &&
2134
+ node.getStart(source) === start
2135
+ ) {
2136
+ return node;
2137
+ }
2138
+ return node.pos <= start && start < node.end
2139
+ ? ts.forEachChild(node, visit)
2140
+ : undefined;
2141
+ };
2142
+ return visit(source);
2143
+ };
2144
+
2145
+ /** The symbols a closure's identifiers read, by name; a shorthand property reads its value's. */
2146
+ const closureSymbols = (
2147
+ declaration: ts.Node,
2148
+ checker: ts.TypeChecker,
2149
+ ): ReadonlyMap<string, ts.Symbol[]> => {
2150
+ const found = new Map<string, ts.Symbol[]>();
2151
+ const visit = (node: ts.Node): void => {
2152
+ if (ts.isIdentifier(node)) {
2153
+ const symbol = valueSymbol(checker, node);
2154
+ const known = found.get(node.text) ?? [];
2155
+ if (symbol && !known.includes(symbol)) {
2156
+ found.set(node.text, [...known, symbol]);
2157
+ }
2158
+ }
2159
+ ts.forEachChild(node, visit);
2160
+ };
2161
+ visit(declaration);
2162
+ return found;
2163
+ };
2164
+
2165
+ /** The expression a getter's body is no more than `return`ing. */
2166
+ const onlyReturned = (
2167
+ accessor: ts.GetAccessorDeclaration,
2168
+ ): ts.Expression | undefined => {
2169
+ const [only, ...others] = accessor.body?.statements ?? [];
2170
+ return only && !others.length && ts.isReturnStatement(only)
2171
+ ? only.expression
2172
+ : undefined;
2173
+ };
2174
+
2175
+ /** Whether reading a value's text again reads the same places and runs nothing: no call besides a conversion. */
2176
+ const pureRead = (text: string | Mapped): boolean =>
2177
+ !/[\w\]>]\s*\(/.test(String(text).replace(/\b(?:wrap|exact)<\w+>\(/g, "("));