@tsplc/compiler 0.5.13 → 0.5.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (263) hide show
  1. package/README.md +33 -8
  2. package/dist/cli.js +794 -621
  3. package/dist/cli.js.map +19 -16
  4. package/dist/clock.js +5 -2
  5. package/dist/clock.js.map +5 -4
  6. package/dist/codesys.js +4162 -4157
  7. package/dist/codesys.js.map +43 -29
  8. package/dist/index.js +7852 -6549
  9. package/dist/index.js.map +53 -50
  10. package/dist/ir.js +2482 -2277
  11. package/dist/ir.js.map +28 -25
  12. package/dist/retain.js +3 -1
  13. package/dist/retain.js.map +3 -3
  14. package/dist/signals.js +115 -0
  15. package/dist/signals.js.map +10 -0
  16. package/dist/telemetry.js +25 -20
  17. package/dist/telemetry.js.map +6 -6
  18. package/package.json +19 -39
  19. package/src/codesys/config.ts +3 -3
  20. package/src/codesys/debug.ts +92 -108
  21. package/src/codesys/emit.ts +100 -88
  22. package/src/codesys/endpoints.ts +111 -0
  23. package/src/codesys/engineering.ts +30 -54
  24. package/src/codesys/explain/expressions.ts +445 -0
  25. package/src/codesys/explain/flags.ts +134 -0
  26. package/src/codesys/explain/parameters.ts +53 -0
  27. package/src/codesys/explain/rows.ts +182 -0
  28. package/src/codesys/explain/tables.ts +79 -0
  29. package/src/codesys/explain/tasks.ts +68 -0
  30. package/src/codesys/explain/writes.ts +497 -0
  31. package/src/codesys/explain.ts +85 -1401
  32. package/src/codesys/expressions.ts +41 -33
  33. package/src/codesys/global-lists.ts +114 -94
  34. package/src/codesys/global-names.ts +12 -14
  35. package/src/codesys/http.ts +428 -388
  36. package/src/codesys/instrumentation.ts +142 -148
  37. package/src/codesys/io-paths.ts +31 -23
  38. package/src/codesys/loops.ts +101 -0
  39. package/src/codesys/manifest.ts +269 -269
  40. package/src/codesys/names.ts +10 -33
  41. package/src/codesys/numeric.ts +89 -42
  42. package/src/codesys/plan.ts +202 -190
  43. package/src/codesys/programs.ts +23 -16
  44. package/src/codesys/publication.ts +13 -86
  45. package/src/codesys/required.ts +8 -0
  46. package/src/codesys/routines.ts +103 -489
  47. package/src/codesys/scheduling.ts +96 -0
  48. package/src/codesys/service-channels.ts +23 -0
  49. package/src/codesys/sources.ts +34 -28
  50. package/src/codesys/st-files.ts +112 -105
  51. package/src/codesys/statements.ts +409 -0
  52. package/src/codesys/storage.ts +41 -23
  53. package/src/codesys/symbols.ts +130 -119
  54. package/src/codesys/task-access.ts +65 -221
  55. package/src/codesys/telemetry-settings.ts +19 -0
  56. package/src/codesys/telemetry.ts +185 -148
  57. package/src/codesys/types.ts +69 -109
  58. package/src/codesys/vendor.ts +13 -50
  59. package/src/frontend/analyzer.ts +66 -111
  60. package/src/frontend/async.ts +316 -128
  61. package/src/frontend/blocks.ts +178 -154
  62. package/src/frontend/configuration.ts +49 -153
  63. package/src/frontend/const-functions.ts +50 -40
  64. package/src/frontend/control-flow.ts +164 -129
  65. package/src/frontend/cooperative.ts +17 -9
  66. package/src/frontend/coroutines.ts +539 -441
  67. package/src/frontend/dialect-names.ts +104 -0
  68. package/src/frontend/elaborate/array-searches.ts +77 -69
  69. package/src/frontend/elaborate/assignments.ts +68 -77
  70. package/src/frontend/elaborate/calls.ts +878 -512
  71. package/src/frontend/elaborate/capture-protocol.ts +118 -21
  72. package/src/frontend/elaborate/capture.ts +196 -109
  73. package/src/frontend/elaborate/declarations.ts +124 -0
  74. package/src/frontend/elaborate/dialect.ts +119 -46
  75. package/src/frontend/elaborate/expressions.ts +763 -442
  76. package/src/frontend/elaborate/filtered-arrays.ts +127 -91
  77. package/src/frontend/elaborate/frame.ts +50 -2
  78. package/src/frontend/elaborate/generics.ts +20 -34
  79. package/src/frontend/elaborate/graph.ts +13 -87
  80. package/src/frontend/elaborate/imports.ts +0 -5
  81. package/src/frontend/elaborate/index.ts +416 -169
  82. package/src/frontend/elaborate/initializers.ts +64 -42
  83. package/src/frontend/elaborate/iterators.ts +228 -364
  84. package/src/frontend/elaborate/layouts.ts +477 -116
  85. package/src/frontend/elaborate/model.ts +113 -55
  86. package/src/frontend/elaborate/references.ts +116 -138
  87. package/src/frontend/elaborate/retention.ts +137 -59
  88. package/src/frontend/elaborate/specialize.ts +617 -308
  89. package/src/frontend/elaborate/statements.ts +436 -247
  90. package/src/frontend/elaborate/storage.ts +280 -213
  91. package/src/frontend/elaborate/time-constructors.ts +34 -0
  92. package/src/frontend/elaborate/values.ts +77 -7
  93. package/src/frontend/elaborate/writes.ts +98 -84
  94. package/src/frontend/expressions.ts +149 -151
  95. package/src/frontend/generated-names.ts +3 -3
  96. package/src/frontend/intrinsics.ts +31 -17
  97. package/src/frontend/lowering-key.ts +23 -0
  98. package/src/frontend/module-graph.ts +105 -43
  99. package/src/frontend/positions.ts +43 -35
  100. package/src/frontend/promise-chains.ts +226 -266
  101. package/src/frontend/promises.ts +88 -67
  102. package/src/frontend/routines.ts +122 -65
  103. package/src/frontend/sdk.ts +104 -5
  104. package/src/frontend/services.ts +149 -102
  105. package/src/frontend/statements.ts +60 -64
  106. package/src/frontend/tasks.ts +151 -96
  107. package/src/frontend/telemetry.ts +1 -1
  108. package/src/frontend/types.ts +366 -181
  109. package/src/frontend/typescript.ts +239 -112
  110. package/src/index.ts +2 -1
  111. package/src/ir/aggregates.ts +90 -75
  112. package/src/ir/allocation.ts +29 -18
  113. package/src/ir/conditions.ts +38 -78
  114. package/src/ir/core-model.ts +128 -11
  115. package/src/ir/declarations.ts +18 -32
  116. package/src/ir/diagnostics.ts +25 -18
  117. package/src/ir/domains.ts +26 -23
  118. package/src/ir/fold.ts +55 -50
  119. package/src/ir/identity.ts +10 -0
  120. package/src/ir/index.ts +31 -7
  121. package/src/ir/job-errors.ts +30 -8
  122. package/src/ir/layouts.ts +63 -34
  123. package/src/ir/link.ts +11 -46
  124. package/src/ir/model.ts +25 -6
  125. package/src/ir/normalize.ts +3 -28
  126. package/src/ir/numeric.ts +45 -18
  127. package/src/ir/operands.ts +102 -0
  128. package/src/ir/ranges.ts +242 -67
  129. package/src/ir/routine.ts +126 -183
  130. package/src/ir/scalars.ts +29 -25
  131. package/src/ir/share.ts +323 -343
  132. package/src/ir/short-circuit.ts +140 -0
  133. package/src/ir/tables.ts +111 -0
  134. package/src/ir/temporaries.ts +15 -113
  135. package/src/ir/types.ts +32 -8
  136. package/src/project/artifacts.ts +143 -71
  137. package/src/project/cli.ts +104 -87
  138. package/src/project/debugger.ts +48 -34
  139. package/src/project/deployments.ts +12 -68
  140. package/src/project/flags.ts +14 -0
  141. package/src/project/plant.ts +293 -225
  142. package/src/project/project-commands.ts +254 -192
  143. package/src/project/project.ts +184 -141
  144. package/src/project/release.ts +22 -28
  145. package/src/project/server.ts +22 -26
  146. package/src/project/terminal.ts +13 -2
  147. package/src/runtime/async.ts +17 -13
  148. package/src/runtime/launch.ts +5 -2
  149. package/src/runtime/main.ts +8 -3
  150. package/src/runtime/missing-file.ts +3 -0
  151. package/src/runtime/process.ts +24 -19
  152. package/src/runtime/program.ts +20 -53
  153. package/src/runtime/retain.ts +18 -10
  154. package/src/runtime/runtime.ts +47 -60
  155. package/src/runtime/settings.ts +27 -0
  156. package/src/runtime/storage.ts +49 -74
  157. package/src/runtime/symbols.ts +19 -75
  158. package/src/runtime/telemetry.ts +37 -14
  159. package/src/runtime/transport.ts +26 -30
  160. package/stdlib/clock.ts +4 -2
  161. package/stdlib/plc-time.ts +2 -0
  162. package/stdlib/retain.ts +2 -0
  163. package/stdlib/signals.ts +142 -0
  164. package/stdlib/telemetry.ts +5 -12
  165. package/types/dialect.d.ts +49 -0
  166. package/types/globals.d.ts +2 -42
  167. package/types/index.d.ts +3 -1
  168. package/types/retain.d.ts +8 -2
  169. package/types/telemetry.d.ts +3 -0
  170. package/dist/bun-runtime.js +0 -1472
  171. package/dist/bun-runtime.js.map +0 -26
  172. package/dist/elaborate-capture.js +0 -304
  173. package/dist/elaborate-capture.js.map +0 -11
  174. package/dist/math.js +0 -24
  175. package/dist/math.js.map +0 -10
  176. package/dist/project.js +0 -626
  177. package/dist/project.js.map +0 -12
  178. package/dist/server-check.js +0 -59
  179. package/dist/server-check.js.map +0 -11
  180. package/src/frontend/exposure.ts +0 -181
  181. package/src/project/index.ts +0 -6
  182. package/src/runtime/.runtime-65O4JH/server/router.ts +0 -17
  183. package/src/runtime/.runtime-65O4JH/src/cell.ts +0 -45
  184. package/src/runtime/.runtime-65O4JH/src/controller.ts +0 -58
  185. package/src/runtime/.runtime-65O4JH/src/lane.ts +0 -6
  186. package/src/runtime/.runtime-65O4JH/src/main.ts +0 -11
  187. package/src/runtime/.runtime-65O4JH/src/services.ts +0 -8
  188. package/src/runtime/.runtime-65O4JH/tsconfig.json +0 -13
  189. package/src/runtime/.runtime-65O4JH/tsplc.config.ts +0 -31
  190. package/src/runtime/.runtime-Brw2kO/server/router.ts +0 -17
  191. package/src/runtime/.runtime-Brw2kO/src/cell.ts +0 -45
  192. package/src/runtime/.runtime-Brw2kO/src/controller.ts +0 -58
  193. package/src/runtime/.runtime-Brw2kO/src/lane.ts +0 -6
  194. package/src/runtime/.runtime-Brw2kO/src/main.ts +0 -11
  195. package/src/runtime/.runtime-Brw2kO/src/services.ts +0 -8
  196. package/src/runtime/.runtime-Brw2kO/tsconfig.json +0 -13
  197. package/src/runtime/.runtime-Brw2kO/tsplc.config.ts +0 -31
  198. package/src/runtime/.runtime-NHfu1D/server/router.ts +0 -17
  199. package/src/runtime/.runtime-NHfu1D/src/cell.ts +0 -45
  200. package/src/runtime/.runtime-NHfu1D/src/controller.ts +0 -58
  201. package/src/runtime/.runtime-NHfu1D/src/lane.ts +0 -6
  202. package/src/runtime/.runtime-NHfu1D/src/main.ts +0 -11
  203. package/src/runtime/.runtime-NHfu1D/src/services.ts +0 -8
  204. package/src/runtime/.runtime-NHfu1D/tsconfig.json +0 -13
  205. package/src/runtime/.runtime-NHfu1D/tsplc.config.ts +0 -31
  206. package/src/runtime/.runtime-VaUSOu/server/router.ts +0 -17
  207. package/src/runtime/.runtime-VaUSOu/src/cell.ts +0 -45
  208. package/src/runtime/.runtime-VaUSOu/src/controller.ts +0 -58
  209. package/src/runtime/.runtime-VaUSOu/src/lane.ts +0 -6
  210. package/src/runtime/.runtime-VaUSOu/src/main.ts +0 -11
  211. package/src/runtime/.runtime-VaUSOu/src/services.ts +0 -8
  212. package/src/runtime/.runtime-VaUSOu/tsconfig.json +0 -13
  213. package/src/runtime/.runtime-VaUSOu/tsplc.config.ts +0 -31
  214. package/src/runtime/.runtime-WbtNvR/server/router.ts +0 -17
  215. package/src/runtime/.runtime-WbtNvR/src/cell.ts +0 -45
  216. package/src/runtime/.runtime-WbtNvR/src/controller.ts +0 -58
  217. package/src/runtime/.runtime-WbtNvR/src/lane.ts +0 -6
  218. package/src/runtime/.runtime-WbtNvR/src/main.ts +0 -11
  219. package/src/runtime/.runtime-WbtNvR/src/services.ts +0 -8
  220. package/src/runtime/.runtime-WbtNvR/tsconfig.json +0 -13
  221. package/src/runtime/.runtime-WbtNvR/tsplc.config.ts +0 -31
  222. package/src/runtime/.runtime-opcua-GMPUt8/server/router.ts +0 -17
  223. package/src/runtime/.runtime-opcua-GMPUt8/src/cell.ts +0 -45
  224. package/src/runtime/.runtime-opcua-GMPUt8/src/controller.ts +0 -58
  225. package/src/runtime/.runtime-opcua-GMPUt8/src/lane.ts +0 -6
  226. package/src/runtime/.runtime-opcua-GMPUt8/src/main.ts +0 -11
  227. package/src/runtime/.runtime-opcua-GMPUt8/src/services.ts +0 -8
  228. package/src/runtime/.runtime-opcua-GMPUt8/tsconfig.json +0 -13
  229. package/src/runtime/.runtime-opcua-GMPUt8/tsplc.config.ts +0 -31
  230. package/src/runtime/.runtime-opcua-UwafxO/server/router.ts +0 -17
  231. package/src/runtime/.runtime-opcua-UwafxO/src/cell.ts +0 -45
  232. package/src/runtime/.runtime-opcua-UwafxO/src/controller.ts +0 -58
  233. package/src/runtime/.runtime-opcua-UwafxO/src/lane.ts +0 -6
  234. package/src/runtime/.runtime-opcua-UwafxO/src/main.ts +0 -11
  235. package/src/runtime/.runtime-opcua-UwafxO/src/services.ts +0 -8
  236. package/src/runtime/.runtime-opcua-UwafxO/tsconfig.json +0 -13
  237. package/src/runtime/.runtime-opcua-UwafxO/tsplc.config.ts +0 -31
  238. package/src/runtime/.runtime-opcua-ecaSee/server/router.ts +0 -17
  239. package/src/runtime/.runtime-opcua-ecaSee/src/cell.ts +0 -45
  240. package/src/runtime/.runtime-opcua-ecaSee/src/controller.ts +0 -58
  241. package/src/runtime/.runtime-opcua-ecaSee/src/lane.ts +0 -6
  242. package/src/runtime/.runtime-opcua-ecaSee/src/main.ts +0 -11
  243. package/src/runtime/.runtime-opcua-ecaSee/src/services.ts +0 -8
  244. package/src/runtime/.runtime-opcua-ecaSee/tsconfig.json +0 -13
  245. package/src/runtime/.runtime-opcua-ecaSee/tsplc.config.ts +0 -31
  246. package/src/runtime/.runtime-opcua-y91UCm/server/router.ts +0 -17
  247. package/src/runtime/.runtime-opcua-y91UCm/src/cell.ts +0 -45
  248. package/src/runtime/.runtime-opcua-y91UCm/src/controller.ts +0 -58
  249. package/src/runtime/.runtime-opcua-y91UCm/src/lane.ts +0 -6
  250. package/src/runtime/.runtime-opcua-y91UCm/src/main.ts +0 -11
  251. package/src/runtime/.runtime-opcua-y91UCm/src/services.ts +0 -8
  252. package/src/runtime/.runtime-opcua-y91UCm/tsconfig.json +0 -13
  253. package/src/runtime/.runtime-opcua-y91UCm/tsplc.config.ts +0 -31
  254. package/src/runtime/.runtime-ybIxYh/server/router.ts +0 -17
  255. package/src/runtime/.runtime-ybIxYh/src/cell.ts +0 -45
  256. package/src/runtime/.runtime-ybIxYh/src/controller.ts +0 -58
  257. package/src/runtime/.runtime-ybIxYh/src/lane.ts +0 -6
  258. package/src/runtime/.runtime-ybIxYh/src/main.ts +0 -11
  259. package/src/runtime/.runtime-ybIxYh/src/services.ts +0 -8
  260. package/src/runtime/.runtime-ybIxYh/tsconfig.json +0 -13
  261. package/src/runtime/.runtime-ybIxYh/tsplc.config.ts +0 -31
  262. package/stdlib/math.ts +0 -23
  263. package/types/plc.d.ts +0 -4
@@ -1,27 +1,52 @@
1
- // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
2
- import { identityDigest } from "@tsplc/compiler/ir";
1
+ import {
2
+ constantFits,
3
+ identityDigest,
4
+ integerType,
5
+ literalOutsideType,
6
+ optionalRecord,
7
+ primitiveTypes,
8
+ } from "@tsplc/compiler/ir";
3
9
  import ts from "typescript";
4
10
  import { from, joined, type Mapped, mapped, type Part } from "../positions";
5
- import { unaliased } from "../sdk";
11
+ import { sdkModules, unaliased, valueSymbol } from "../sdk";
12
+ import { defaultNumericTypes } from "../types";
6
13
  import { AssignmentSpecializer, containsWrite } from "./assignments";
7
- import { CallSpecializer } from "./calls";
8
- import type { CapturedValue } from "./capture-protocol";
14
+ import { CallSpecializer, floatIec } from "./calls";
15
+ import {
16
+ isGlobal,
17
+ namedElements,
18
+ namedFields,
19
+ parameterDefault,
20
+ symbolOf,
21
+ } from "./declarations";
9
22
  import type { DialectText } from "./dialect";
10
23
  import { FilteredArrays } from "./filtered-arrays";
11
- import type { Frame } from "./frame";
24
+ import type { Emitter, Frame } from "./frame";
12
25
  import type { EntryImports } from "./imports";
13
26
  import type { Initializers } from "./initializers";
14
27
  import { Iterators } from "./iterators";
15
- import { isAbsent, type Layouts, recordTypes } from "./layouts";
28
+ import {
29
+ type ArrayLayout,
30
+ arrayLayout,
31
+ isAbsent,
32
+ type Layouts,
33
+ optionalValue,
34
+ recordTypes,
35
+ } from "./layouts";
16
36
  import type { Model, ModelNode } from "./model";
17
37
  import { References, referenceType } from "./references";
18
38
  import type { Storage } from "./storage";
19
39
  import {
40
+ capturedPrimitive,
20
41
  constant,
21
42
  type Env,
22
43
  type FunctionLike,
44
+ finite,
45
+ holdsSetupObjects,
23
46
  repeatable,
47
+ restoring,
24
48
  SpecializeError,
49
+ unwrapped,
25
50
  type Value,
26
51
  } from "./values";
27
52
  import {
@@ -45,6 +70,8 @@ export interface SpecializeContext {
45
70
  sdkFile: string;
46
71
  /** The program's runtime sources, where the functions setup stored are declared. */
47
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;
48
75
  }
49
76
 
50
77
  /** A call to a specialized routine: its name, the runtime arguments it takes and its result type. */
@@ -55,7 +82,7 @@ export interface RoutineCall {
55
82
  /** The IEC width the routine's declaration gives its result, as `(): UINT` does. */
56
83
  iec?: string;
57
84
  /** An array result's layout, at the length the routine returns. */
58
- layout?: string;
85
+ layout?: ArrayLayout;
59
86
  length?: number;
60
87
  /** Whether the routine returns stored state, which its caller gets a copy of. */
61
88
  returnsStored?: boolean;
@@ -69,8 +96,36 @@ export interface RoutineTable {
69
96
  declaration: FunctionLike,
70
97
  self: ModelNode | undefined,
71
98
  args: Value[],
72
- closure?: Env,
99
+ closure?: Closure,
73
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;
74
129
  }
75
130
 
76
131
  /** Evaluates expressions against the setup graph, and writes what remains as dialect text. */
@@ -83,25 +138,11 @@ export class ExpressionSpecializer {
83
138
  private readonly services = new Map<string, ModelNode>();
84
139
  private readonly tables = new Map<number, string>();
85
140
  readonly tableDeclarations: Mapped[] = [];
86
- private readonly model: Model;
87
- private readonly checker: ts.TypeChecker;
88
- private readonly dialect: DialectText;
89
- private readonly layouts: Layouts;
90
- private readonly storage: Storage;
91
- private readonly initializers: Initializers;
92
- private readonly imports: EntryImports;
93
141
 
94
142
  constructor(
95
- context: SpecializeContext,
143
+ private readonly context: SpecializeContext,
96
144
  private readonly routineTable: RoutineTable,
97
145
  ) {
98
- this.model = context.model;
99
- this.checker = context.checker;
100
- this.imports = context.imports;
101
- this.dialect = context.dialect;
102
- this.layouts = context.layouts;
103
- this.storage = context.storage;
104
- this.initializers = context.initializers;
105
146
  this.calls = new CallSpecializer(context, this);
106
147
  this.assignments = new AssignmentSpecializer(context, this);
107
148
  this.references = new References(context, this);
@@ -126,13 +167,16 @@ export class ExpressionSpecializer {
126
167
  frame: Frame,
127
168
  expected?: ts.Type,
128
169
  ): Value {
129
- if (
130
- ts.isParenthesizedExpression(node) ||
131
- ts.isNonNullExpression(node) ||
132
- ts.isAsExpression(node) ||
133
- ts.isSatisfiesExpression(node)
134
- ) {
135
- return this.expression(node.expression, frame, expected);
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);
136
180
  }
137
181
  if (ts.isNumericLiteral(node)) {
138
182
  return constant(Number(node.text));
@@ -163,20 +207,27 @@ export class ExpressionSpecializer {
163
207
  return this.identifier(node, frame);
164
208
  }
165
209
  if (ts.isPropertyAccessExpression(node)) {
166
- const member = this.checker.getSymbolAtLocation(
210
+ const member = this.context.checker.getSymbolAtLocation(
167
211
  node.name,
168
212
  )?.valueDeclaration;
169
213
  if (member && ts.isEnumMember(member)) {
170
- return constant(this.checker.getConstantValue(member));
214
+ return constant(this.context.checker.getConstantValue(member));
171
215
  }
172
216
  if (node.expression.kind === ts.SyntaxKind.SuperKeyword) {
173
217
  return this.superMember(node, frame);
174
218
  }
175
- if (this.isMathConstant(node)) {
176
- return constant(mathConstants.get(node.name.text));
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);
177
225
  }
178
- if (node.name.text === "length" && this.calls.isFilter(node.expression)) {
179
- return this.calls.count(node.expression, frame);
226
+ if (
227
+ node.name.text === "length" &&
228
+ this.filteredArrays.isFilter(node.expression)
229
+ ) {
230
+ return this.filteredArrays.count(node.expression, frame);
180
231
  }
181
232
  return this.property(
182
233
  this.expression(node.expression, frame),
@@ -194,10 +245,15 @@ export class ExpressionSpecializer {
194
245
  }
195
246
  if (ts.isAwaitExpression(node)) {
196
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
+ }
197
252
  return {
198
253
  kind: "code",
199
- text: mapped`await ${this.dialect.code(value, undefined)}`,
200
- declared: this.checker.getTypeAtLocation(node),
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,
201
257
  awaited: true,
202
258
  };
203
259
  }
@@ -222,10 +278,10 @@ export class ExpressionSpecializer {
222
278
  expected,
223
279
  );
224
280
  }
225
- const own = this.checker.getTypeAtLocation(node);
281
+ const own = this.context.checker.getTypeAtLocation(node);
226
282
  if (referenceType(own)) {
227
283
  return this.references.branch(
228
- this.dialect.condition(condition, node.condition),
284
+ this.context.dialect.condition(condition, node.condition),
229
285
  [
230
286
  () => this.expression(node.whenTrue, frame),
231
287
  () => this.expression(node.whenFalse, frame),
@@ -238,8 +294,8 @@ export class ExpressionSpecializer {
238
294
  const declared =
239
295
  expected &&
240
296
  !(
241
- this.layouts.isOptionalRecord(expected) &&
242
- !this.layouts.isOptionalRecord(own)
297
+ this.context.layouts.isOptionalRecord(expected) &&
298
+ !this.context.layouts.isOptionalRecord(own)
243
299
  )
244
300
  ? expected
245
301
  : own;
@@ -250,7 +306,7 @@ export class ExpressionSpecializer {
250
306
  ) {
251
307
  return this.branched(
252
308
  declared,
253
- this.dialect.condition(condition, node.condition),
309
+ this.context.dialect.condition(condition, node.condition),
254
310
  [node.whenTrue, node.whenFalse],
255
311
  frame,
256
312
  );
@@ -259,8 +315,7 @@ export class ExpressionSpecializer {
259
315
  const whenFalse = this.expression(node.whenFalse, frame, declared);
260
316
  return {
261
317
  kind: "code",
262
- // Each branch is stored into the choice's type, so a defined value in an optional is wrapped.
263
- text: mapped`(${this.dialect.condition(condition, node.condition)} ? ${this.dialect.assignmentText(whenTrue, declared)} : ${this.dialect.assignmentText(whenFalse, declared)})`,
318
+ text: mapped`(${this.context.dialect.condition(condition, node.condition)} ? ${this.context.dialect.assignmentText(whenTrue, declared, undefined)} : ${this.context.dialect.assignmentText(whenFalse, declared, undefined)})`,
264
319
  declared,
265
320
  copyOf: [whenTrue, whenFalse].find(
266
321
  (branch): branch is Value & { kind: "code" } =>
@@ -323,9 +378,29 @@ export class ExpressionSpecializer {
323
378
  node.questionDotToken &&
324
379
  object.kind === "code" &&
325
380
  object.declared &&
326
- this.layouts.isOptionalRecord(object.declared)
381
+ this.context.layouts.isOptionalRecord(object.declared)
327
382
  ) {
328
- return this.optionalMember(object, node, frame);
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
+ );
329
404
  }
330
405
  return this.narrowed(
331
406
  this.member(object, node.name.text, node, frame),
@@ -337,15 +412,12 @@ export class ExpressionSpecializer {
337
412
  if (node.text === "undefined") {
338
413
  return constant(undefined);
339
414
  }
340
- const symbol = this.checker.getSymbolAtLocation(node);
341
- if (!symbol) {
342
- throw new SpecializeError(node, `${node.text} is not declared.`);
343
- }
415
+ const symbol = symbolOf(this.context.checker, node);
344
416
  const local = frame.env.get(symbol);
345
417
  if (local) {
346
418
  return this.narrowed(local, node);
347
419
  }
348
- const target = unaliased(this.checker, symbol);
420
+ const target = unaliased(this.context.checker, symbol);
349
421
  const own = frame.env.get(target);
350
422
  if (own) {
351
423
  return own;
@@ -357,42 +429,43 @@ export class ExpressionSpecializer {
357
429
  if (ts.isFunctionDeclaration(declaration)) {
358
430
  return { kind: "function", declaration };
359
431
  }
360
- if (ts.isVariableDeclaration(declaration)) {
361
- const initializer = declaration.initializer;
362
- if (
363
- initializer &&
364
- (ts.isArrowFunction(initializer) ||
365
- ts.isFunctionExpression(initializer))
366
- ) {
367
- return { kind: "function", declaration: initializer };
368
- }
369
- const root = this.model.roots.find(
370
- (item) => item.declaration === declaration,
371
- );
372
- if (root) {
373
- return this.storage.rootValue(root);
374
- }
375
- if (
376
- ts.isVariableStatement(declaration.parent.parent) &&
377
- declaration.parent.parent.parent &&
378
- ts.isSourceFile(declaration.parent.parent.parent)
379
- ) {
380
- if (initializer) {
381
- return this.expression(initializer, { ...frame, env: new Map() });
382
- }
383
- }
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 };
384
439
  }
385
- // A module constant named by a destructuring declaration is a root of its own.
386
- if (ts.isBindingElement(declaration)) {
387
- const root = this.model.roots.find(
388
- (item) => item.declaration === declaration,
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,
389
450
  );
390
- if (root) {
391
- return this.storage.rootValue(root);
392
- }
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() });
393
460
  }
394
461
  if (ts.isEnumMember(declaration)) {
395
- return constant(this.checker.getConstantValue(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
+ );
396
469
  }
397
470
  throw new SpecializeError(
398
471
  node,
@@ -422,12 +495,10 @@ export class ExpressionSpecializer {
422
495
  };
423
496
  }
424
497
  if (captured.kind === "instance") {
425
- const members = this.model.members(this.model.classOf(node));
426
- const accessor = members.find(
427
- (member): member is ts.GetAccessorDeclaration =>
428
- ts.isGetAccessorDeclaration(member) &&
429
- member.name.getText() === name,
498
+ const members = this.context.model.members(
499
+ this.context.model.classOf(node),
430
500
  );
501
+ const accessor = getterNamed(members, name);
431
502
  if (accessor) {
432
503
  // A getter that only returns an expression reads it in place, as a field is read, so one
433
504
  // naming an object setup built is that object rather than a routine's copy of it.
@@ -448,10 +519,7 @@ export class ExpressionSpecializer {
448
519
  frame,
449
520
  );
450
521
  }
451
- const method = members.find(
452
- (member): member is ts.MethodDeclaration =>
453
- ts.isMethodDeclaration(member) && member.name.getText() === name,
454
- );
522
+ const method = methodNamed(members, name);
455
523
  if (method) {
456
524
  return { kind: "function", declaration: method, self: node };
457
525
  }
@@ -468,7 +536,10 @@ export class ExpressionSpecializer {
468
536
  throw new SpecializeError(at, `${name} is not set during setup.`);
469
537
  }
470
538
  return this.references.field(
471
- this.storage.fromCaptured(field, node, { kind: "field", name }),
539
+ this.context.storage.fromCaptured(field, node, {
540
+ kind: "field",
541
+ name,
542
+ }),
472
543
  node,
473
544
  name,
474
545
  );
@@ -479,9 +550,8 @@ export class ExpressionSpecializer {
479
550
  if (name === "length" && object.items) {
480
551
  return constant(object.items.length);
481
552
  }
482
- const field = object.fields?.get(name);
483
- if (field) {
484
- return field;
553
+ if (object.fields) {
554
+ return object.fields.get(name) ?? constant(undefined);
485
555
  }
486
556
  throw new SpecializeError(at, `${name} is not set.`);
487
557
  }
@@ -490,8 +560,8 @@ export class ExpressionSpecializer {
490
560
  object.declared && this.fieldDeclared(object.declared, name, at);
491
561
  const property =
492
562
  object.declared &&
493
- this.checker.getPropertyOfType(
494
- this.checker.getNonNullableType(object.declared),
563
+ this.context.checker.getPropertyOfType(
564
+ this.context.checker.getNonNullableType(object.declared),
495
565
  name,
496
566
  );
497
567
  const pinnedObject = object.pinned;
@@ -505,66 +575,74 @@ export class ExpressionSpecializer {
505
575
  pinned: (pinFrame: Frame) =>
506
576
  this.member(pinnedObject(pinFrame), name, at, pinFrame),
507
577
  }),
508
- iec: this.layouts.iecName(property?.valueDeclaration),
509
- elementIec: this.layouts.elementIec(property?.valueDeclaration),
578
+ iec: this.context.layouts.iecName(property?.valueDeclaration),
579
+ elementIec: this.context.layouts.elementIec(property?.valueDeclaration),
510
580
  layout:
511
- property && declared && this.checker.isArrayType(declared)
512
- ? this.layouts.fieldText(property)
581
+ property && declared && this.context.checker.isArrayType(declared)
582
+ ? this.context.layouts.fieldArray(property)
513
583
  : undefined,
514
584
  };
515
585
  }
516
586
  if (object.kind === "const" && object.value === undefined) {
517
- throw new SpecializeError(at, `Reading ${name} of 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
+ );
518
591
  }
519
592
  throw new SpecializeError(at, `${name} cannot be read from this value.`);
520
593
  }
521
594
 
522
- /** An optional's value where TypeScript has narrowed out undefined, as `x` reads after `x !== undefined`. */
595
+ /** An optional's value, or a reference known defined, where TypeScript has narrowed out undefined, as `x` reads after `x !== undefined`. */
523
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
+ }
524
602
  if (
525
603
  value.kind !== "code" ||
526
604
  !value.declared ||
527
- !this.layouts.isOptionalRecord(value.declared)
605
+ !this.context.layouts.isOptionalRecord(value.declared) ||
606
+ !this.narrowedOut(at)
528
607
  ) {
529
608
  return value;
530
609
  }
531
- const type = this.checker.getTypeAtLocation(at);
532
- if (type.isUnion() && type.types.some(isAbsent)) {
533
- return value;
534
- }
535
- if (isAbsent(type)) {
536
- return value;
537
- }
538
610
  return {
539
611
  kind: "code",
540
- text: mapped`${value.text}.value`,
541
- declared: this.checker.getNonNullableType(value.declared),
612
+ text: optionalValue(value.text),
613
+ declared: this.context.checker.getNonNullableType(value.declared),
542
614
  place: value.place,
543
615
  copyOf: value.copyOf,
544
616
  };
545
617
  }
546
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
+
547
625
  /** The declared type of a field of a runtime record, through optionals and tagged unions. */
548
626
  private fieldDeclared(
549
627
  type: ts.Type,
550
628
  name: string,
551
629
  at: ts.Node,
552
630
  ): ts.Type | undefined {
553
- const defined = this.checker.getNonNullableType(type);
554
- const tagged = this.layouts.tagged(defined);
631
+ const defined = this.context.checker.getNonNullableType(type);
632
+ const tagged = this.context.layouts.tagged(defined);
555
633
  if (tagged) {
556
634
  return name === tagged.tag
557
- ? this.layouts.tagType(defined, tagged)
558
- : this.layouts.taggedFieldType(defined, tagged, name);
635
+ ? this.context.layouts.tagType(defined, tagged)
636
+ : this.context.layouts.taggedFieldType(defined, tagged, name);
559
637
  }
560
- const property = this.checker.getPropertyOfType(defined, name);
638
+ const property = this.context.checker.getPropertyOfType(defined, name);
561
639
  if (!property) {
562
640
  throw new SpecializeError(
563
641
  at,
564
- `${name} is not a field of ${this.checker.typeToString(type)}.`,
642
+ `${name} is not a field of ${this.context.checker.typeToString(type)}.`,
565
643
  );
566
644
  }
567
- return this.checker.getTypeOfSymbol(property);
645
+ return this.context.checker.getTypeOfSymbol(property);
568
646
  }
569
647
 
570
648
  private serviceNode(path: string): ModelNode {
@@ -609,7 +687,7 @@ export class ExpressionSpecializer {
609
687
  if (!item) {
610
688
  return constant(undefined);
611
689
  }
612
- return this.storage.fromCaptured(item, object.node, {
690
+ return this.context.storage.fromCaptured(item, object.node, {
613
691
  kind: "index",
614
692
  index: index.value,
615
693
  });
@@ -619,7 +697,7 @@ export class ExpressionSpecializer {
619
697
  if (!field) {
620
698
  return constant(undefined);
621
699
  }
622
- return this.storage.fromCaptured(field, object.node, {
700
+ return this.context.storage.fromCaptured(field, object.node, {
623
701
  kind: "field",
624
702
  name: String(index.value),
625
703
  });
@@ -627,18 +705,17 @@ export class ExpressionSpecializer {
627
705
  }
628
706
  if (object.kind === "static") {
629
707
  const node = object.node;
630
- // A runtime index into stored data, or into a fixed table of plain values.
631
708
  const declared =
632
709
  node.type &&
633
710
  (node.captured.kind === "array"
634
- ? this.model.elementType(node.type)
711
+ ? this.context.model.elementType(node.type)
635
712
  : recordTypes(node.type)?.value);
636
- const text = this.storage.storedNode(node)
637
- ? this.storage.pathText(node)
713
+ const text = this.context.storage.storedNode(node)
714
+ ? this.context.storage.pathText(node)
638
715
  : this.table(node, at);
639
716
  return {
640
717
  kind: "code",
641
- text: mapped`${text}[${this.dialect.code(index, node.type && recordTypes(node.type)?.key)}]`,
718
+ text: mapped`${text}[${this.context.dialect.code(index, node.type && recordTypes(node.type)?.key)}]`,
642
719
  declared,
643
720
  place: true,
644
721
  ...(index.kind === "code" && {
@@ -650,13 +727,13 @@ export class ExpressionSpecializer {
650
727
  if (object.kind === "code") {
651
728
  const declared =
652
729
  object.declared &&
653
- (this.model.elementType(object.declared) ??
730
+ (this.context.model.elementType(object.declared) ??
654
731
  recordTypes(object.declared)?.value);
655
732
  // A key setup fixed reads as a number; an enum-keyed record takes its enum's member.
656
733
  const key = object.declared && recordTypes(object.declared)?.key;
657
734
  return {
658
735
  kind: "code",
659
- text: mapped`${object.text}[${this.dialect.code(index, key)}]`,
736
+ text: mapped`${object.text}[${this.context.dialect.code(index, key)}]`,
660
737
  declared,
661
738
  place: object.place,
662
739
  iec: object.elementIec,
@@ -683,11 +760,11 @@ export class ExpressionSpecializer {
683
760
  if (chosen) {
684
761
  return chosen;
685
762
  }
686
- const text = this.materialize(object, at, frame);
763
+ const text = this.materialize(object.items, at, frame);
687
764
  return {
688
765
  kind: "code",
689
- text: mapped`${text}[${this.dialect.code(index, undefined)}]`,
690
- declared: this.checker.getTypeAtLocation(at),
766
+ text: mapped`${text}[${this.context.dialect.code(index, undefined)}]`,
767
+ declared: this.context.checker.getTypeAtLocation(at),
691
768
  };
692
769
  }
693
770
  throw new SpecializeError(at, "This value cannot be indexed.");
@@ -700,35 +777,45 @@ export class ExpressionSpecializer {
700
777
  return known;
701
778
  }
702
779
  if (!node.type) {
703
- throw new Error("A table needs a declared type.");
780
+ throw new SpecializeError(
781
+ at,
782
+ "This array has no declared type to index it by at run time.",
783
+ );
704
784
  }
705
785
  // Named for where setup put it: numbered by first read, two tables swapped names under one type.
706
- const identity = this.model.identity(node);
786
+ const identity = this.context.model.identity(node);
707
787
  const name = identity
708
788
  ? `tsplcTable_${identityDigest(identity)}`
709
789
  : `tsplcTable${this.tables.size + 1}`;
710
790
  this.tables.set(node.id, name);
711
- const type = this.layouts.text(node.type, { kind: "node", id: node.id });
791
+ const type = this.context.layouts.text(node.type, {
792
+ kind: "node",
793
+ id: node.id,
794
+ });
712
795
  this.tableDeclarations.push(
713
796
  from(
714
797
  at,
715
- `const ${name}: ${type} = ${this.initializers.valueText({ kind: "node", id: node.id }, node.type, type)};`,
798
+ `const ${name}: ${type} = ${this.context.initializers.valueText({ kind: "node", id: node.id }, node.type, type)};`,
716
799
  ),
717
800
  );
718
801
  return name;
719
802
  }
720
803
 
721
804
  /** Stores a scan-built array in a local, for indexing at runtime. */
722
- private materialize(value: Value, at: ts.Node, frame: Frame): string {
723
- const type = this.checker.getTypeAtLocation(at);
724
- const element = this.model.elementType(type);
725
- if (!element || value.kind !== "virtual" || !value.items) {
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) {
726
813
  throw new SpecializeError(at, "Not an array.");
727
814
  }
728
815
  const local = frame.emitter.temporary();
729
816
  frame.emitter.line(
730
- mapped`const ${local}: FixedArray<${this.layouts.text(element)}, ${Math.max(value.items.length, 1)}> = [${joined(
731
- value.items.map((item) => this.dialect.code(item, element)),
817
+ mapped`const ${local}: ${arrayLayout(this.context.layouts.text(element), items.length).text} = [${joined(
818
+ items.map((item) => this.context.dialect.code(item, element)),
732
819
  ", ",
733
820
  )}];`,
734
821
  );
@@ -744,18 +831,16 @@ export class ExpressionSpecializer {
744
831
  this.expression(
745
832
  property.initializer,
746
833
  frame,
747
- this.checker.getContextualType(property.initializer),
834
+ this.context.checker.getContextualType(property.initializer),
748
835
  ),
749
836
  );
750
837
  } else if (ts.isShorthandPropertyAssignment(property)) {
751
- const symbol = this.checker.getShorthandAssignmentValueSymbol(property);
752
- const local = symbol && frame.env.get(symbol);
753
- fields.set(
754
- property.name.text,
755
- local ?? this.expression(property.name, frame),
756
- );
838
+ fields.set(property.name.text, this.shorthand(property, frame));
757
839
  } else if (ts.isSpreadAssignment(property)) {
758
- for (const [name, value] of this.spreadFields(property, frame)) {
840
+ for (const [name, value] of this.recordFields(
841
+ property.expression,
842
+ frame,
843
+ )) {
759
844
  fields.set(name, value);
760
845
  }
761
846
  } else {
@@ -765,6 +850,13 @@ export class ExpressionSpecializer {
765
850
  return { kind: "virtual", fields };
766
851
  }
767
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
+
768
860
  private unary(node: ts.PrefixUnaryExpression, frame: Frame): Value {
769
861
  const operand = this.expression(node.operand, frame);
770
862
  switch (node.operator) {
@@ -777,8 +869,8 @@ export class ExpressionSpecializer {
777
869
  }
778
870
  return {
779
871
  kind: "code",
780
- text: mapped`!${this.dialect.condition(operand, node.operand)}`,
781
- declared: this.checker.getBooleanType(),
872
+ text: mapped`!${this.context.dialect.condition(operand, node.operand)}`,
873
+ declared: this.context.checker.getBooleanType(),
782
874
  };
783
875
  case ts.SyntaxKind.MinusToken:
784
876
  if (operand.kind === "const" && typeof operand.value === "number") {
@@ -786,8 +878,8 @@ export class ExpressionSpecializer {
786
878
  }
787
879
  return {
788
880
  kind: "code",
789
- text: mapped`-${this.dialect.code(operand, undefined)}`,
790
- declared: this.checker.getTypeAtLocation(node),
881
+ text: mapped`-${this.context.dialect.code(operand, undefined)}`,
882
+ declared: this.context.checker.getTypeAtLocation(node),
791
883
  };
792
884
  case ts.SyntaxKind.PlusToken:
793
885
  return operand;
@@ -830,10 +922,10 @@ export class ExpressionSpecializer {
830
922
  }
831
923
  if (
832
924
  left.kind === "choice" &&
833
- referenceType(this.checker.getTypeAtLocation(node))
925
+ referenceType(this.context.checker.getTypeAtLocation(node))
834
926
  ) {
835
927
  return this.references.branch(
836
- this.dialect.condition(left, node.left),
928
+ this.context.dialect.condition(left, node.left),
837
929
  [
838
930
  () => this.expression(node.right, frame, expected),
839
931
  () => constant(undefined),
@@ -854,103 +946,45 @@ export class ExpressionSpecializer {
854
946
  // The right operand's writes happen only when it is evaluated.
855
947
  const result = frame.emitter.temporary();
856
948
  frame.emitter.line(
857
- mapped`let ${result}: boolean = ${this.dialect.condition(left, node.left)};`,
949
+ mapped`let ${result}: boolean = ${this.context.dialect.condition(left, node.left)};`,
858
950
  );
859
951
  frame.emitter.open(and ? `if (${result}) {` : `if (!${result}) {`);
860
952
  const right = this.expression(node.right, frame, expected);
861
953
  frame.emitter.line(
862
- mapped`${result} = ${this.dialect.condition(right, node.right)};`,
954
+ mapped`${result} = ${this.context.dialect.condition(right, node.right)};`,
863
955
  );
864
956
  frame.emitter.close();
865
957
  return {
866
958
  kind: "code",
867
959
  text: result,
868
- declared: this.checker.getBooleanType(),
960
+ declared: this.context.checker.getBooleanType(),
869
961
  place: true,
870
962
  };
871
963
  }
872
964
  const right = this.expression(node.right, frame, expected);
873
- // A right operand known now decides by its truthiness, as a condition reads it.
874
965
  if (right.kind === "const") {
875
966
  if (Boolean(right.value) === and) {
876
967
  return {
877
968
  kind: "code",
878
- text: this.dialect.condition(left, node.left),
879
- declared: this.checker.getBooleanType(),
969
+ text: this.context.dialect.condition(left, node.left),
970
+ declared: this.context.checker.getBooleanType(),
880
971
  };
881
972
  }
882
973
  return constant(!and);
883
974
  }
884
975
  return {
885
976
  kind: "code",
886
- text: mapped`(${this.dialect.condition(left, node.left)} ${and ? "&&" : "||"} ${this.dialect.condition(right, node.right)})`,
887
- declared: this.checker.getBooleanType(),
977
+ text: mapped`(${this.context.dialect.condition(left, node.left)} ${and ? "&&" : "||"} ${this.context.dialect.condition(right, node.right)})`,
978
+ declared: this.context.checker.getBooleanType(),
888
979
  };
889
980
  }
890
981
  if (kind === ts.SyntaxKind.QuestionQuestionToken) {
891
- const left = this.expression(node.left, frame);
892
- if (left.kind === "const") {
893
- return left.value === undefined
894
- ? this.expression(node.right, frame, expected)
895
- : left;
896
- }
897
- if (left.kind === "static") {
898
- return left;
899
- }
900
- if (left.kind === "choice") {
901
- return this.references.fallback(
902
- left,
903
- () => this.expression(node.right, frame, expected),
904
- node,
905
- frame,
906
- );
907
- }
908
- const declared = left.kind === "code" ? left.declared : undefined;
909
- // A value that can't be undefined is its own result.
910
- if (declared && this.checker.getNonNullableType(declared) === declared) {
911
- return left;
912
- }
913
- // A record or array result is chosen by statements: PLC code loads one only into storage.
914
- if (
915
- declared &&
916
- (this.runsWhenNeeded(node.right, frame) ||
917
- this.isAggregate(this.checker.getNonNullableType(declared)))
918
- ) {
919
- const defined = this.checker.getNonNullableType(declared);
920
- // Read once to test and once to give, so a call on the left runs once, into a const.
921
- const held =
922
- left.kind === "code" && this.isAggregate(declared)
923
- ? this.temporaryOf(left, frame)
924
- : this.held(left, frame);
925
- return this.branched(
926
- defined,
927
- this.dialect.isUndefinedText(
928
- this.dialect.code(held, declared),
929
- declared,
930
- ),
931
- [
932
- node.right,
933
- () => ({
934
- kind: "code",
935
- text: mapped`${this.dialect.code(held, undefined)}${this.optionalValueSuffix(declared)}`,
936
- declared: defined,
937
- }),
938
- ],
939
- frame,
940
- );
941
- }
942
- // The left operand is read twice, so a call in it runs once, into a const.
943
- const once = left.kind === "code" ? this.temporaryOf(left, frame) : left;
944
- const right = this.expression(
982
+ return this.orElse(
983
+ this.expression(node.left, frame),
945
984
  node.right,
946
985
  frame,
947
- declared && this.checker.getNonNullableType(declared),
986
+ expected,
948
987
  );
949
- return {
950
- kind: "code",
951
- text: mapped`(${this.dialect.isUndefinedText(this.dialect.code(once, declared), declared)} ? ${this.dialect.code(right, declared && this.checker.getNonNullableType(declared))} : ${this.dialect.code(once, undefined)}${declared && this.layouts.isOptionalRecord(declared) ? ".value" : ""})`,
952
- declared: declared && this.checker.getNonNullableType(declared),
953
- };
954
988
  }
955
989
  if (isAssignment(kind)) {
956
990
  return this.assignments.assign(node, frame);
@@ -984,41 +1018,44 @@ export class ExpressionSpecializer {
984
1018
  ) {
985
1019
  const folded = foldNumber(kind, left.value, right.value);
986
1020
  if (folded !== undefined) {
987
- return constant(folded);
1021
+ return constant(finite(folded, node));
988
1022
  }
989
1023
  }
990
1024
  if (kind === ts.SyntaxKind.AsteriskAsteriskToken) {
991
- if (
992
- left.kind === "const" &&
993
- right.kind === "const" &&
994
- typeof left.value === "number" &&
995
- typeof right.value === "number"
996
- ) {
997
- return constant(left.value ** right.value);
998
- }
999
- return this.calls.power(left, right, node, frame);
1025
+ return this.calls.floatMath("pow", [left, right], node, frame);
1000
1026
  }
1001
- const operator = binaryOperators.get(kind);
1002
- if (!operator) {
1003
- throw new SpecializeError(
1004
- node,
1005
- `${node.operatorToken.getText()} is not supported.`,
1006
- );
1007
- }
1008
- const declared = this.checker.getTypeAtLocation(node);
1009
- if (["<", "<=", ">", ">="].includes(operator)) {
1010
- const [leftText, rightText] = this.dialect.comparable(
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(
1011
1031
  left,
1012
1032
  right,
1013
1033
  undefined,
1014
1034
  );
1015
1035
  return {
1016
1036
  kind: "code",
1017
- text: mapped`(${leftText} ${operator} ${rightText})`,
1037
+ text: mapped`(${leftText} ${comparison} ${rightText})`,
1018
1038
  declared,
1019
1039
  };
1020
1040
  }
1021
- const { texts, iec } = this.dialect.arithmetic(left, right);
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);
1022
1059
  return {
1023
1060
  kind: "code",
1024
1061
  text: mapped`(${texts[0]} ${operator} ${texts[1]})`,
@@ -1029,7 +1066,7 @@ export class ExpressionSpecializer {
1029
1066
 
1030
1067
  /** A plain number: an enum's members are numbers to TypeScript, but the PLC's enum is no integer. */
1031
1068
  private isNumber(node: ts.Expression): boolean {
1032
- const flags = this.checker.getTypeAtLocation(node).flags;
1069
+ const flags = this.context.checker.getTypeAtLocation(node).flags;
1033
1070
  return (
1034
1071
  Boolean(flags & (ts.TypeFlags.Number | ts.TypeFlags.NumberLiteral)) &&
1035
1072
  !(flags & ts.TypeFlags.EnumLike)
@@ -1047,11 +1084,11 @@ export class ExpressionSpecializer {
1047
1084
  ): Value {
1048
1085
  const once = this.temporaryOf(left, frame);
1049
1086
  const right = this.expression(node.right, frame);
1050
- const first = this.dialect.code(once, undefined);
1087
+ const first = this.context.dialect.code(once, undefined);
1051
1088
  return {
1052
1089
  kind: "code",
1053
- text: mapped`(${first} !== 0 ? ${first} : ${this.dialect.code(right, undefined)})`,
1054
- declared: this.checker.getTypeAtLocation(node),
1090
+ text: mapped`(${first} !== 0 ? ${first} : ${this.context.dialect.code(right, undefined)})`,
1091
+ declared: this.context.checker.getTypeAtLocation(node),
1055
1092
  iec: left.iec,
1056
1093
  };
1057
1094
  }
@@ -1075,20 +1112,23 @@ export class ExpressionSpecializer {
1075
1112
  // A value whose storage can't hold undefined never is, as an index setup filled isn't.
1076
1113
  if (
1077
1114
  !code.declared ||
1078
- (!this.layouts.isOptionalRecord(code.declared) &&
1079
- !this.layouts.literals(code.declared)?.optional)
1115
+ (!this.context.layouts.isOptionalRecord(code.declared) &&
1116
+ !this.context.layouts.literals(code.declared)?.optional)
1080
1117
  ) {
1081
1118
  return constant(negate);
1082
1119
  }
1083
- const test = this.dialect.isUndefinedText(code.text, code.declared);
1120
+ const test = this.context.dialect.isUndefinedText(
1121
+ code.text,
1122
+ code.declared,
1123
+ );
1084
1124
  return {
1085
1125
  kind: "code",
1086
1126
  text: negate ? mapped`!(${test})` : test,
1087
- declared: this.checker.getBooleanType(),
1127
+ declared: this.context.checker.getBooleanType(),
1088
1128
  };
1089
1129
  }
1090
1130
  const declared = code.kind === "code" ? code.declared : undefined;
1091
- const [leftText, rightText] = this.dialect.comparable(
1131
+ const [leftText, rightText] = this.context.dialect.comparable(
1092
1132
  left,
1093
1133
  right,
1094
1134
  declared,
@@ -1096,12 +1136,12 @@ export class ExpressionSpecializer {
1096
1136
  return {
1097
1137
  kind: "code",
1098
1138
  text: mapped`(${leftText} ${negate ? "!==" : "==="} ${rightText})`,
1099
- declared: this.checker.getBooleanType(),
1139
+ declared: this.context.checker.getBooleanType(),
1100
1140
  };
1101
1141
  }
1102
1142
 
1103
1143
  /** Equality known now: two known objects, or a known object against undefined. */
1104
- equal(left: Value, right: Value): boolean | undefined {
1144
+ private equal(left: Value, right: Value): boolean | undefined {
1105
1145
  if (left.kind === "const" && right.kind === "const") {
1106
1146
  return left.value === right.value;
1107
1147
  }
@@ -1127,7 +1167,7 @@ export class ExpressionSpecializer {
1127
1167
  ): Value {
1128
1168
  if (target.kind === "static" && target.node.captured.kind === "closure") {
1129
1169
  return this.invoke(
1130
- this.closure(target.node, at),
1170
+ this.closure(target.node.captured, at),
1131
1171
  args,
1132
1172
  at,
1133
1173
  frame,
@@ -1138,21 +1178,31 @@ export class ExpressionSpecializer {
1138
1178
  throw new SpecializeError(at, "Only functions can be called.");
1139
1179
  }
1140
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
+ }
1141
1188
  if (
1142
- (ts.isArrowFunction(declaration) ||
1143
- ts.isFunctionExpression(declaration)) &&
1144
1189
  target.env &&
1145
1190
  ts.isArrowFunction(declaration) &&
1146
1191
  !ts.isBlock(declaration.body)
1147
1192
  ) {
1148
- // A callback with one expression inlines with its arguments bound.
1149
1193
  const inline: Frame = {
1150
1194
  ...frame,
1151
1195
  env: new Map(target.env),
1152
1196
  self: target.self ?? frame.self,
1153
1197
  };
1154
1198
  declaration.parameters.forEach((parameter, index) => {
1155
- const arg = args[index] ?? constant(undefined);
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;
1156
1206
  const value =
1157
1207
  arg.kind === "code" && !arg.place
1158
1208
  ? this.temporaryOf(arg, frame)
@@ -1160,23 +1210,39 @@ export class ExpressionSpecializer {
1160
1210
  this.bind(
1161
1211
  parameter.name,
1162
1212
  value,
1163
- false,
1164
1213
  inline,
1165
- this.checker.getTypeAtLocation(parameter),
1214
+ this.context.checker.getTypeAtLocation(parameter),
1215
+ { mutable: false, iec: this.context.layouts.iecName(parameter) },
1166
1216
  );
1167
1217
  });
1168
- return this.expression(declaration.body, inline, expected);
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
+ };
1169
1234
  }
1170
1235
  const called = this.routineTable.routine(
1171
1236
  declaration,
1172
1237
  target.self,
1173
1238
  args,
1174
- target.env,
1239
+ target.env && { env: target.env, caller: frame.emitter },
1175
1240
  );
1176
1241
  const text = mapped`${called.name}(${joined(called.args, ", ")})`;
1177
1242
  const returns = called.returns;
1178
1243
  if (!returns || returns.flags & ts.TypeFlags.Void) {
1179
- if (ts.isExpressionStatement(at.parent)) {
1244
+ const statement = ts.isAwaitExpression(at.parent) ? at.parent : at;
1245
+ if (ts.isExpressionStatement(statement.parent) || linksPromise(at)) {
1180
1246
  return { kind: "code", text, declared: returns };
1181
1247
  }
1182
1248
  frame.emitter.line(mapped`${text};`);
@@ -1192,7 +1258,7 @@ export class ExpressionSpecializer {
1192
1258
  iec: called.iec,
1193
1259
  layout: called.layout,
1194
1260
  length: called.length,
1195
- ...(called.returnsStored && { copyOf: called.name }),
1261
+ ...(called.returnsStored && { copyOf: sourceName(target) }),
1196
1262
  };
1197
1263
  }
1198
1264
 
@@ -1206,14 +1272,11 @@ export class ExpressionSpecializer {
1206
1272
  throw new SpecializeError(node, "`super` outside a method.");
1207
1273
  }
1208
1274
  const name = node.name.text;
1209
- const inherited = this.model
1275
+ const inherited = this.context.model
1210
1276
  .ancestry(owner)
1211
1277
  .slice(1)
1212
1278
  .flatMap((base) => [...base.members]);
1213
- const accessor = inherited.find(
1214
- (member): member is ts.GetAccessorDeclaration =>
1215
- ts.isGetAccessorDeclaration(member) && member.name.getText() === name,
1216
- );
1279
+ const accessor = getterNamed(inherited, name);
1217
1280
  if (accessor) {
1218
1281
  return this.invoke(
1219
1282
  { kind: "function", declaration: accessor, self: frame.self },
@@ -1222,21 +1285,13 @@ export class ExpressionSpecializer {
1222
1285
  frame,
1223
1286
  );
1224
1287
  }
1225
- const method = inherited.find(
1226
- (member): member is ts.MethodDeclaration =>
1227
- ts.isMethodDeclaration(member) && member.name.getText() === name,
1228
- );
1288
+ const method = methodNamed(inherited, name);
1229
1289
  if (!method) {
1230
1290
  throw new SpecializeError(node, `The base class has no ${name}.`);
1231
1291
  }
1232
1292
  return { kind: "function", declaration: method, self: frame.self };
1233
1293
  }
1234
1294
 
1235
- /** The fields `...source` spreads into a record literal: a known record's, or each property its type declares. */
1236
- spreadFields(property: ts.SpreadAssignment, frame: Frame): [string, Value][] {
1237
- return this.recordFields(property.expression, frame);
1238
- }
1239
-
1240
1295
  /** Each field of a record-valued expression: a known record's, or each property its type declares. */
1241
1296
  recordFields(expression: ts.Expression, frame: Frame): [string, Value][] {
1242
1297
  const evaluated = this.expression(expression, frame);
@@ -1248,9 +1303,9 @@ export class ExpressionSpecializer {
1248
1303
  evaluated.kind === "code"
1249
1304
  ? this.temporaryOf(evaluated, frame)
1250
1305
  : evaluated;
1251
- const type = this.checker.getTypeAtLocation(expression);
1252
- return this.checker
1253
- .getPropertiesOfType(this.checker.getNonNullableType(type))
1306
+ const type = this.context.checker.getTypeAtLocation(expression);
1307
+ return this.context.checker
1308
+ .getPropertiesOfType(this.context.checker.getNonNullableType(type))
1254
1309
  .map((symbol): [string, Value] => [
1255
1310
  symbol.name,
1256
1311
  this.member(source, symbol.name, expression, frame),
@@ -1266,20 +1321,10 @@ export class ExpressionSpecializer {
1266
1321
  name: ts.Identifier,
1267
1322
  symbol: ts.Symbol,
1268
1323
  ): boolean {
1269
- const inner = [...(value.fields?.values() ?? []), ...(value.items ?? [])];
1270
- if (
1271
- inner.some(
1272
- (item) =>
1273
- item.kind === "static" ||
1274
- item.kind === "function" ||
1275
- item.kind === "choice",
1276
- )
1277
- ) {
1324
+ if (holdsSetupObjects(value)) {
1278
1325
  return false;
1279
1326
  }
1280
- const scope =
1281
- ts.findAncestor(name.parent, ts.isFunctionLike) ?? name.getSourceFile();
1282
- return writesThrough(scope, symbol, this.checker);
1327
+ return writesThrough(scopeOf(name), symbol, this.context.checker);
1283
1328
  }
1284
1329
 
1285
1330
  /** `typeof`, known when the program compiles: from a value setup fixed, or from runtime storage's declared type. */
@@ -1304,31 +1349,15 @@ export class ExpressionSpecializer {
1304
1349
  return constant(found ? found[1] : "object");
1305
1350
  }
1306
1351
 
1307
- /** `Math.PI` and JavaScript's other Math constants, from its own library rather than the program. */
1308
- private isMathConstant(node: ts.PropertyAccessExpression): boolean {
1309
- return (
1310
- ts.isIdentifier(node.expression) &&
1311
- node.expression.text === "Math" &&
1312
- mathConstants.has(node.name.text) &&
1313
- (this.checker
1314
- .getSymbolAtLocation(node.expression)
1315
- ?.declarations?.every(
1316
- (declaration) => declaration.getSourceFile().isDeclarationFile,
1317
- ) ??
1318
- false)
1319
- );
1320
- }
1321
-
1322
1352
  /**
1323
1353
  * A function setup made inside another and stored: its declaration, with the values it captured
1324
1354
  * as its closure, and the object it was made in as its `this`.
1325
1355
  */
1326
- private closure(node: ModelNode, at: ts.Node): Value {
1327
- const captured = node.captured;
1328
- if (captured.kind !== "closure") {
1329
- throw new SpecializeError(at, "Not a closure.");
1330
- }
1331
- const source = this.model.sourceFile(captured.file);
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);
1332
1361
  const declaration = findClosure(source, captured.start);
1333
1362
  if (!declaration) {
1334
1363
  throw new SpecializeError(
@@ -1336,14 +1365,13 @@ export class ExpressionSpecializer {
1336
1365
  "The function setup stored isn't in the program.",
1337
1366
  );
1338
1367
  }
1339
- // Each captured name maps to the symbols the closure's own identifiers read by it.
1340
- const symbols = closureSymbols(declaration, this.checker);
1368
+ const symbols = closureSymbols(declaration, this.context.checker);
1341
1369
  const env: Env = new Map(
1342
1370
  captured.captures.flatMap(({ name, value }): [ts.Symbol, Value][] => {
1343
- const held = this.model.node(value);
1344
- const known: Value = held
1345
- ? { kind: "static", node: held }
1346
- : capturedConstant(value);
1371
+ const known: Value =
1372
+ value.kind === "node"
1373
+ ? { kind: "static", node: this.context.model.node(value) }
1374
+ : capturedPrimitive(value);
1347
1375
  return (symbols.get(name) ?? []).map((symbol): [ts.Symbol, Value] => [
1348
1376
  symbol,
1349
1377
  known,
@@ -1351,44 +1379,78 @@ export class ExpressionSpecializer {
1351
1379
  }),
1352
1380
  );
1353
1381
  const made = captured.captures.find(({ name }) => name === "this");
1354
- const self = made && this.model.node(made.value);
1382
+ const self = made && this.context.model.node(made.value);
1355
1383
  return { kind: "function", declaration, self, env };
1356
1384
  }
1357
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
+
1358
1431
  /** `record?.field` on an optional record: the field as an optional, or the empty value when the record is. */
1359
1432
  private optionalMember(
1360
- object: Value & { kind: "code" },
1433
+ object: Code,
1434
+ declared: ts.Type,
1361
1435
  node: ts.PropertyAccessExpression,
1362
1436
  frame: Frame,
1363
1437
  ): Value {
1364
- const declared = object.declared;
1365
- if (!declared) {
1366
- throw new SpecializeError(node, "Not an optional record.");
1367
- }
1368
1438
  const held = this.temporaryOf(object, frame);
1369
- if (held.kind !== "code") {
1370
- throw new SpecializeError(node, "Not an optional record.");
1371
- }
1372
1439
  const defined: Value = {
1373
1440
  kind: "code",
1374
- text: mapped`${held.text}.value`,
1375
- declared: this.checker.getNonNullableType(declared),
1441
+ text: optionalValue(held.text),
1442
+ declared: this.context.checker.getNonNullableType(declared),
1376
1443
  place: held.place,
1377
1444
  };
1378
1445
  const field = this.member(defined, node.name.text, node, frame);
1379
- const result = this.checker.getTypeAtLocation(node);
1446
+ const result = this.context.checker.getTypeAtLocation(node);
1380
1447
  return {
1381
1448
  kind: "code",
1382
- text: mapped`(${this.dialect.isUndefinedText(held.text, declared)} ? ${this.dialect.assignmentText(constant(undefined), result)} : ${this.dialect.assignmentText(field, result)})`,
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)})`,
1383
1450
  declared: result,
1384
1451
  };
1385
1452
  }
1386
1453
 
1387
- /** A call to a generator, which a for…of runs inline. */
1388
- generator(node: ts.Expression, frame: Frame) {
1389
- return this.calls.generator(node, frame);
1390
- }
1391
-
1392
1454
  /**
1393
1455
  * Evaluates operands left to right. A runtime value read before a later operand writes is held in
1394
1456
  * a const first, so it is the value JavaScript reads then.
@@ -1417,22 +1479,51 @@ export class ExpressionSpecializer {
1417
1479
  ) {
1418
1480
  return value;
1419
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
+ }
1420
1495
  const local = frame.emitter.temporary();
1421
- const type =
1422
- value.iec ?? (value.declared ? this.localType(value.declared) : "number");
1423
- frame.emitter.line(mapped`const ${local}: ${type} = ${value.text};`);
1496
+ frame.emitter.line(
1497
+ mapped`const ${local}: ${this.heldType(value, holding)} = ${value.text};`,
1498
+ );
1424
1499
  return {
1425
1500
  kind: "code",
1426
1501
  text: local,
1427
1502
  declared: value.declared,
1428
1503
  place: true,
1429
- iec: value.iec,
1504
+ ...(holding.width && { iec: value.iec }),
1430
1505
  };
1431
1506
  }
1432
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
+
1433
1522
  /** `.value` for an optional record, whose defined value sits in a field. */
1434
1523
  optionalValueSuffix(declared: ts.Type): string {
1435
- return this.layouts.isOptionalRecord(declared) ? ".value" : "";
1524
+ return this.context.layouts.isOptionalRecord(declared)
1525
+ ? `.${optionalRecord.value}`
1526
+ : "";
1436
1527
  }
1437
1528
 
1438
1529
  /**
@@ -1450,21 +1541,20 @@ export class ExpressionSpecializer {
1450
1541
  ): Value {
1451
1542
  const result = frame.emitter.temporary();
1452
1543
  frame.emitter.line(
1453
- `let ${result}: ${this.localType(declared)} = ${this.initializers.defaultOf(declared)};`,
1454
- );
1455
- const [yes, no] = branches.map(
1456
- (branch) => () =>
1457
- typeof branch === "function"
1458
- ? branch()
1459
- : this.expression(branch, frame, declared),
1544
+ `let ${result}: ${this.localType(declared)} = ${this.context.initializers.defaultOf(declared)};`,
1460
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;
1461
1551
  frame.emitter.open(mapped`if (${condition}) {`);
1462
1552
  frame.emitter.line(
1463
- mapped`${result} = ${this.dialect.assignmentText(yes!(), declared, undefined)};`,
1553
+ mapped`${result} = ${this.context.dialect.assignmentText(evaluate(yes), declared, undefined)};`,
1464
1554
  );
1465
1555
  frame.emitter.reopen("} else {");
1466
1556
  frame.emitter.line(
1467
- mapped`${result} = ${this.dialect.assignmentText(no!(), declared, undefined)};`,
1557
+ mapped`${result} = ${this.context.dialect.assignmentText(evaluate(no), declared, undefined)};`,
1468
1558
  );
1469
1559
  frame.emitter.close();
1470
1560
  return { kind: "code", text: result, declared, place: true };
@@ -1478,26 +1568,154 @@ export class ExpressionSpecializer {
1478
1568
  return containsWrite(node) || this.iterators.traverses(node, frame);
1479
1569
  }
1480
1570
 
1481
- /** A runtime value held in a const, so inlining doesn't evaluate it twice. */
1482
- temporaryOf(value: Value & { kind: "code" }, frame: Frame): Value {
1483
- if (repeatable(value.text)) {
1484
- return value;
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
+ }
1485
1590
  }
1486
- const local = frame.emitter.temporary();
1487
- const type = value.declared ? this.localType(value.declared) : "number";
1488
- frame.emitter.line(mapped`const ${local}: ${type} = ${value.text};`);
1489
- return { kind: "code", text: local, declared: value.declared, place: true };
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
+ });
1490
1703
  }
1491
1704
 
1492
1705
  /** Binds a local, or each name of a destructuring pattern, to a value. */
1493
1706
  bind(
1494
1707
  name: ts.BindingName,
1495
1708
  value: Value,
1496
- mutable: boolean,
1497
1709
  frame: Frame,
1498
1710
  declared: ts.Type,
1499
- /** The IEC width the local's annotation names, as `const slot: UINT` does. */
1500
- iec?: string,
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
+ },
1501
1719
  ): void {
1502
1720
  // A pattern reads its value once per name, so a computed value is held first.
1503
1721
  const bound =
@@ -1505,36 +1723,46 @@ export class ExpressionSpecializer {
1505
1723
  ? this.temporaryOf(value, frame)
1506
1724
  : value;
1507
1725
  if (ts.isObjectBindingPattern(name)) {
1508
- for (const element of name.elements) {
1509
- const field = (element.propertyName ?? element.name).getText();
1510
- const inner = this.member(bound, field, element, frame);
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
+ );
1511
1732
  this.bind(
1512
1733
  element.name,
1513
1734
  inner,
1514
- mutable,
1515
1735
  frame,
1516
- this.checker.getTypeAtLocation(element.name),
1736
+ this.context.checker.getTypeAtLocation(element.name),
1737
+ { mutable, iec: undefined },
1517
1738
  );
1518
1739
  }
1519
1740
  return;
1520
1741
  }
1521
1742
  if (ts.isArrayBindingPattern(name)) {
1522
- name.elements.forEach((element, index) => {
1523
- if (ts.isOmittedExpression(element)) {
1524
- return;
1525
- }
1526
- const inner = this.element(bound, constant(index), element, frame);
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
+ );
1527
1749
  this.bind(
1528
1750
  element.name,
1529
1751
  inner,
1530
- mutable,
1531
1752
  frame,
1532
- this.checker.getTypeAtLocation(element.name),
1753
+ this.context.checker.getTypeAtLocation(element.name),
1754
+ { mutable, iec: undefined },
1533
1755
  );
1534
- });
1756
+ }
1535
1757
  return;
1536
1758
  }
1537
- const symbol = this.checker.getSymbolAtLocation(name)!;
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
+ }
1538
1766
  const reference = this.references.local(name.text, bound, declared, frame, {
1539
1767
  mutable,
1540
1768
  });
@@ -1544,12 +1772,12 @@ export class ExpressionSpecializer {
1544
1772
  }
1545
1773
  if (
1546
1774
  bound.kind === "virtual" &&
1547
- !isReadonly(declared, this.checker) &&
1775
+ !isReadonly(declared, this.context.checker) &&
1548
1776
  this.heldAsLocal(bound, name, symbol)
1549
1777
  ) {
1550
1778
  const local = frame.emitter.local(name.text);
1551
1779
  frame.emitter.line(
1552
- mapped`let ${local}: ${this.localType(declared)} = ${this.dialect.assignmentText(bound, declared)};`,
1780
+ mapped`let ${local}: ${this.localType(declared)} = ${this.context.dialect.assignmentText(bound, declared, undefined)};`,
1553
1781
  );
1554
1782
  frame.env.set(symbol, {
1555
1783
  kind: "code",
@@ -1559,7 +1787,14 @@ export class ExpressionSpecializer {
1559
1787
  });
1560
1788
  return;
1561
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
+ }
1562
1796
  if (!mutable && bound.kind !== "code") {
1797
+ this.refuseOutsideWidth(bound, iec, name);
1563
1798
  frame.env.set(symbol, bound);
1564
1799
  return;
1565
1800
  }
@@ -1568,8 +1803,8 @@ export class ExpressionSpecializer {
1568
1803
  bound.kind === "code" &&
1569
1804
  bound.place &&
1570
1805
  ts.isIdentifier(name) &&
1571
- this.isAggregate(this.checker.getNonNullableType(declared)) &&
1572
- replacedWhileAliased(name, this.checker)
1806
+ this.isAggregate(this.context.checker.getNonNullableType(declared)) &&
1807
+ replacedWhileAliased(name, this.context.checker)
1573
1808
  ) {
1574
1809
  this.snapshot(name, symbol, bound, declared, frame);
1575
1810
  return;
@@ -1583,33 +1818,87 @@ export class ExpressionSpecializer {
1583
1818
  const repeats =
1584
1819
  ts.isIdentifier(name) &&
1585
1820
  pureRead(bound.text) &&
1586
- stableAlias(name, this.checker);
1821
+ stableAlias(name, this.context.checker);
1587
1822
  frame.env.set(symbol, pin && !repeats ? pin(frame) : bound);
1588
1823
  return;
1589
1824
  }
1590
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
+ }
1591
1860
  const local = frame.emitter.local(name.text);
1592
1861
  // A const record changed through its name, or lent to a call that may, is a variable to the PLC:
1593
1862
  // TypeScript's const fixes the binding, not the object.
1594
1863
  const changes =
1595
1864
  !mutable &&
1596
1865
  this.isAggregate(declared) &&
1597
- writesThrough(
1598
- ts.findAncestor(name.parent, ts.isFunctionLike) ?? name.getSourceFile(),
1599
- symbol,
1600
- this.checker,
1601
- );
1866
+ writesThrough(scopeOf(name), symbol, this.context.checker);
1602
1867
  const width = iec ?? (bound.kind === "code" ? bound.iec : undefined);
1603
1868
  const layout = bound.kind === "code" ? bound.layout : undefined;
1604
1869
  const length = bound.kind === "code" ? bound.length : undefined;
1605
- const type = width ?? layout ?? this.localType(declared);
1870
+ const type = width ?? layout?.text ?? this.localType(declared);
1871
+ // The async lowering suspends only at a bare await, so an awaited value cannot be converted in place.
1872
+ if (
1873
+ iec !== undefined &&
1874
+ bound.kind === "code" &&
1875
+ bound.awaited &&
1876
+ this.context.dialect.converts(bound, declared, iec)
1877
+ ) {
1878
+ throw new SpecializeError(
1879
+ name,
1880
+ `An awaited value keeps its routine's result type, ${bound.iec ?? defaultNumericTypes.number}; store it in a local of that type, then convert it.`,
1881
+ );
1882
+ }
1606
1883
  // An annotated width converts the value as IEC assignment does.
1607
1884
  const text = iec
1608
- ? this.dialect.assignmentText(bound, declared, iec)
1609
- : this.dialect.code(bound, declared);
1610
- // What an await gives is typed by the call awaited, which the async lowering reads itself.
1611
- const annotation =
1612
- bound.kind === "code" && bound.awaited && !iec ? "" : `: ${type}`;
1885
+ ? this.context.dialect.assignmentText(bound, declared, iec)
1886
+ : this.context.dialect.code(bound, declared);
1887
+ // What an await gives is typed by the call awaited, which the async lowering reads itself, and
1888
+ // what a task returns by the task's declaration, whose IEC result type no TypeScript type keeps.
1889
+ const typedByCall =
1890
+ bound.kind === "code" &&
1891
+ (bound.awaited || bound.typedByTask) &&
1892
+ !iec &&
1893
+ // A record the program annotates keeps that layout: no width conversion stands between it
1894
+ // and the call, and the call alone may not name it, as fetch's type argument doesn't.
1895
+ !(
1896
+ bound.awaited &&
1897
+ this.isAggregate(declared) &&
1898
+ ts.isVariableDeclaration(name.parent) &&
1899
+ name.parent.type !== undefined
1900
+ );
1901
+ const annotation = typedByCall ? "" : `: ${type}`;
1613
1902
  frame.emitter.line(
1614
1903
  mapped`${mutable || changes ? "let" : "const"} ${local}${annotation} = ${text};`,
1615
1904
  );
@@ -1627,10 +1916,12 @@ export class ExpressionSpecializer {
1627
1916
 
1628
1917
  /** A local's dialect type: a literal union keeps its enum; a lone literal widens to its base type. */
1629
1918
  localType(declared: ts.Type): string {
1630
- if (this.layouts.literalEnum(declared)) {
1631
- return this.layouts.text(declared);
1919
+ if (this.context.layouts.literalEnum(declared)) {
1920
+ return this.context.layouts.text(declared);
1632
1921
  }
1633
- return this.layouts.text(this.checker.getBaseTypeOfLiteralType(declared));
1922
+ return this.context.layouts.text(
1923
+ this.context.checker.getBaseTypeOfLiteralType(declared),
1924
+ );
1634
1925
  }
1635
1926
 
1636
1927
  /**
@@ -1645,23 +1936,17 @@ export class ExpressionSpecializer {
1645
1936
  declared: ts.Type,
1646
1937
  frame: Frame,
1647
1938
  ): void {
1648
- if (
1649
- writesThrough(
1650
- ts.findAncestor(name.parent, ts.isFunctionLike) ?? name.getSourceFile(),
1651
- symbol,
1652
- this.checker,
1653
- )
1654
- ) {
1939
+ if (writesThrough(scopeOf(name), symbol, this.context.checker)) {
1655
1940
  throw new SpecializeError(
1656
1941
  name,
1657
1942
  "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.",
1658
1943
  );
1659
1944
  }
1660
1945
  const local = frame.emitter.local(name.text);
1661
- const type = bound.layout ?? this.localType(declared);
1662
- this.imports.addSdk("@tsplc/compiler/types", "copy");
1946
+ const type = bound.layout?.text ?? this.localType(declared);
1947
+ this.context.imports.addSdk(sdkModules.types, "copy");
1663
1948
  frame.emitter.line(
1664
- mapped`const ${local}: ${type} = copy(${this.dialect.code(bound, declared)});`,
1949
+ mapped`const ${local}: ${type} = copy(${this.context.dialect.code(bound, declared)});`,
1665
1950
  );
1666
1951
  frame.env.set(symbol, {
1667
1952
  kind: "code",
@@ -1676,7 +1961,7 @@ export class ExpressionSpecializer {
1676
1961
  private isAggregate(type: ts.Type): boolean {
1677
1962
  return (
1678
1963
  Boolean(type.flags & ts.TypeFlags.Object) &&
1679
- !this.layouts.literalEnum(type)
1964
+ !this.context.layouts.literalEnum(type)
1680
1965
  );
1681
1966
  }
1682
1967
 
@@ -1688,9 +1973,9 @@ export class ExpressionSpecializer {
1688
1973
  if (value.kind === "virtual" && value.items) {
1689
1974
  return value.items;
1690
1975
  }
1691
- // An array scan code writes is stored, at the length setup gave it.
1692
1976
  if (value.kind === "code" && value.length !== undefined) {
1693
- const declared = value.declared && this.model.elementType(value.declared);
1977
+ const declared =
1978
+ value.declared && this.context.model.elementType(value.declared);
1694
1979
  return Array.from(
1695
1980
  { length: value.length },
1696
1981
  (_, index): Value => ({
@@ -1711,21 +1996,26 @@ export class ExpressionSpecializer {
1711
1996
  return undefined;
1712
1997
  }
1713
1998
  return captured.items.map((item, index) =>
1714
- this.storage.fromCaptured(item, array, { kind: "index", index }),
1999
+ this.context.storage.fromCaptured(item, array, { kind: "index", index }),
1715
2000
  );
1716
2001
  }
1717
2002
  }
1718
2003
 
1719
- /** Binary operators the dialect writes as TypeScript does. */
1720
- const binaryOperators = new Map<ts.SyntaxKind, string>([
1721
- [ts.SyntaxKind.PlusToken, "+"],
1722
- [ts.SyntaxKind.MinusToken, "-"],
1723
- [ts.SyntaxKind.AsteriskToken, "*"],
1724
- [ts.SyntaxKind.PercentToken, "%"],
2004
+ /** Comparisons the dialect writes as TypeScript does. */
2005
+ const comparisonOperators = new Map<ts.SyntaxKind, string>([
1725
2006
  [ts.SyntaxKind.LessThanToken, "<"],
1726
2007
  [ts.SyntaxKind.LessThanEqualsToken, "<="],
1727
2008
  [ts.SyntaxKind.GreaterThanToken, ">"],
1728
2009
  [ts.SyntaxKind.GreaterThanEqualsToken, ">="],
2010
+ ]);
2011
+
2012
+ /** Arithmetic and bit operators the dialect writes as TypeScript does. */
2013
+ const arithmeticOperators = new Map<ts.SyntaxKind, string>([
2014
+ [ts.SyntaxKind.PlusToken, "+"],
2015
+ [ts.SyntaxKind.MinusToken, "-"],
2016
+ [ts.SyntaxKind.AsteriskToken, "*"],
2017
+ [ts.SyntaxKind.SlashToken, "/"],
2018
+ [ts.SyntaxKind.PercentToken, "%"],
1729
2019
  [ts.SyntaxKind.AmpersandToken, "&"],
1730
2020
  [ts.SyntaxKind.BarToken, "|"],
1731
2021
  [ts.SyntaxKind.CaretToken, "^"],
@@ -1745,6 +2035,10 @@ const foldNumber = (
1745
2035
  return left - right;
1746
2036
  case ts.SyntaxKind.AsteriskToken:
1747
2037
  return left * right;
2038
+ case ts.SyntaxKind.AsteriskAsteriskToken:
2039
+ return left ** right;
2040
+ case ts.SyntaxKind.SlashToken:
2041
+ return left / right;
1748
2042
  case ts.SyntaxKind.PercentToken:
1749
2043
  return right === 0 ? undefined : left % right;
1750
2044
  case ts.SyntaxKind.LessThanToken:
@@ -1771,10 +2065,53 @@ const mathConstants = new Map([
1771
2065
  ["SQRT2", Math.SQRT2],
1772
2066
  ]);
1773
2067
 
2068
+ /** A function as its source names it, for a message: `Class.method`, or the function's name. */
2069
+ const sourceName = (target: Extract<Value, { kind: "function" }>): string => {
2070
+ const own = target.declaration.name?.getText() ?? "this function";
2071
+ return target.self?.captured.kind === "instance"
2072
+ ? `${target.self.captured.name}.${own}`
2073
+ : own;
2074
+ };
2075
+
2076
+ /** Whether a call is a `.then` or `.catch` link on a promise. */
2077
+ export const isPromiseLink = (node: ts.Node): node is ts.CallExpression =>
2078
+ ts.isCallExpression(node) &&
2079
+ ts.isPropertyAccessExpression(node.expression) &&
2080
+ promiseLinks.has(node.expression.name.text);
2081
+
2082
+ const promiseLinks: ReadonlySet<string> = new Set(["then", "catch"]);
2083
+
2084
+ /** Whether an expression is the promise a `.then` or `.catch` link is called on. */
2085
+ const linksPromise = (node: ts.Node): boolean =>
2086
+ ts.isPropertyAccessExpression(node.parent) &&
2087
+ node.parent.expression === node &&
2088
+ isPromiseLink(node.parent.parent);
2089
+
2090
+ /** The function, or else the module, a name is declared in. */
2091
+ const scopeOf = (name: ts.Identifier): ts.Node =>
2092
+ ts.findAncestor(name.parent, ts.isFunctionLike) ?? name.getSourceFile();
2093
+
2094
+ const getterNamed = (
2095
+ members: readonly ts.ClassElement[],
2096
+ name: string,
2097
+ ): ts.GetAccessorDeclaration | undefined =>
2098
+ members.find(
2099
+ (member): member is ts.GetAccessorDeclaration =>
2100
+ ts.isGetAccessorDeclaration(member) && member.name.getText() === name,
2101
+ );
2102
+
2103
+ const methodNamed = (
2104
+ members: readonly ts.ClassElement[],
2105
+ name: string,
2106
+ ): ts.MethodDeclaration | undefined =>
2107
+ members.find(
2108
+ (member): member is ts.MethodDeclaration =>
2109
+ ts.isMethodDeclaration(member) && member.name.getText() === name,
2110
+ );
2111
+
1774
2112
  /** A readonly array or record: what holds it can't change it, so a literal given to it stays a value. */
1775
2113
  const isReadonly = (type: ts.Type, checker: ts.TypeChecker): boolean =>
1776
- (checker.isArrayType(type) === false &&
1777
- type.getSymbol()?.name === "ReadonlyArray") ||
2114
+ (!checker.isArrayType(type) && type.getSymbol()?.name === "ReadonlyArray") ||
1778
2115
  type.aliasSymbol?.name === "Readonly" ||
1779
2116
  checker.typeToString(type).startsWith("readonly ");
1780
2117
 
@@ -1799,20 +2136,6 @@ const findClosure = (
1799
2136
  return visit(source);
1800
2137
  };
1801
2138
 
1802
- /** A primitive setup captured, as a value known now. */
1803
- const capturedConstant = (value: CapturedValue): Value => {
1804
- switch (value.kind) {
1805
- case "undefined":
1806
- return constant(undefined);
1807
- case "bigint":
1808
- return constant(BigInt(value.value));
1809
- case "node":
1810
- throw new Error("Not a primitive.");
1811
- default:
1812
- return constant(value.value);
1813
- }
1814
- };
1815
-
1816
2139
  /** The symbols a closure's identifiers read, by name; a shorthand property reads its value's. */
1817
2140
  const closureSymbols = (
1818
2141
  declaration: ts.Node,
@@ -1821,9 +2144,7 @@ const closureSymbols = (
1821
2144
  const found = new Map<string, ts.Symbol[]>();
1822
2145
  const visit = (node: ts.Node): void => {
1823
2146
  if (ts.isIdentifier(node)) {
1824
- const symbol = ts.isShorthandPropertyAssignment(node.parent)
1825
- ? checker.getShorthandAssignmentValueSymbol(node.parent)
1826
- : checker.getSymbolAtLocation(node);
2147
+ const symbol = valueSymbol(checker, node);
1827
2148
  const known = found.get(node.text) ?? [];
1828
2149
  if (symbol && !known.includes(symbol)) {
1829
2150
  found.set(node.text, [...known, symbol]);