@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
@@ -0,0 +1,34 @@
1
+ import type { PlcType } from "@tsplc/compiler/ir";
2
+
3
+ type CalendarDomain = Extract<PlcType, { kind: "calendar" }>["domain"];
4
+
5
+ /** The SDK's TIME constructors. */
6
+ export const durationNames: ReadonlySet<string> = new Set([
7
+ "ms",
8
+ "seconds",
9
+ "minutes",
10
+ ]);
11
+
12
+ /** The SDK's calendar constructors: the domain each makes, its IEC type and the text it takes. */
13
+ export const calendarFormats = new Map<
14
+ string,
15
+ { domain: CalendarDomain; type: string; format: string }
16
+ >([
17
+ ["date", { domain: "date", type: "DATE", format: "YYYY-MM-DD" }],
18
+ [
19
+ "timeOfDay",
20
+ { domain: "timeOfDay", type: "TIME_OF_DAY", format: "hh:mm:ss[.mmm]" },
21
+ ],
22
+ [
23
+ "dateAndTime",
24
+ {
25
+ domain: "dateTime",
26
+ type: "DATE_AND_TIME",
27
+ format: "YYYY-MM-DDThh:mm:ss",
28
+ },
29
+ ],
30
+ ]);
31
+
32
+ /** The calendar constructor that makes a value of the IEC type `type`, as `date` makes a DATE. */
33
+ export const calendarConstructor = (type: string): string | undefined =>
34
+ [...calendarFormats].find(([, format]) => format.type === type)?.[0];
@@ -1,6 +1,9 @@
1
- import type ts from "typescript";
1
+ import ts from "typescript";
2
2
  import type { Mapped } from "../positions";
3
+ import { isWrapper } from "../types";
4
+ import type { CapturedPrimitive } from "./capture-protocol";
3
5
  import type { Frame } from "./frame";
6
+ import type { ArrayLayout } from "./layouts";
4
7
  import type { ModelNode } from "./model";
5
8
 
6
9
  export type FunctionLike =
@@ -30,11 +33,11 @@ export type Value =
30
33
  /** For an array place, the IEC width its declaration gives its elements, as `Array<BYTE>` does. */
31
34
  elementIec?: string;
32
35
  /** For an array place, its layout with the length setup gave it, such as `FixedArray<BYTE, 32>`. */
33
- layout?: string;
36
+ layout?: ArrayLayout;
34
37
  /** For an array place, the length setup gave it, so scan code can visit each element. */
35
38
  length?: number;
36
- /** A module global another module stores into through its setter; an import is read-only. */
37
- setter?: string;
39
+ /** For a place the config's `io` binds to an input, or one holding such a place: the hardware writes it every scan. */
40
+ input?: { path: string; address: string };
38
41
  /**
39
42
  * For a place reached through a runtime index, the same place with its indexes held in
40
43
  * consts, so a name for it keeps meaning the element it named when it was bound.
@@ -45,22 +48,26 @@ export type Value =
45
48
  * the stored object, so writing it here would change nothing the PLC keeps.
46
49
  */
47
50
  copyOf?: string;
51
+ /** A float the program made whole with Math.trunc, floor, ceil or round, which an integer place takes saturated. */
52
+ whole?: true;
48
53
  /** What an `await` gives, typed by the call it awaited. */
49
54
  awaited?: boolean;
55
+ /** What a task's method returns, typed by the task's declaration in its kept module. */
56
+ typedByTask?: boolean;
50
57
  }
51
58
  /**
52
59
  * A reference scan code chooses at run time, among objects setup built. `index` is code for the
53
- * id of the object it holds, one of `options`, or -1 for undefined.
60
+ * id of the object it holds, one of `options`, or `noReference` for undefined.
54
61
  */
55
62
  | {
56
63
  kind: "choice";
57
64
  options: readonly ModelNode[];
58
65
  index: string | Mapped;
59
66
  optional: boolean;
67
+ /** Whether TypeScript narrowed out undefined where this was read, though `optional` says its storage may hold none. */
68
+ narrowed?: boolean;
60
69
  /** Whether `index` is storage scan code can assign: a reference field, or a let. */
61
70
  place?: boolean;
62
- /** A module global's setter, as a code place has. */
63
- setter?: string;
64
71
  }
65
72
  /**
66
73
  * An array of known values a filter decided at run time: every candidate, each with whether the
@@ -115,6 +122,69 @@ export const constant = (
115
122
  value,
116
123
  });
117
124
 
125
+ /** A primitive setup captured, as a value known while specializing. */
126
+ export const capturedPrimitive = (value: CapturedPrimitive): Value => {
127
+ switch (value.kind) {
128
+ case "undefined":
129
+ return constant(undefined);
130
+ case "bigint":
131
+ return constant(BigInt(value.value));
132
+ default:
133
+ return constant(value.value);
134
+ }
135
+ };
136
+
137
+ /** A number setup fixed; undefined for one decided at run time. */
138
+ export const known = (value: Value): number | undefined =>
139
+ value.kind === "const" && typeof value.value === "number"
140
+ ? value.value
141
+ : undefined;
142
+
143
+ /**
144
+ * A number folded now, which the PLC can hold only when finite: NaN and the infinities have no PLC
145
+ * value, as setup capture finds too.
146
+ */
147
+ export const finite = <T>(value: T, at: ts.Node): T => {
148
+ if (typeof value === "number" && !Number.isFinite(value)) {
149
+ throw new SpecializeError(at, `${value} has no PLC value.`);
150
+ }
151
+ return value;
152
+ };
153
+
154
+ /** Each entry `map` holds now, put back by the function returned. */
155
+ export const restoring = <K, V>(map: Map<K, V>): VoidFunction => {
156
+ const saved = [...map];
157
+ return () => {
158
+ map.clear();
159
+ for (const [key, value] of saved) {
160
+ map.set(key, value);
161
+ }
162
+ };
163
+ };
164
+
165
+ /** Whether a value is stored state: a record or array the PLC keeps, or a copy of one. */
166
+ export const isStoredState = (value: Value): boolean =>
167
+ value.kind === "code" &&
168
+ (value.copyOf !== undefined ||
169
+ (value.place === true &&
170
+ value.declared !== undefined &&
171
+ Boolean(value.declared.flags & ts.TypeFlags.Object)));
172
+
173
+ /** Whether a literal's own fields or items hold objects setup built: instances, functions or references to them. */
174
+ export const holdsSetupObjects = (
175
+ value: Extract<Value, { kind: "virtual" }>,
176
+ ): boolean =>
177
+ [...(value.fields?.values() ?? []), ...(value.items ?? [])].some(
178
+ (item) =>
179
+ item.kind === "static" ||
180
+ item.kind === "function" ||
181
+ item.kind === "choice",
182
+ );
183
+
184
+ /** An expression without the wrappers around it. */
185
+ export const unwrapped = (node: ts.Expression): ts.Expression =>
186
+ isWrapper(node) ? unwrapped(node.expression) : node;
187
+
118
188
  /** Whether code names a place or a literal, which reads the same however often it is repeated. */
119
189
  export const repeatable = (text: string | Mapped): boolean =>
120
190
  /^[\w.[\]]+$/.test(String(text));
@@ -1,4 +1,7 @@
1
1
  import ts from "typescript";
2
+ import { valueSymbol } from "../sdk";
3
+ import { unparenthesized } from "../types";
4
+ import { boundNames } from "./capture-protocol";
2
5
 
3
6
  /**
4
7
  * The properties scan code assigns outside constructors. Fields scan code writes are state; the
@@ -23,7 +26,7 @@ export class ScanWrites {
23
26
  }
24
27
  // A union's property is written through any member's declaration of it.
25
28
  return (symbol.declarations ?? []).some((declaration) => {
26
- const own = ownSymbol(declaration);
29
+ const own = this.ownSymbol(declaration);
27
30
  return own !== undefined && this.assigned.has(own);
28
31
  });
29
32
  }
@@ -37,29 +40,7 @@ export class ScanWrites {
37
40
  !ts.isFunctionExpression(node));
38
41
  if (!constructing) {
39
42
  const write = (target: ts.Expression): void => {
40
- const place = unwrapped(target);
41
- // A destructuring assignment writes each of its pattern's targets.
42
- if (ts.isArrayLiteralExpression(place)) {
43
- for (const element of place.elements) {
44
- write(ts.isSpreadElement(element) ? element.expression : element);
45
- }
46
- return;
47
- }
48
- if (ts.isObjectLiteralExpression(place)) {
49
- for (const property of place.properties) {
50
- if (ts.isPropertyAssignment(property)) {
51
- write(property.initializer);
52
- }
53
- }
54
- return;
55
- }
56
- if (
57
- ts.isBinaryExpression(place) &&
58
- place.operatorToken.kind === ts.SyntaxKind.EqualsToken
59
- ) {
60
- write(place.left);
61
- return;
62
- }
43
+ const place = unparenthesized(target, { nonNull: true });
63
44
  if (ts.isPropertyAccessExpression(place)) {
64
45
  this.markAssigned(place.name);
65
46
  } else if (ts.isElementAccessExpression(place)) {
@@ -73,7 +54,7 @@ export class ScanWrites {
73
54
  ts.isBinaryExpression(node) &&
74
55
  isAssignment(node.operatorToken.kind)
75
56
  ) {
76
- write(node.left);
57
+ assignedTargets(node.left).forEach(write);
77
58
  }
78
59
  if (isUpdate(node)) {
79
60
  write(node.operand);
@@ -92,23 +73,19 @@ export class ScanWrites {
92
73
  this.assigned.add(symbol);
93
74
  // A property of a union is a synthetic symbol over each member's own property.
94
75
  for (const declaration of symbol.declarations ?? []) {
95
- const own = ownSymbol(declaration);
76
+ const own = this.ownSymbol(declaration);
96
77
  if (own) {
97
78
  this.assigned.add(own);
98
79
  }
99
80
  }
100
81
  }
101
- }
102
-
103
- /** The symbol a declaration declares, which TypeScript keeps on it but does not expose. */
104
- const ownSymbol = (declaration: ts.Declaration): ts.Symbol | undefined =>
105
- (declaration as { symbol?: ts.Symbol }).symbol;
106
82
 
107
- /** An assignment target without the parentheses and non-null assertions around it. */
108
- const unwrapped = (target: ts.Expression): ts.Expression =>
109
- ts.isParenthesizedExpression(target) || ts.isNonNullExpression(target)
110
- ? unwrapped(target.expression)
111
- : target;
83
+ /** The symbol a declaration declares. */
84
+ private ownSymbol(declaration: ts.Declaration): ts.Symbol | undefined {
85
+ const name = ts.getNameOfDeclaration(declaration);
86
+ return name && this.checker.getSymbolAtLocation(name);
87
+ }
88
+ }
112
89
 
113
90
  /** What an element access chain such as `a.b[1][2]` indexes: `a.b`. */
114
91
  const indexed = (node: ts.Expression): ts.Expression =>
@@ -126,28 +103,68 @@ export const isUpdate = (
126
103
  export const isAssignment = (kind: ts.SyntaxKind): boolean =>
127
104
  kind >= ts.SyntaxKind.FirstAssignment && kind <= ts.SyntaxKind.LastAssignment;
128
105
 
106
+ /**
107
+ * The places an assignment's left side writes: the side itself, or each target a destructuring
108
+ * pattern names, as `[a, { b }, c = 1] = value` writes `a`, `b` and `c`.
109
+ */
110
+ const assignedTargets = (left: ts.Expression): ts.Expression[] => {
111
+ const place = unparenthesized(left, { nonNull: true });
112
+ if (ts.isArrayLiteralExpression(place)) {
113
+ return place.elements.flatMap((element) =>
114
+ assignedTargets(
115
+ ts.isSpreadElement(element) ? element.expression : element,
116
+ ),
117
+ );
118
+ }
119
+ if (ts.isObjectLiteralExpression(place)) {
120
+ return place.properties.flatMap((property) => {
121
+ if (ts.isPropertyAssignment(property)) {
122
+ return assignedTargets(property.initializer);
123
+ }
124
+ if (ts.isShorthandPropertyAssignment(property)) {
125
+ return [property.name];
126
+ }
127
+ if (ts.isSpreadAssignment(property)) {
128
+ return assignedTargets(property.expression);
129
+ }
130
+ return [];
131
+ });
132
+ }
133
+ if (
134
+ ts.isBinaryExpression(place) &&
135
+ place.operatorToken.kind === ts.SyntaxKind.EqualsToken
136
+ ) {
137
+ return assignedTargets(place.left);
138
+ }
139
+ return [left];
140
+ };
141
+
142
+ /** Whether some node in `node` passes `test`, outside the functions it declares, which run apart from it. */
143
+ export const occursOutsideFunctions = (
144
+ node: ts.Node,
145
+ test: (node: ts.Node) => boolean,
146
+ ): boolean =>
147
+ test(node) ||
148
+ (!ts.isFunctionLike(node) &&
149
+ (ts.forEachChild(node, (child) => occursOutsideFunctions(child, test)) ??
150
+ false));
151
+
152
+ /** Whether `node` lies within `container`'s source range. */
153
+ export const within = (node: ts.Node, container: ts.Node): boolean =>
154
+ node.pos >= container.pos && node.end <= container.end;
155
+
129
156
  /** Whether the body assigns or steps any name the binding declares. */
130
157
  export const assignsName = (
131
158
  body: ts.Node,
132
159
  binding: ts.BindingName,
133
160
  checker: ts.TypeChecker,
134
161
  ): boolean => {
135
- const declared = new Set<ts.Symbol>();
136
- const collect = (name: ts.BindingName): void => {
137
- if (ts.isIdentifier(name)) {
162
+ const declared = new Set(
163
+ boundNames(binding).flatMap((name) => {
138
164
  const symbol = checker.getSymbolAtLocation(name);
139
- if (symbol) {
140
- declared.add(symbol);
141
- }
142
- return;
143
- }
144
- for (const element of name.elements) {
145
- if (!ts.isOmittedExpression(element)) {
146
- collect(element.name);
147
- }
148
- }
149
- };
150
- collect(binding);
165
+ return symbol ? [symbol] : [];
166
+ }),
167
+ );
151
168
  return assignsSymbol(body, declared, checker);
152
169
  };
153
170
 
@@ -159,14 +176,14 @@ export const assignsSymbol = (
159
176
  ): boolean => {
160
177
  const target = (node: ts.Expression): boolean => {
161
178
  const symbol = ts.isIdentifier(node)
162
- ? checker.getSymbolAtLocation(node)
179
+ ? valueSymbol(checker, node)
163
180
  : undefined;
164
181
  return symbol !== undefined && declared.has(symbol);
165
182
  };
166
183
  const visit = (node: ts.Node): boolean =>
167
184
  (ts.isBinaryExpression(node) &&
168
185
  isAssignment(node.operatorToken.kind) &&
169
- target(node.left)) ||
186
+ assignedTargets(node.left).some(target)) ||
170
187
  (isUpdate(node) && target(node.operand)) ||
171
188
  (ts.forEachChild(node, visit) ?? false);
172
189
  return visit(body);
@@ -195,7 +212,7 @@ export const writesThrough = (
195
212
  const visit = (node: ts.Node): boolean =>
196
213
  (ts.isBinaryExpression(node) &&
197
214
  isAssignment(node.operatorToken.kind) &&
198
- throughIt(node.left)) ||
215
+ assignedTargets(node.left).some(throughIt)) ||
199
216
  (isUpdate(node) && throughIt(node.operand)) ||
200
217
  (ts.isCallExpression(node) && node.arguments.some(named)) ||
201
218
  (ts.forEachChild(node, visit) ?? false);
@@ -239,26 +256,23 @@ const aliasWindow = (
239
256
  if (
240
257
  ts.isIdentifier(node) &&
241
258
  node !== name &&
242
- checker.getSymbolAtLocation(node) === symbol
259
+ valueSymbol(checker, node) === symbol
243
260
  ) {
244
261
  uses.push(node);
245
262
  }
246
263
  ts.forEachChild(node, collect);
247
264
  };
248
265
  collect(scope);
249
- const contains = (outer: ts.Node, inner: ts.Node): boolean =>
250
- outer.pos <= inner.pos && inner.end <= outer.end;
251
- const reentered = (use: ts.Node): boolean => {
252
- for (let node = use.parent; node && node !== scope; node = node.parent) {
253
- if (
254
- (ts.isIterationStatement(node, false) || ts.isFunctionLike(node)) &&
255
- !contains(node, declaration)
256
- ) {
257
- return true;
266
+ const reentered = (use: ts.Node): boolean =>
267
+ ts.findAncestor(use.parent, (node) => {
268
+ if (node === scope) {
269
+ return "quit";
258
270
  }
259
- }
260
- return false;
261
- };
271
+ return (
272
+ (ts.isIterationStatement(node, false) || ts.isFunctionLike(node)) &&
273
+ !within(declaration, node)
274
+ );
275
+ }) !== undefined;
262
276
  const from = declaration.end;
263
277
  return {
264
278
  scope,
@@ -284,7 +298,7 @@ const runsBetween = (
284
298
 
285
299
  /** The names along a place's path, root first, past `this`; element indexes are left out. */
286
300
  const pathNames = (place: ts.Expression): string[] | undefined => {
287
- const node = unwrapped(place);
301
+ const node = unparenthesized(place, { nonNull: true });
288
302
  if (ts.isIdentifier(node)) {
289
303
  return [node.text];
290
304
  }
@@ -301,7 +315,7 @@ const pathNames = (place: ts.Expression): string[] | undefined => {
301
315
  return undefined;
302
316
  };
303
317
 
304
- /** Each assignment or step in the window, by the place it writes. */
318
+ /** Each assignment's left side and each step's operand in the window. */
305
319
  const writesIn = (window: AliasWindow): ts.Expression[] => {
306
320
  const targets: ts.Expression[] = [];
307
321
  runsBetween(window, (node) => {
@@ -340,6 +354,8 @@ export const stableAlias = (
340
354
  ts.forEachChild(node, readNames);
341
355
  };
342
356
  readNames(window.source);
357
+ // A destructuring assignment names no path, so it counts as writing what the alias reads: an alias
358
+ // that holds its indexes is never wrong.
343
359
  const writesRead = (target: ts.Expression): boolean => {
344
360
  const names = pathNames(target);
345
361
  return names === undefined || names.some((written) => read.has(written));
@@ -377,25 +393,23 @@ export const replacedWhileAliased = (
377
393
  const path =
378
394
  window.property === undefined ? base : [...base, window.property];
379
395
  // Writing the place, or anything on its path, replaces what it holds.
380
- return writesIn(window).some((target) => {
381
- const written = pathNames(target);
382
- const last = written?.at(-1);
383
- return last !== undefined && path.includes(last);
384
- });
396
+ return writesIn(window)
397
+ .flatMap(assignedTargets)
398
+ .some((target) => {
399
+ const written = pathNames(target);
400
+ const last = written?.at(-1);
401
+ return last !== undefined && path.includes(last);
402
+ });
385
403
  };
386
404
 
387
405
  /** The block, clause or source a declaration's name is scoped to. */
388
- const enclosingScope = (node: ts.Node): ts.Node | undefined => {
389
- for (let parent = node.parent; parent; parent = parent.parent) {
390
- if (
406
+ const enclosingScope = (node: ts.Node): ts.Node | undefined =>
407
+ ts.findAncestor(
408
+ node.parent,
409
+ (parent) =>
391
410
  ts.isBlock(parent) ||
392
411
  ts.isSourceFile(parent) ||
393
412
  ts.isCaseClause(parent) ||
394
413
  ts.isDefaultClause(parent) ||
395
- ts.isFunctionLike(parent)
396
- ) {
397
- return parent;
398
- }
399
- }
400
- return undefined;
401
- };
414
+ ts.isFunctionLike(parent),
415
+ );