@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,4 +1,10 @@
1
- // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
1
+ import { calendarLiteral } from "@tsplc/compiler/ir";
2
+ import { elementaryType } from "@tsplc/iec";
3
+ import {
4
+ type ElementaryFunction,
5
+ elementaryFunctions,
6
+ elementaryValue,
7
+ } from "@tsplc/iec/arithmetic";
2
8
  import ts from "typescript";
3
9
  import {
4
10
  copied,
@@ -8,200 +14,383 @@ import {
8
14
  mapped,
9
15
  type Part,
10
16
  } from "../positions";
11
- import { declaredBySdk, inSdk, sdkModule, symbolAt } from "../sdk";
12
- import { ArraySearches } from "./array-searches";
13
- import type { DialectText } from "./dialect";
14
- import type { ExpressionSpecializer, SpecializeContext } from "./expressions";
17
+ import {
18
+ declaredBySdk,
19
+ inSdk,
20
+ isTelemetryDeclaration,
21
+ sdkModule,
22
+ sdkModules,
23
+ symbolAt,
24
+ unaliased,
25
+ valueSymbol,
26
+ } from "../sdk";
27
+ import { ArraySearches, callbackArgument, ordered } from "./array-searches";
28
+ import { isGlobal } from "./declarations";
29
+ import {
30
+ type ExpressionSpecializer,
31
+ type Holding,
32
+ isPromiseLink,
33
+ type SpecializeContext,
34
+ } from "./expressions";
15
35
  import type { Frame } from "./frame";
16
- import type { EntryImports } from "./imports";
17
- import type { Model, ModelNode } from "./model";
18
- import type { Storage } from "./storage";
36
+ import type { ModelNode } from "./model";
37
+ import { calendarFormats, durationNames } from "./time-constructors";
19
38
  import {
20
39
  constant,
21
40
  type FunctionLike,
22
- repeatable,
41
+ finite,
23
42
  SpecializeError,
43
+ unwrapped,
24
44
  type Value,
25
45
  } from "./values";
26
46
 
47
+ /** What calls read from the expression specializer: evaluation, invocation, and the specializers for array values. */
48
+ type CallParts = Pick<
49
+ ExpressionSpecializer,
50
+ | "expression"
51
+ | "invoke"
52
+ | "inOrder"
53
+ | "member"
54
+ | "superMember"
55
+ | "recordFields"
56
+ | "shorthand"
57
+ | "items"
58
+ | "element"
59
+ | "canceller"
60
+ | "chained"
61
+ | "held"
62
+ | "hold"
63
+ | "localType"
64
+ | "equality"
65
+ | "assignments"
66
+ | "references"
67
+ | "filteredArrays"
68
+ | "iterators"
69
+ >;
70
+
27
71
  /** Specializes calls: to what the language and SDK provide, to the service client, and to functions. */
28
72
  export class CallSpecializer {
29
- private readonly model: Model;
30
- private readonly checker: ts.TypeChecker;
31
- private readonly dialect: DialectText;
32
- private readonly storage: Storage;
33
- private readonly imports: EntryImports;
34
- private readonly sdkFile: string;
35
- private readonly sources: readonly ts.SourceFile[];
36
-
37
73
  private readonly searches: ArraySearches;
38
74
 
39
75
  constructor(
40
- context: SpecializeContext,
41
- private readonly expressions: ExpressionSpecializer,
76
+ private readonly context: SpecializeContext,
77
+ private readonly expressions: CallParts,
42
78
  ) {
43
79
  this.searches = new ArraySearches(context, expressions);
44
- this.model = context.model;
45
- this.checker = context.checker;
46
- this.dialect = context.dialect;
47
- this.storage = context.storage;
48
- this.imports = context.imports;
49
- this.sdkFile = context.sdkFile;
50
- this.sources = context.sources;
51
80
  }
52
81
 
53
82
  call(node: ts.CallExpression, frame: Frame, expected?: ts.Type): Value {
54
83
  const callee = node.expression;
55
- // Array methods and other calls the language provides.
56
84
  if (
57
85
  ts.isPropertyAccessExpression(callee) ||
58
86
  ts.isPropertyAccessChain(callee)
59
87
  ) {
60
- const name = callee.name.text;
61
- if (
62
- ts.isIdentifier(callee.expression) &&
63
- callee.expression.text === "Array" &&
64
- name === "from"
65
- ) {
66
- return this.arrayFrom(node, frame);
67
- }
68
- if (callee.expression.kind === ts.SyntaxKind.SuperKeyword) {
69
- const method = this.expressions.superMember(callee, frame);
70
- return this.expressions.invoke(
71
- method,
72
- this.expressions.inOrder(
73
- node.arguments,
74
- (argument, index) => this.argument(argument, method, index, frame),
75
- frame,
76
- ),
77
- node,
78
- frame,
79
- expected,
80
- );
81
- }
82
- if (
83
- ts.isIdentifier(callee.expression) &&
84
- callee.expression.text === "Math"
85
- ) {
86
- return this.math(name, node, frame);
87
- }
88
- if (
89
- ts.isIdentifier(callee.expression) &&
90
- callee.expression.text === "Object" &&
91
- name === "values"
92
- ) {
93
- const [argument] = node.arguments;
94
- const object = argument && this.expressions.expression(argument, frame);
95
- if (
96
- object?.kind === "static" &&
97
- object.node.captured.kind === "object"
98
- ) {
99
- return {
100
- kind: "virtual",
101
- items: Object.entries(object.node.captured.fields).map(
102
- ([field, value]) =>
103
- this.storage.fromCaptured(value, object.node, {
104
- kind: "field",
105
- name: field,
106
- }),
107
- ),
108
- };
109
- }
110
- throw new SpecializeError(
111
- node,
112
- "Object.values needs a record setup built.",
113
- );
114
- }
115
- if (this.telemetryCall(callee)) {
116
- return {
117
- kind: "code",
118
- text: this.telemetry(node, callee, frame),
119
- declared: this.checker.getTypeAtLocation(node),
120
- };
121
- }
122
- const iterated = this.expressions.iterators.call(node, frame);
123
- if (iterated) {
124
- return iterated;
125
- }
126
- const receiver = this.expressions.expression(callee.expression, frame);
127
- const counted = this.expressions.iterators.receiver(receiver, name);
128
- if (counted) {
129
- return this.expressions.iterators.method(name, counted, node, frame);
130
- }
131
- const items = this.expressions.items(receiver);
132
- const referred = this.expressions.references.call(
133
- name,
134
- receiver,
135
- items,
136
- node,
137
- frame,
138
- expected,
139
- );
140
- if (referred) {
141
- return referred;
142
- }
143
- if (items && arrayMethods.has(name)) {
144
- return this.arrayMethod(name, receiver, items, node, frame);
145
- }
146
- if (
147
- receiver.kind === "static" &&
148
- receiver.node.captured.kind === "service"
149
- ) {
150
- const path = receiver.node.captured.path
151
- ? `${receiver.node.captured.path}.${name}`
152
- : name;
153
- return this.serviceCall(path, node, frame);
154
- }
155
- const method = this.expressions.member(receiver, name, callee, frame);
156
- if (method.kind === "static" && method.node.captured.kind === "service") {
157
- return this.serviceCall(method.node.captured.path, node, frame);
158
- }
159
- return this.expressions.invoke(
160
- method,
161
- this.expressions.inOrder(
162
- node.arguments,
163
- (argument, index) => this.argument(argument, method, index, frame),
164
- frame,
165
- ),
166
- node,
167
- frame,
168
- expected,
169
- );
88
+ return this.method(node, callee, frame, expected);
170
89
  }
171
- if (ts.isIdentifier(callee) && callee.text === "structuredClone") {
90
+ if (isGlobal(this.context.checker, callee, "structuredClone")) {
172
91
  return this.cloned(node, frame);
173
92
  }
174
93
  const target = this.expressions.expression(callee, frame);
94
+ // `f?.()` of a function setup left undefined calls nothing.
95
+ if (
96
+ node.questionDotToken &&
97
+ target.kind === "const" &&
98
+ target.value === undefined
99
+ ) {
100
+ return constant(undefined);
101
+ }
102
+ if (target.kind === "static" && target.node.captured.kind === "task") {
103
+ return this.taskCall(target.node, null, node, frame);
104
+ }
175
105
  if (target.kind === "static" && target.node.captured.kind === "service") {
176
106
  return this.serviceCall(target.node.captured.path, node, frame);
177
107
  }
178
108
  if (target.kind === "static" && target.node.captured.kind === "function") {
179
- const fn = this.functionDeclaration(
109
+ const declaration = this.functionDeclaration(
180
110
  target.node.captured.file,
181
111
  target.node.captured.name,
182
112
  );
183
- return this.expressions.invoke(
184
- { kind: "function", declaration: fn },
185
- this.expressions.inOrder(
186
- node.arguments,
187
- (argument, index) =>
188
- this.argument(
189
- argument,
190
- { kind: "function", declaration: fn },
191
- index,
192
- frame,
193
- ),
194
- frame,
195
- ),
113
+ return this.invokeCall(
114
+ { kind: "function", declaration },
196
115
  node,
197
116
  frame,
198
117
  expected,
199
118
  );
200
119
  }
201
120
  const sdkFile = ts.isIdentifier(callee) && this.sdkDeclaration(callee);
121
+ if (
122
+ ts.isIdentifier(callee) &&
123
+ sdkFile &&
124
+ callee.text === "cancelAsync" &&
125
+ sdkModule(sdkFile) === sdkModules.async &&
126
+ node.arguments.length
127
+ ) {
128
+ return this.cancelOwner(node, frame);
129
+ }
202
130
  if (ts.isIdentifier(callee) && sdkFile) {
203
131
  return this.sdk(callee.text, sdkModule(sdkFile), node, frame);
204
132
  }
133
+ return this.invokeCall(target, node, frame, expected);
134
+ }
135
+
136
+ /** `receiver.name(…)`: what the language and SDK provide on the receiver, or its method. */
137
+ private method(
138
+ node: ts.CallExpression,
139
+ callee: ts.PropertyAccessExpression,
140
+ frame: Frame,
141
+ expected: ts.Type | undefined,
142
+ ): Value {
143
+ const name = callee.name.text;
144
+ const checker = this.context.checker;
145
+ if (name === "from" && isGlobal(checker, callee.expression, "Array")) {
146
+ return this.arrayFrom(node, frame);
147
+ }
148
+ if (callee.expression.kind === ts.SyntaxKind.SuperKeyword) {
149
+ return this.invokeCall(
150
+ this.expressions.superMember(callee, frame),
151
+ node,
152
+ frame,
153
+ expected,
154
+ );
155
+ }
156
+ if (isGlobal(checker, callee.expression, "Math")) {
157
+ return this.math(name, node, frame);
158
+ }
159
+ if (name === "values" && isGlobal(checker, callee.expression, "Object")) {
160
+ return this.objectValues(node, frame);
161
+ }
162
+ if (this.telemetryCall(callee)) {
163
+ return {
164
+ kind: "code",
165
+ text: this.telemetry(node, callee, frame),
166
+ declared: checker.getTypeAtLocation(node),
167
+ };
168
+ }
169
+ if (isPromiseLink(node) && this.isPromise(callee.expression)) {
170
+ return this.promiseLink(node, callee, frame);
171
+ }
172
+ const iterated = this.expressions.iterators.call(node, frame);
173
+ if (iterated) {
174
+ return iterated;
175
+ }
176
+ const receiver = this.receiver(callee.expression, frame);
177
+ if (receiver.kind === "static" && receiver.node.captured.kind === "task") {
178
+ return this.taskCall(receiver.node, name, node, frame);
179
+ }
180
+ const counted = this.expressions.iterators.arrayCall(
181
+ name,
182
+ receiver,
183
+ node,
184
+ frame,
185
+ );
186
+ if (counted) {
187
+ return counted;
188
+ }
189
+ if (receiver.kind === "choice") {
190
+ const call = () =>
191
+ this.expressions.references.call(receiver, name, node, frame, expected);
192
+ return callee.questionDotToken && receiver.optional
193
+ ? this.expressions.chained(receiver, call, node, frame)
194
+ : call();
195
+ }
196
+ const items = this.expressions.items(receiver);
197
+ const filtered = this.expressions.filteredArrays.call(
198
+ name,
199
+ receiver,
200
+ items,
201
+ node,
202
+ frame,
203
+ );
204
+ if (filtered) {
205
+ return filtered;
206
+ }
207
+ if (items && isArrayMethod(name)) {
208
+ return this.arrayMethod(name, receiver, items, node, frame);
209
+ }
210
+ const method = this.expressions.member(receiver, name, callee, frame);
211
+ if (
212
+ node.questionDotToken &&
213
+ method.kind === "const" &&
214
+ method.value === undefined
215
+ ) {
216
+ return constant(undefined);
217
+ }
218
+ if (method.kind === "static" && method.node.captured.kind === "service") {
219
+ return this.serviceCall(method.node.captured.path, node, frame);
220
+ }
221
+ return this.invokeCall(method, node, frame, expected);
222
+ }
223
+
224
+ /**
225
+ * What a method is called on. An element of an array of objects setup built, at an index decided
226
+ * at run time, is a reference to whichever it is, so the call runs that object's method.
227
+ */
228
+ private receiver(node: ts.Expression, frame: Frame): Value {
229
+ const inner = unwrapped(node);
230
+ if (!ts.isElementAccessExpression(inner)) {
231
+ return this.expressions.expression(node, frame);
232
+ }
233
+ const object = this.expressions.expression(inner.expression, frame);
234
+ const index = this.expressions.expression(inner.argumentExpression, frame);
235
+ const items =
236
+ object.kind === "static" && object.node.captured.kind === "array"
237
+ ? this.expressions.items(object)
238
+ : undefined;
239
+ const chosen =
240
+ items?.every(
241
+ (item) =>
242
+ item.kind === "static" && item.node.captured.kind === "instance",
243
+ ) &&
244
+ this.expressions.filteredArrays.indexed(
245
+ items,
246
+ index,
247
+ { fromEnd: false },
248
+ inner,
249
+ frame,
250
+ );
251
+ return chosen || this.expressions.element(object, index, inner, frame);
252
+ }
253
+
254
+ /** `cancelAsync(object)`: cancels the pending async calls of that object's methods. */
255
+ private cancelOwner(node: ts.CallExpression, frame: Frame): Value {
256
+ const [argument, ...rest] = node.arguments;
257
+ const owner = argument && this.expressions.expression(argument, frame);
258
+ if (
259
+ rest.length ||
260
+ owner?.kind !== "static" ||
261
+ owner.node.captured.kind !== "instance"
262
+ ) {
263
+ throw new SpecializeError(
264
+ node,
265
+ "cancelAsync takes an object setup built, such as this, whose pending async calls it cancels, or no argument to cancel every pending async call.",
266
+ );
267
+ }
268
+ frame.emitter.line(`${this.expressions.canceller(owner.node)}();`);
269
+ return constant(undefined);
270
+ }
271
+
272
+ /** Whether an expression is a promise: an async call TypeScript types as one. */
273
+ private isPromise(node: ts.Expression): boolean {
274
+ const type = this.context.checker.getTypeAtLocation(node);
275
+ return this.context.checker.getAwaitedType(type) !== type;
276
+ }
277
+
278
+ /**
279
+ * `promise.then(fulfilled, rejected)` or `promise.catch(rejected)`, awaited in an async routine:
280
+ * the promise awaited into a local and the callback run on its value, or on its error code in the
281
+ * catch block of a try around both. The link's value is what the await of it gives.
282
+ */
283
+ private promiseLink(
284
+ node: ts.CallExpression,
285
+ callee: ts.PropertyAccessExpression,
286
+ frame: Frame,
287
+ ): Value {
288
+ const name = callee.name.text;
289
+ if (!frame.async || !awaitedLink(node)) {
290
+ throw new SpecializeError(
291
+ node,
292
+ `.${name} runs only where an async function awaits it: in an async function, write const value = await call(); inside a try, and handle the value, or the error in catch.`,
293
+ );
294
+ }
295
+ const { checker, initializers } = this.context;
296
+ const [first, second] = node.arguments;
297
+ const fulfilled = name === "then" ? first : undefined;
298
+ const rejected = name === "then" ? second : first;
299
+ const result = checker.getAwaitedType(checker.getTypeAtLocation(node));
300
+ const resultType =
301
+ result && !(result.flags & ts.TypeFlags.Void) ? result : undefined;
302
+ const fulfil = (): Value => {
303
+ const value = this.awaitedValue(
304
+ this.expressions.expression(callee.expression, frame),
305
+ frame,
306
+ );
307
+ return fulfilled ? this.handled(fulfilled, [value], frame) : value;
308
+ };
309
+ if (!rejected) {
310
+ return fulfil();
311
+ }
312
+ const local = resultType && frame.emitter.temporary();
313
+ if (local && resultType) {
314
+ frame.emitter.line(
315
+ `let ${local}: ${this.expressions.localType(resultType)} = ${initializers.defaultOf(resultType)};`,
316
+ );
317
+ }
318
+ const store = (value: Value) => {
319
+ if (local) {
320
+ frame.emitter.line(
321
+ mapped`${local} = ${this.context.dialect.assignmentText(value, resultType, undefined)};`,
322
+ );
323
+ }
324
+ };
325
+ frame.emitter.open("try {");
326
+ store(fulfil());
327
+ const error = frame.emitter.local("error");
328
+ frame.emitter.reopen(`} catch (${error}) {`);
329
+ // The callback is given the error code, as errorCode reads it from the catch binding.
330
+ const code = frame.emitter.local("code");
331
+ this.context.imports.addSdk(sdkModules.async, "errorCode");
332
+ frame.emitter.line(`const ${code}: UDINT = errorCode(${error});`);
333
+ store(
334
+ this.handled(
335
+ rejected,
336
+ [
337
+ {
338
+ kind: "code",
339
+ text: code,
340
+ declared: checker.getNumberType(),
341
+ place: true,
342
+ iec: "UDINT",
343
+ },
344
+ ],
345
+ frame,
346
+ ),
347
+ );
348
+ frame.emitter.close();
349
+ return local
350
+ ? { kind: "code", text: local, declared: resultType, place: true }
351
+ : constant(undefined);
352
+ }
353
+
354
+ /** What awaiting a promise gives: the call awaited into a local, or nothing for a void one. */
355
+ private awaitedValue(promise: Value, frame: Frame): Value {
356
+ if (promise.kind !== "code") {
357
+ return promise;
358
+ }
359
+ if (!promise.declared || promise.declared.flags & ts.TypeFlags.Void) {
360
+ frame.emitter.line(mapped`await ${promise.text};`);
361
+ return constant(undefined);
362
+ }
363
+ const local = frame.emitter.temporary();
364
+ frame.emitter.line(mapped`const ${local} = await ${promise.text};`);
365
+ return {
366
+ kind: "code",
367
+ text: local,
368
+ declared: promise.declared,
369
+ place: true,
370
+ iec: promise.iec,
371
+ };
372
+ }
373
+
374
+ /** A link's callback run on `args`; an async callback's promise is awaited too. */
375
+ private handled(callback: ts.Expression, args: Value[], frame: Frame): Value {
376
+ const target = this.expressions.expression(callback, frame);
377
+ const value = this.expressions.invoke(target, args, callback, frame);
378
+ const isAsync =
379
+ target.kind === "function" &&
380
+ ts.canHaveModifiers(target.declaration) &&
381
+ ts
382
+ .getModifiers(target.declaration)
383
+ ?.some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword);
384
+ return isAsync ? this.awaitedValue(value, frame) : value;
385
+ }
386
+
387
+ /** Calls a function value with the call's arguments, each evaluated for the parameter it is passed to. */
388
+ private invokeCall(
389
+ target: Value,
390
+ node: ts.CallExpression,
391
+ frame: Frame,
392
+ expected: ts.Type | undefined,
393
+ ): Value {
205
394
  return this.expressions.invoke(
206
395
  target,
207
396
  this.expressions.inOrder(
@@ -229,12 +418,12 @@ export class CallSpecializer {
229
418
  return this.expressions.expression(
230
419
  node,
231
420
  frame,
232
- parameter && this.checker.getTypeAtLocation(parameter),
421
+ parameter && this.context.checker.getTypeAtLocation(parameter),
233
422
  );
234
423
  }
235
424
 
236
425
  private functionDeclaration(file: string, name: string): FunctionLike {
237
- const source = this.sources.find((item) => item.fileName === file);
426
+ const source = this.context.sources.find((item) => item.fileName === file);
238
427
  for (const statement of source?.statements ?? []) {
239
428
  if (
240
429
  ts.isFunctionDeclaration(statement) &&
@@ -259,29 +448,27 @@ export class CallSpecializer {
259
448
  throw new Error(`${file}: no function ${name}.`);
260
449
  }
261
450
 
262
- /** SDK functions scan code calls, such as the PLC clock. */
263
451
  /** The SDK declaration file of the function `callee` names, or null when the SDK doesn't declare it. */
264
452
  private sdkDeclaration(callee: ts.Identifier): string | null {
265
- const symbol = symbolAt(this.checker, callee);
266
- if (symbol === undefined || !declaredBySdk(this.sdkFile, symbol)) {
453
+ const sdkFile = this.context.sdkFile;
454
+ const symbol = symbolAt(this.context.checker, callee);
455
+ if (symbol === undefined || !declaredBySdk(sdkFile, symbol)) {
267
456
  return null;
268
457
  }
269
458
  return (
270
459
  symbol.declarations
271
460
  ?.map((declaration) => declaration.getSourceFile().fileName)
272
- .find((file) => inSdk(this.sdkFile, file)) ?? null
461
+ .find((file) => inSdk(sdkFile, file)) ?? null
273
462
  );
274
463
  }
275
464
 
276
465
  /** A method of `@tsplc/compiler/telemetry`'s `telemetry`. */
277
466
  private telemetryCall(callee: ts.PropertyAccessExpression): boolean {
278
- const file = this.checker
279
- .getSymbolAtLocation(callee.name)
280
- ?.declarations?.[0]?.getSourceFile().fileName;
467
+ const declaration = this.context.checker.getSymbolAtLocation(callee.name)
468
+ ?.declarations?.[0];
281
469
  return (
282
- file !== undefined &&
283
- inSdk(this.sdkFile, file) &&
284
- file.endsWith("/telemetry.d.ts")
470
+ declaration !== undefined &&
471
+ isTelemetryDeclaration(this.context.sdkFile, declaration)
285
472
  );
286
473
  }
287
474
 
@@ -294,15 +481,16 @@ export class CallSpecializer {
294
481
  callee: ts.PropertyAccessExpression,
295
482
  frame: Frame,
296
483
  ): Mapped {
484
+ const { checker, dialect } = this.context;
297
485
  const value = (argument: ts.Expression): Part =>
298
486
  ts.isCallExpression(argument) &&
299
487
  ts.isPropertyAccessExpression(argument.expression) &&
300
488
  this.telemetryCall(argument.expression)
301
489
  ? this.telemetry(argument, argument.expression, frame)
302
490
  : // A folded enum field keeps its type, so it is sent as its member's name.
303
- this.dialect.code(
491
+ dialect.code(
304
492
  this.expressions.expression(argument, frame),
305
- this.checker.getTypeAtLocation(argument),
493
+ checker.getTypeAtLocation(argument),
306
494
  );
307
495
  const args = node.arguments.map((argument): Part => {
308
496
  if (
@@ -311,77 +499,129 @@ export class CallSpecializer {
311
499
  ) {
312
500
  return copied(argument);
313
501
  }
314
- // Properties held in a record are sent field by field, as an object literal's are.
315
- const argumentType = this.checker.getTypeAtLocation(argument);
502
+ if (ts.isObjectLiteralExpression(argument)) {
503
+ return this.telemetryProperties(argument, value, frame);
504
+ }
505
+ const argumentType = checker.getTypeAtLocation(argument);
316
506
  if (
317
- !ts.isObjectLiteralExpression(argument) &&
318
507
  argumentType.flags & ts.TypeFlags.Object &&
319
- !this.checker.isArrayType(argumentType)
508
+ !checker.isArrayType(argumentType)
320
509
  ) {
321
510
  const fields = this.expressions
322
511
  .recordFields(argument, frame)
323
512
  .map(
324
513
  ([name, field]) =>
325
- mapped`${name}: ${this.dialect.code(field, undefined)}`,
514
+ mapped`${name}: ${dialect.code(field, undefined)}`,
326
515
  );
327
516
  return mapped`{ ${joined(fields, ", ")} }`;
328
517
  }
329
- if (!ts.isObjectLiteralExpression(argument)) {
330
- return value(argument);
331
- }
332
- const properties = argument.properties.flatMap((property): Part[] => {
333
- if (ts.isShorthandPropertyAssignment(property)) {
334
- // The name reads the local it names, not the property it declares.
335
- const symbol =
336
- this.checker.getShorthandAssignmentValueSymbol(property);
337
- const local = symbol && frame.env.get(symbol);
338
- return [
339
- local
340
- ? mapped`${copied(property.name)}: ${this.dialect.code(local, this.checker.getTypeAtLocation(property.name))}`
341
- : mapped`${copied(property.name)}: ${value(property.name)}`,
342
- ];
343
- }
344
- if (ts.isSpreadAssignment(property)) {
345
- return this.expressions
346
- .spreadFields(property, frame)
347
- .map(
348
- ([name, field]) =>
349
- mapped`${name}: ${this.dialect.code(field, undefined)}`,
350
- );
351
- }
352
- if (!ts.isPropertyAssignment(property)) {
353
- throw new SpecializeError(property, "Name each telemetry property.");
354
- }
355
- return [
356
- mapped`${copied(property.name)}: ${value(property.initializer)}`,
357
- ];
358
- });
359
- return mapped`{ ${joined(properties, ", ")} }`;
518
+ return value(argument);
360
519
  });
361
- this.imports.telemetry = true;
520
+ this.context.imports.addSdk(sdkModules.telemetry, "telemetry");
362
521
  return from(
363
522
  node,
364
523
  mapped`telemetry.${callee.name.text}(${joined(args, ", ")})`,
365
524
  );
366
525
  }
367
526
 
527
+ private telemetryProperties(
528
+ argument: ts.ObjectLiteralExpression,
529
+ value: (argument: ts.Expression) => Part,
530
+ frame: Frame,
531
+ ): Mapped {
532
+ const { checker, dialect } = this.context;
533
+ const properties = argument.properties.flatMap((property): Part[] => {
534
+ if (ts.isShorthandPropertyAssignment(property)) {
535
+ return [
536
+ mapped`${copied(property.name)}: ${dialect.code(this.expressions.shorthand(property, frame), checker.getTypeAtLocation(property.name))}`,
537
+ ];
538
+ }
539
+ if (ts.isSpreadAssignment(property)) {
540
+ return this.expressions
541
+ .recordFields(property.expression, frame)
542
+ .map(
543
+ ([name, field]) =>
544
+ mapped`${name}: ${dialect.code(field, undefined)}`,
545
+ );
546
+ }
547
+ if (!ts.isPropertyAssignment(property)) {
548
+ throw new SpecializeError(property, "Name each telemetry property.");
549
+ }
550
+ return [mapped`${copied(property.name)}: ${value(property.initializer)}`];
551
+ });
552
+ return mapped`{ ${joined(properties, ", ")} }`;
553
+ }
554
+
555
+ /** An SDK function scan code calls, such as the PLC clock. */
368
556
  private sdk(
369
557
  name: string,
370
558
  module: string,
371
559
  node: ts.CallExpression,
372
560
  frame: Frame,
373
561
  ): Value {
562
+ // A record built in scan code, such as fetch's `json`, is written as the type it was declared.
563
+ const code = (argument: ts.Expression) => {
564
+ const value = this.expressions.expression(argument, frame);
565
+ if (module === sdkModules.types) {
566
+ refuseTimeArgument(name, value, argument);
567
+ }
568
+ return this.context.dialect.code(
569
+ value,
570
+ value.kind === "virtual"
571
+ ? this.context.checker.getTypeAtLocation(argument)
572
+ : undefined,
573
+ );
574
+ };
575
+ // An options record, such as fetch's, is the SDK's own type: its fields are written as given.
374
576
  const args = node.arguments.map((argument) =>
375
- this.dialect.code(
376
- this.expressions.expression(argument, frame),
377
- undefined,
378
- ),
577
+ ts.isObjectLiteralExpression(argument)
578
+ ? mapped`{ ${joined(
579
+ argument.properties.map((property) => {
580
+ if (ts.isShorthandPropertyAssignment(property)) {
581
+ return mapped`${copied(property.name)}: ${this.context.dialect.code(this.expressions.shorthand(property, frame), undefined)}`;
582
+ }
583
+ if (!ts.isPropertyAssignment(property)) {
584
+ throw new SpecializeError(property, "Name each option.");
585
+ }
586
+ return mapped`${copied(property.name)}: ${code(property.initializer)}`;
587
+ }),
588
+ ", ",
589
+ )} }`
590
+ : code(argument),
379
591
  );
380
- this.imports.addSdk(module, name);
592
+ // A type argument names the operation's IEC type, which no resolved TypeScript type keeps.
593
+ const typeArguments = (node.typeArguments ?? []).map((argument) =>
594
+ elementaryType(argument.getText())
595
+ ? argument.getText()
596
+ : this.context.layouts.text(
597
+ this.context.checker.getTypeFromTypeNode(argument),
598
+ ),
599
+ );
600
+ const generic = typeArguments.length ? `<${typeArguments.join(", ")}>` : "";
601
+ this.context.imports.addSdk(module, name);
602
+ const text = mapped`${name}${generic}(${joined(args, ", ")})`;
603
+ const declared = this.context.checker.getTypeAtLocation(node);
604
+ // A record the SDK returns is held in a const its own declaration types, so its fields are read
605
+ // from storage and keep the widths the SDK gives them.
606
+ if (module === sdkModules.async && name === "asyncDiagnostics") {
607
+ const local = frame.emitter.temporary();
608
+ frame.emitter.line(mapped`const ${local} = ${text};`);
609
+ return { kind: "code", text: local, declared, place: true };
610
+ }
611
+ // A numeric operation's result is of the IEC type its type argument names, as `div<UDINT>` is,
612
+ // or else the one its declaration names, as errorCode's UDINT.
613
+ const [width] = typeArguments;
614
+ const iec =
615
+ width && elementaryType(width)
616
+ ? width
617
+ : this.context.layouts.iecName(
618
+ symbolAt(this.context.checker, node.expression)?.valueDeclaration,
619
+ );
381
620
  return {
382
621
  kind: "code",
383
- text: mapped`${name}(${joined(args, ", ")})`,
384
- declared: this.checker.getTypeAtLocation(node),
622
+ text,
623
+ declared,
624
+ ...(iec && declared.flags & ts.TypeFlags.NumberLike && { iec }),
385
625
  };
386
626
  }
387
627
 
@@ -392,36 +632,58 @@ export class CallSpecializer {
392
632
  const values = args.flatMap((arg) =>
393
633
  arg.kind === "const" && typeof arg.value === "number" ? [arg.value] : [],
394
634
  );
395
- if (values.length === args.length) {
396
- const folded = (
397
- Math as unknown as Record<string, (...items: number[]) => number>
398
- )[name]?.(...values);
399
- if (typeof folded === "number") {
400
- return constant(folded);
401
- }
635
+ const fold = mathFolds.get(name);
636
+ if (fold && values.length === args.length) {
637
+ return constant(finite(fold(...values), node));
402
638
  }
403
- const texts = args.map((arg) => this.dialect.code(arg, undefined));
404
- const declared = this.checker.getTypeAtLocation(node);
639
+ if (name === "random") {
640
+ throw new SpecializeError(
641
+ node,
642
+ "Math.random has no PLC equivalent: keep a pseudo-random sequence in a UDINT field instead, stepped each time with wrapAdd and wrapMultiply from @tsplc/compiler/types.",
643
+ );
644
+ }
645
+ const declared = this.context.checker.getTypeAtLocation(node);
405
646
  switch (name) {
406
647
  case "abs": {
407
- const local = frame.emitter.temporary();
408
- frame.emitter.line(mapped`const ${local}: number = ${texts[0]!};`);
648
+ const [operand] = args;
649
+ if (!operand) {
650
+ throw new SpecializeError(node, "Math.abs needs a value.");
651
+ }
652
+ const held =
653
+ operand.kind === "code"
654
+ ? this.expressions.hold(operand, frame, comparedOperand)
655
+ : operand;
656
+ const text = this.context.dialect.code(held, undefined);
657
+ // A float negates exactly; an integer's most negative value wraps to itself, as `0 - x` does.
658
+ const negated = floatIec(held) ? mapped`-${text}` : mapped`0 - ${text}`;
409
659
  return {
410
660
  kind: "code",
411
- text: `(${local} < 0 ? 0 - ${local} : ${local})`,
661
+ text: mapped`(${text} < 0 ? ${negated} : ${text})`,
412
662
  declared,
663
+ iec: held.kind === "code" ? held.iec : undefined,
413
664
  };
414
665
  }
415
666
  case "min":
416
667
  case "max": {
417
- const [left, right, ...rest] = texts;
668
+ const [left, right, ...rest] = args;
418
669
  if (left === undefined || right === undefined || rest.length) {
419
670
  throw new SpecializeError(node, `Math.${name} takes two values.`);
420
671
  }
672
+ // Each operand is read twice, so one that computes is held and runs once.
673
+ const operand = (value: Value) =>
674
+ value.kind === "code"
675
+ ? this.expressions.hold(value, frame, comparedOperand)
676
+ : value;
677
+ // Both operands at one width, which the result keeps, so its range proof follows them.
678
+ const {
679
+ texts: [first, second],
680
+ iec,
681
+ } = this.context.dialect.arithmetic(operand(left), operand(right));
421
682
  return {
422
683
  kind: "code",
423
- text: mapped`(${left} ${name === "min" ? "<" : ">"} ${right} ? ${left} : ${right})`,
684
+ text: mapped`(${first} ${name === "min" ? "<" : ">"} ${second} ? ${first} : ${second})`,
424
685
  declared,
686
+ iec,
425
687
  };
426
688
  }
427
689
  default:
@@ -429,55 +691,138 @@ export class CallSpecializer {
429
691
  }
430
692
  }
431
693
 
694
+ /**
695
+ * A call of a task's `start`, `snapshot`, `cancel` or `reset`, through the binding a kept module
696
+ * defines the task in, which the async lowering compiles as the dialect's task.
697
+ */
698
+ private taskCall(
699
+ task: ModelNode,
700
+ name: string | null,
701
+ node: ts.CallExpression,
702
+ frame: Frame,
703
+ ): Value {
704
+ const { model, checker, dialect, imports } = this.context;
705
+ const root = model.roots.find(
706
+ (item) => item.value.kind === "node" && item.value.id === task.id,
707
+ );
708
+ if (!root || !this.context.isKept(root.file)) {
709
+ throw new SpecializeError(
710
+ node,
711
+ "Define a task in a module-level const of a module that holds only constants, tasks and the service client.",
712
+ );
713
+ }
714
+ const work = this.workFunction(root.declaration);
715
+ if (work) {
716
+ this.refuseStateInWork(work);
717
+ }
718
+ imports.kept.add(root.file, root.name);
719
+ const args = node.arguments.map((argument) => {
720
+ const contextual = checker.getContextualType(argument);
721
+ return dialect.code(
722
+ this.expressions.expression(argument, frame, contextual),
723
+ contextual,
724
+ );
725
+ });
726
+ // Calling a background task itself runs it and gives a promise of its result, as awaiting does.
727
+ return {
728
+ kind: "code",
729
+ text:
730
+ name === null
731
+ ? mapped`${root.name}(${joined(args, ", ")})`
732
+ : mapped`${root.name}.${name}(${joined(args, ", ")})`,
733
+ declared:
734
+ name === null
735
+ ? checker.getAwaitedType(checker.getTypeAtLocation(node))
736
+ : checker.getTypeAtLocation(node),
737
+ typedByTask: true,
738
+ ...(name === null && { iec: this.context.layouts.iecName(work) }),
739
+ };
740
+ }
741
+
742
+ /** The named async function a task definition runs. */
743
+ private workFunction(
744
+ declaration: ts.VariableDeclaration | ts.BindingElement,
745
+ ): ts.FunctionDeclaration | undefined {
746
+ const init = declaration.initializer;
747
+ const work =
748
+ init && ts.isCallExpression(init) ? init.arguments[0] : undefined;
749
+ const symbol =
750
+ work && ts.isIdentifier(work)
751
+ ? this.context.checker.getSymbolAtLocation(work)
752
+ : undefined;
753
+ const fn =
754
+ symbol && unaliased(this.context.checker, symbol).valueDeclaration;
755
+ return fn && ts.isFunctionDeclaration(fn) && fn.body ? fn : undefined;
756
+ }
757
+
758
+ /**
759
+ * A task's work runs on its own, given only its arguments; the program's state is compiled into
760
+ * storage the kept module the task lives in can't import, so the work can't read it.
761
+ */
762
+ private refuseStateInWork(fn: ts.FunctionDeclaration): void {
763
+ const visit = (node: ts.Node): void => {
764
+ if (ts.isIdentifier(node)) {
765
+ const read = valueSymbol(this.context.checker, node);
766
+ const declared =
767
+ read && unaliased(this.context.checker, read).valueDeclaration;
768
+ const file = declared?.getSourceFile().fileName;
769
+ if (
770
+ declared &&
771
+ file &&
772
+ moduleLevel(declared) &&
773
+ this.context.sources.some((source) => source.fileName === file) &&
774
+ !this.context.isKept(file)
775
+ ) {
776
+ throw new SpecializeError(
777
+ node,
778
+ `A task's work runs on its own, given only its arguments, so it can't read ${node.text} from a module of program state: pass what it needs as arguments, and use its result in scan code.`,
779
+ );
780
+ }
781
+ }
782
+ ts.forEachChild(node, visit);
783
+ };
784
+ ts.forEachChild(fn, visit);
785
+ }
786
+
432
787
  private serviceCall(
433
788
  path: string,
434
789
  node: ts.CallExpression,
435
790
  frame: Frame,
436
791
  ): Value {
437
- const client = this.model.roots.find((root) => {
438
- const value = this.model.node(root.value);
792
+ const { model, checker, dialect, imports } = this.context;
793
+ const client = model.roots.find((root) => {
794
+ const value = model.node(root.value);
439
795
  return value?.captured.kind === "service" && value.captured.path === "";
440
796
  });
441
797
  if (!client) {
442
798
  throw new SpecializeError(
443
799
  node,
444
- "Create the service client in a module of its own.",
800
+ "Create the service client in a module-level const, and import it where scan code calls it: the PLC calls the server through that one client, with the types the server's router gives each call.",
445
801
  );
446
802
  }
447
- this.imports.kept.add(client.file, client.name);
448
- const args = node.arguments.map((argument) =>
449
- this.dialect.code(
450
- this.expressions.expression(
451
- argument,
452
- frame,
453
- this.checker.getContextualType(argument),
454
- ),
455
- this.checker.getContextualType(argument),
456
- ),
457
- );
803
+ imports.kept.add(client.file, client.name);
804
+ const args = node.arguments.map((argument) => {
805
+ const contextual = checker.getContextualType(argument);
806
+ return dialect.code(
807
+ this.expressions.expression(argument, frame, contextual),
808
+ contextual,
809
+ );
810
+ });
458
811
  return {
459
812
  kind: "code",
460
813
  text: mapped`${client.name}.${path}(${joined(args, ", ")})`,
461
- declared: this.checker.getTypeAtLocation(node),
814
+ declared: checker.getTypeAtLocation(node),
462
815
  };
463
816
  }
464
817
 
818
+ /** An array method on elements known now, which unrolls into code for each element. */
465
819
  private arrayMethod(
466
- name: string,
820
+ name: ArrayMethod,
467
821
  receiver: Value,
468
822
  items: Value[],
469
823
  node: ts.CallExpression,
470
824
  frame: Frame,
471
825
  ): Value {
472
- const callback = node.arguments[0]
473
- ? this.expressions.expression(node.arguments[0], frame)
474
- : undefined;
475
- const apply = (args: Value[]): Value => {
476
- if (!callback) {
477
- throw new SpecializeError(node, `${name} needs a callback.`);
478
- }
479
- return this.expressions.invoke(callback, args, node, frame);
480
- };
481
826
  switch (name) {
482
827
  case "entries":
483
828
  return {
@@ -487,53 +832,19 @@ export class CallSpecializer {
487
832
  items: [constant(index), item],
488
833
  })),
489
834
  };
490
- case "slice": {
491
- const [start, end] = node.arguments.map((argument) =>
492
- this.expressions.expression(argument, frame),
493
- );
494
- if (
495
- (start && start.kind !== "const") ||
496
- (end && end.kind !== "const")
497
- ) {
498
- return this.expressions.iterators.sliced(
499
- items,
500
- { start, end },
501
- node,
502
- frame,
503
- );
504
- }
505
- return {
506
- kind: "virtual",
507
- items: items.slice(
508
- start?.value as number | undefined,
509
- end?.value as number | undefined,
510
- ),
511
- };
512
- }
513
- case "map":
835
+ case "slice":
836
+ return this.slice(items, node, frame);
837
+ case "map": {
838
+ const apply = this.callback(node, frame);
514
839
  return {
515
840
  kind: "virtual",
516
841
  items: items.map((item, index) =>
517
842
  this.settle(apply([item, constant(index)]), frame),
518
843
  ),
519
844
  };
520
- case "filter": {
521
- const kept: Value[] = [];
522
- items.forEach((item, index) => {
523
- const test = apply([item, constant(index)]);
524
- if (test.kind !== "const") {
525
- throw new SpecializeError(
526
- node,
527
- "filter must decide from what setup built.",
528
- );
529
- }
530
- if (test.value) {
531
- kept.push(item);
532
- }
533
- });
534
- return { kind: "virtual", items: kept };
535
845
  }
536
- case "forEach":
846
+ case "forEach": {
847
+ const apply = this.callback(node, frame);
537
848
  items.forEach((item, index) => {
538
849
  const result = apply([item, constant(index)]);
539
850
  if (result.kind === "code") {
@@ -541,70 +852,42 @@ export class CallSpecializer {
541
852
  }
542
853
  });
543
854
  return constant(undefined);
544
- case "some":
545
- case "every": {
546
- const some = name === "some";
547
- const tests = items.map((item, index) =>
548
- apply([item, constant(index)]),
549
- );
550
- const runtime: (string | Mapped)[] = [];
551
- for (const test of tests) {
552
- if (test.kind === "const") {
553
- if (Boolean(test.value) === some) {
554
- return constant(some);
555
- }
556
- continue;
557
- }
558
- runtime.push(this.dialect.condition(test, node.arguments[0] ?? node));
559
- }
560
- if (!runtime.length) {
561
- return constant(!some);
562
- }
563
- return {
564
- kind: "code",
565
- text: mapped`(${joined(runtime, some ? " || " : " && ")})`,
566
- declared: this.checker.getBooleanType(),
567
- };
568
855
  }
856
+ case "some":
857
+ case "every":
858
+ case "includes":
859
+ return this.expressions.iterators.unrolled(name, items, node, frame);
569
860
  case "reduce":
570
- case "reduceRight": {
571
- const indexed = [...items.entries()];
572
- const order = name === "reduce" ? indexed : indexed.reverse();
573
- let accumulator = node.arguments[1]
574
- ? this.expressions.expression(node.arguments[1], frame)
575
- : order.shift()![1];
576
- for (const [index, item] of order) {
577
- accumulator = this.settle(
578
- apply([accumulator, item, constant(index)]),
579
- frame,
580
- );
581
- }
582
- return accumulator;
583
- }
861
+ case "reduceRight":
862
+ return this.reduce(
863
+ name,
864
+ items,
865
+ node,
866
+ frame,
867
+ this.callback(node, frame),
868
+ );
584
869
  case "find":
585
- // A reference to an object setup built is chosen now; a value can be chosen at run time.
586
- return items.some(
587
- (item) => item.kind === "static" || item.kind === "function",
588
- )
589
- ? this.decidedFind(items, node, apply)
590
- : this.searches.find(items, node, frame, { last: false }, apply);
591
870
  case "findLast":
592
- return this.searches.find(items, node, frame, { last: true }, apply);
871
+ return this.searches.find(
872
+ items,
873
+ node,
874
+ frame,
875
+ { last: name === "findLast" },
876
+ this.callback(node, frame),
877
+ );
593
878
  case "findIndex":
594
879
  case "findLastIndex":
595
880
  return this.searches.findIndex(
596
881
  items,
597
882
  frame,
598
883
  { last: name === "findLastIndex" },
599
- apply,
884
+ this.callback(node, frame),
600
885
  );
601
886
  case "indexOf":
602
887
  case "lastIndexOf":
603
888
  return this.searches.indexOf(items, node, frame, {
604
889
  last: name === "lastIndexOf",
605
890
  });
606
- case "includes":
607
- return this.searches.includes(items, node, frame);
608
891
  case "fill":
609
892
  return this.searches.fill(receiver, items, node, frame);
610
893
  case "at":
@@ -620,50 +903,65 @@ export class CallSpecializer {
620
903
  }),
621
904
  ],
622
905
  };
623
- default:
624
- throw new SpecializeError(node, `${name} is not supported.`);
625
906
  }
626
907
  }
627
908
 
628
- /** A call to a generator, as a for…of runs it: its body, the object it runs on and its arguments. */
629
- generator(
630
- node: ts.Expression,
909
+ /** An array method's callback as the step it runs on elements. */
910
+ private callback(
911
+ node: ts.CallExpression,
631
912
  frame: Frame,
632
- ):
633
- | { declaration: FunctionLike; self?: ModelNode; args: Value[] }
634
- | undefined {
635
- if (!ts.isCallExpression(node)) {
636
- return undefined;
913
+ ): (args: Value[]) => Value {
914
+ const callback = callbackArgument(node, frame, this.expressions);
915
+ return (args) => this.expressions.invoke(callback, args, node, frame);
916
+ }
917
+
918
+ /** `slice(start, end)` with bounds setup fixed picks elements now; one decided at run time is read in place. */
919
+ private slice(
920
+ items: readonly Value[],
921
+ node: ts.CallExpression,
922
+ frame: Frame,
923
+ ): Value {
924
+ const [start, end] = node.arguments.map((argument) =>
925
+ this.expressions.expression(argument, frame),
926
+ );
927
+ const startIndex = sliceBound(start);
928
+ const endIndex = sliceBound(end);
929
+ if (startIndex === null || endIndex === null) {
930
+ return this.expressions.iterators.sliced(
931
+ items,
932
+ { start, end },
933
+ node,
934
+ frame,
935
+ );
637
936
  }
638
- const declaration = this.checker.getResolvedSignature(node)?.declaration;
639
- if (
640
- !declaration ||
641
- !(
642
- ts.isFunctionDeclaration(declaration) ||
643
- ts.isMethodDeclaration(declaration) ||
644
- ts.isFunctionExpression(declaration)
645
- ) ||
646
- !declaration.asteriskToken ||
647
- !declaration.body
648
- ) {
649
- return undefined;
937
+ return { kind: "virtual", items: items.slice(startIndex, endIndex) };
938
+ }
939
+
940
+ /** `reduce(step, initial)` and `reduceRight`: each step's result is the next one's accumulator. */
941
+ private reduce(
942
+ name: "reduce" | "reduceRight",
943
+ items: readonly Value[],
944
+ node: ts.CallExpression,
945
+ frame: Frame,
946
+ apply: (args: Value[]) => Value,
947
+ ): Value {
948
+ const order = ordered(items, { last: name === "reduceRight" });
949
+ const [, initialNode] = node.arguments;
950
+ const [first] = order;
951
+ const initial = initialNode
952
+ ? this.expressions.expression(initialNode, frame)
953
+ : first?.[1];
954
+ if (!initial) {
955
+ throw new SpecializeError(
956
+ node,
957
+ `${name} of an array with no elements needs an initial value.`,
958
+ );
650
959
  }
651
- const callee = node.expression;
652
- const target = ts.isPropertyAccessExpression(callee)
653
- ? this.expressions.member(
654
- this.expressions.expression(callee.expression, frame),
655
- callee.name.text,
656
- callee,
657
- frame,
658
- )
659
- : this.expressions.expression(callee, frame);
660
- const self = target.kind === "function" ? target.self : undefined;
661
- const args = this.expressions.inOrder(
662
- node.arguments,
663
- (argument) => this.expressions.expression(argument, frame),
664
- frame,
960
+ return (initialNode ? order : order.slice(1)).reduce(
961
+ (accumulator, [index, item]) =>
962
+ this.settle(apply([accumulator, item, constant(index)]), frame),
963
+ initial,
665
964
  );
666
- return { declaration, self, args };
667
965
  }
668
966
 
669
967
  /**
@@ -671,13 +969,13 @@ export class CallSpecializer {
671
969
  * exactly, so its proved range carries over; the result is floating, and converts as IEC assignment
672
970
  * does where it is stored as a number.
673
971
  */
674
- private floatMath(
972
+ floatMath(
675
973
  name: string,
676
974
  args: readonly Value[],
677
975
  node: ts.Expression,
678
976
  frame: Frame,
679
977
  ): Value {
680
- const declared = this.checker.getTypeAtLocation(node);
978
+ const declared = this.context.checker.getTypeAtLocation(node);
681
979
  const [first, second] = args;
682
980
  if (!first) {
683
981
  throw new SpecializeError(node, `Math.${name} needs a value.`);
@@ -685,7 +983,7 @@ export class CallSpecializer {
685
983
  const type = floatIec(first) ?? (second && floatIec(second)) ?? "LREAL";
686
984
  const float = (value: Value) => this.asFloat(value, type);
687
985
  const sdk = (fn: string, ...operands: readonly Part[]): Value => {
688
- this.imports.addSdk("@tsplc/compiler/types", fn);
986
+ this.context.imports.addSdk(sdkModules.types, fn);
689
987
  return {
690
988
  kind: "code",
691
989
  text: mapped`${fn}<${type}>(${joined(operands, ", ")})`,
@@ -700,16 +998,17 @@ export class CallSpecializer {
700
998
  if (name === "pow" && second) {
701
999
  return sdk("expt", float(first), float(second));
702
1000
  }
703
- if (["floor", "ceil", "round", "trunc"].includes(name)) {
1001
+ const rounding = roundings.get(name);
1002
+ if (rounding) {
704
1003
  if (!floatIec(first)) {
705
1004
  return first;
706
1005
  }
707
- return this.rounded(name, first, type, frame, declared);
1006
+ return this.rounded(name, rounding, first, type, frame, declared);
708
1007
  }
709
1008
  if (name === "sign") {
710
1009
  const held = this.expressions.held(first, frame);
711
1010
  const zero = floatIec(first) ? "0.0" : "0";
712
- const text = this.dialect.code(held, undefined);
1011
+ const text = this.context.dialect.code(held, undefined);
713
1012
  return {
714
1013
  kind: "code",
715
1014
  text: mapped`(${text} > ${zero} ? 1 : (${text} < ${zero} ? -1 : 0))`,
@@ -722,55 +1021,39 @@ export class CallSpecializer {
722
1021
  );
723
1022
  }
724
1023
 
725
- /** `base ** exponent`, as Math.pow is. */
726
- power(
727
- base: Value,
728
- exponent: Value,
729
- node: ts.BinaryExpression,
730
- frame: Frame,
731
- ): Value {
732
- return this.floatMath("pow", [base, exponent], node, frame);
733
- }
734
-
735
1024
  /** A floating value toward zero, down, up or to the nearest whole value, as floating. */
736
1025
  private rounded(
737
1026
  name: string,
1027
+ rounding: Rounding,
738
1028
  value: Value,
739
1029
  type: string,
740
1030
  frame: Frame,
741
1031
  declared: ts.Type,
742
1032
  ): Value {
743
- this.imports.addSdk("@tsplc/compiler/types", "trunc");
1033
+ this.context.imports.addSdk(sdkModules.types, "trunc");
1034
+ const text = this.context.dialect.code(value, undefined);
744
1035
  // Math.round takes halves up: the nearest whole value is the floor of the value plus a half.
745
- const source =
746
- name === "round"
747
- ? mapped`(${this.dialect.code(value, undefined)} + 0.5)`
748
- : this.dialect.code(value, undefined);
1036
+ const source = name === "round" ? mapped`(${text} + 0.5)` : text;
749
1037
  const held = frame.emitter.temporary();
750
1038
  frame.emitter.line(mapped`const ${held}: ${type} = ${source};`);
751
1039
  const whole = frame.emitter.temporary();
752
1040
  frame.emitter.line(`const ${whole}: ${type} = trunc<${type}>(${held});`);
753
- const text = (() => {
754
- switch (name) {
755
- case "floor":
756
- case "round":
757
- return `(${whole} > ${held} ? ${whole} - 1.0 : ${whole})`;
758
- case "ceil":
759
- return `(${whole} < ${held} ? ${whole} + 1.0 : ${whole})`;
760
- default:
761
- return whole;
762
- }
763
- })();
764
- return { kind: "code", text, declared, iec: type };
1041
+ return {
1042
+ kind: "code",
1043
+ text: rounding(whole, held),
1044
+ declared,
1045
+ iec: type,
1046
+ whole: true,
1047
+ };
765
1048
  }
766
1049
 
767
1050
  /** A value as the floating type: as it is when it already is, else converted exactly. */
768
1051
  private asFloat(value: Value, type: string): Part {
769
1052
  if (floatIec(value) || value.kind === "const") {
770
- return this.dialect.code(value, undefined);
1053
+ return this.context.dialect.code(value, undefined);
771
1054
  }
772
- this.imports.addSdk("@tsplc/compiler/types", "exact");
773
- return mapped`exact<${type}>(${this.dialect.code(value, undefined)})`;
1055
+ this.context.imports.addSdk(sdkModules.types, "exact");
1056
+ return mapped`exact<${type}>(${this.context.dialect.code(value, undefined)})`;
774
1057
  }
775
1058
 
776
1059
  /**
@@ -814,6 +1097,27 @@ export class CallSpecializer {
814
1097
  };
815
1098
  }
816
1099
 
1100
+ /** `Object.values(record)` of a record setup built: its fields' values, in its order. */
1101
+ private objectValues(node: ts.CallExpression, frame: Frame): Value {
1102
+ const [argument] = node.arguments;
1103
+ const object = argument && this.expressions.expression(argument, frame);
1104
+ if (object?.kind !== "static" || object.node.captured.kind !== "object") {
1105
+ throw new SpecializeError(
1106
+ node,
1107
+ "Object.values needs a record setup built.",
1108
+ );
1109
+ }
1110
+ return {
1111
+ kind: "virtual",
1112
+ items: Object.entries(object.node.captured.fields).map(([field, value]) =>
1113
+ this.context.storage.fromCaptured(value, object.node, {
1114
+ kind: "field",
1115
+ name: field,
1116
+ }),
1117
+ ),
1118
+ };
1119
+ }
1120
+
817
1121
  /**
818
1122
  * `structuredClone(value)`: a record or array of its own, as the dialect's `copy` makes one, for
819
1123
  * code that changes it and stores it back.
@@ -824,10 +1128,14 @@ export class CallSpecializer {
824
1128
  throw new SpecializeError(node, "structuredClone needs a value.");
825
1129
  }
826
1130
  const value = this.expressions.expression(argument, frame);
827
- if (value.kind !== "code") {
1131
+ // A primitive is a value already: its clone is itself.
1132
+ if (
1133
+ value.kind !== "code" ||
1134
+ (value.declared && !(value.declared.flags & ts.TypeFlags.Object))
1135
+ ) {
828
1136
  return value;
829
1137
  }
830
- this.imports.addSdk("@tsplc/compiler/types", "copy");
1138
+ this.context.imports.addSdk(sdkModules.types, "copy");
831
1139
  return {
832
1140
  kind: "code",
833
1141
  text: mapped`copy(${value.text})`,
@@ -838,106 +1146,78 @@ export class CallSpecializer {
838
1146
  };
839
1147
  }
840
1148
 
841
- /** Whether the expression is `array.filter(test)`, whose length counts the elements that pass. */
842
- isFilter(node: ts.Expression): node is ts.CallExpression {
843
- return (
844
- ts.isCallExpression(node) &&
845
- ts.isPropertyAccessExpression(node.expression) &&
846
- node.expression.name.text === "filter" &&
847
- node.arguments.length === 1
848
- );
1149
+ /** Keeps a runtime result in a local, so later code reads it rather than repeating it. */
1150
+ private settle(value: Value, frame: Frame): Value {
1151
+ return value.kind === "code"
1152
+ ? this.expressions.hold(value, frame, settledResult)
1153
+ : value;
849
1154
  }
1155
+ }
850
1156
 
851
- /**
852
- * `array.filter(test).length`: how many elements pass. A filter decided at run time has no array
853
- * to build, since its length isn't fixed, but its count is a number.
854
- */
855
- count(node: ts.CallExpression, frame: Frame): Value {
856
- const callee = node.expression;
857
- if (!ts.isPropertyAccessExpression(callee)) {
858
- throw new SpecializeError(node, "Not a filter.");
859
- }
860
- const items = this.expressions.items(
861
- this.expressions.expression(callee.expression, frame),
862
- );
863
- const [testNode] = node.arguments;
864
- if (!items || !testNode) {
865
- throw new SpecializeError(
866
- node,
867
- "filter needs an array setup built and a test.",
868
- );
869
- }
870
- const test = this.expressions.expression(testNode, frame);
871
- const results = items.map((item, index) =>
872
- this.expressions.invoke(test, [item, constant(index)], node, frame),
873
- );
874
- if (results.every((result) => result.kind === "const")) {
875
- return constant(
876
- results.filter((result) => result.kind === "const" && result.value)
877
- .length,
878
- );
879
- }
880
- const total = frame.emitter.temporary();
881
- frame.emitter.line(`let ${total}: number = 0;`);
882
- for (const result of results) {
883
- if (result.kind === "const") {
884
- if (result.value) {
885
- frame.emitter.line(`${total} = ${total} + 1;`);
886
- }
887
- continue;
888
- }
889
- frame.emitter.line(
890
- mapped`if (${this.dialect.condition(result, testNode)}) { ${total} = ${total} + 1; }`,
891
- );
892
- }
893
- return {
894
- kind: "code",
895
- text: total,
896
- declared: this.checker.getNumberType(),
897
- place: true,
898
- };
1157
+ /** Whether a promise link is awaited, directly or as the promise of an outer link that is. */
1158
+ const awaitedLink = (node: ts.CallExpression): boolean => {
1159
+ const parent = node.parent;
1160
+ if (ts.isAwaitExpression(parent)) {
1161
+ return true;
1162
+ }
1163
+ if (ts.isParenthesizedExpression(parent)) {
1164
+ return ts.isAwaitExpression(parent.parent);
899
1165
  }
1166
+ return (
1167
+ ts.isPropertyAccessExpression(parent) &&
1168
+ isPromiseLink(parent.parent) &&
1169
+ awaitedLink(parent.parent)
1170
+ );
1171
+ };
900
1172
 
901
- /** find over objects setup built, whose tests are known now: the object that passes, or undefined. */
902
- private decidedFind(
903
- items: readonly Value[],
904
- node: ts.CallExpression,
905
- apply: (args: Value[]) => Value,
906
- ): Value {
907
- for (const [index, item] of items.entries()) {
908
- const test = apply([item, constant(index)]);
909
- if (test.kind !== "const") {
910
- throw new SpecializeError(
911
- node,
912
- "find picks one of the objects setup built, which scan code can't hold; use findIndex and index the array.",
913
- );
914
- }
915
- if (test.value) {
916
- return item;
917
- }
918
- }
919
- return constant(undefined);
1173
+ /** Whether a declaration is a module's own: a top-level variable, function or class. */
1174
+ const moduleLevel = (declaration: ts.Declaration): boolean => {
1175
+ if (ts.isVariableDeclaration(declaration)) {
1176
+ return ts.isSourceFile(declaration.parent.parent.parent);
920
1177
  }
1178
+ return (
1179
+ (ts.isFunctionDeclaration(declaration) ||
1180
+ ts.isClassDeclaration(declaration)) &&
1181
+ ts.isSourceFile(declaration.parent)
1182
+ );
1183
+ };
921
1184
 
922
- /** Keeps a runtime result in a local, so later code reads it rather than repeating it. */
923
- private settle(value: Value, frame: Frame): Value {
924
- if (value.kind !== "code" || repeatable(value.text)) {
925
- return value;
1185
+ /**
1186
+ * A TIME or calendar constructor's argument, which the PLC stores as a constant: a duration known
1187
+ * when the program compiles, or a calendar text in its format.
1188
+ */
1189
+ const refuseTimeArgument = (
1190
+ name: string,
1191
+ value: Value,
1192
+ argument: ts.Expression,
1193
+ ): void => {
1194
+ const calendar = calendarFormats.get(name);
1195
+ if (!calendar) {
1196
+ if (durationNames.has(name) && value.kind !== "const") {
1197
+ throw new SpecializeError(
1198
+ argument,
1199
+ `${name}() makes a TIME constant, so its value must be known when the program compiles: a literal, a constant or a field only setup writes. To wait a time scan code computes, sleep in steps until now() has passed it.`,
1200
+ );
926
1201
  }
927
- const local = frame.emitter.temporary();
928
- frame.emitter.line(
929
- mapped`const ${local}: ${value.declared ? this.expressions.localType(value.declared) : "boolean"} = ${value.text};`,
1202
+ return;
1203
+ }
1204
+ if (
1205
+ value.kind !== "const" ||
1206
+ typeof value.value !== "string" ||
1207
+ !calendarLiteral(calendar.domain, value.value)
1208
+ ) {
1209
+ throw new SpecializeError(
1210
+ argument,
1211
+ `${name}() takes a ${calendar.type} written as "${calendar.format}", known when the program compiles.`,
930
1212
  );
931
- return { kind: "code", text: local, declared: value.declared, place: true };
932
1213
  }
933
- }
1214
+ };
934
1215
 
935
1216
  /** Array methods scan code calls on arrays setup built, which unroll. */
936
- const arrayMethods = new Set([
1217
+ const arrayMethods = [
937
1218
  "entries",
938
1219
  "slice",
939
1220
  "map",
940
- "filter",
941
1221
  "forEach",
942
1222
  "some",
943
1223
  "every",
@@ -953,24 +1233,110 @@ const arrayMethods = new Set([
953
1233
  "fill",
954
1234
  "at",
955
1235
  "concat",
1236
+ ] as const;
1237
+
1238
+ type ArrayMethod = (typeof arrayMethods)[number];
1239
+
1240
+ const isArrayMethod = (name: string): name is ArrayMethod =>
1241
+ arrayMethods.some((method) => method === name);
1242
+
1243
+ /** A `map` or `reduce` step's result, held as its local type, or as a boolean when nothing declares one. */
1244
+ const settledResult: Holding = {
1245
+ width: false,
1246
+ widen: true,
1247
+ untyped: "boolean",
1248
+ repeatable: false,
1249
+ };
1250
+
1251
+ /** An operand Math.min or Math.max reads twice, held at its own width. */
1252
+ const comparedOperand: Holding = {
1253
+ width: true,
1254
+ widen: true,
1255
+ untyped: "number",
1256
+ repeatable: false,
1257
+ };
1258
+
1259
+ /** The Math function each of the SDK's elementary functions is called as in scan code. */
1260
+ const mathNames: Readonly<
1261
+ Record<ElementaryFunction, Extract<keyof Math, string>>
1262
+ > = {
1263
+ sqrt: "sqrt",
1264
+ ln: "log",
1265
+ log10: "log10",
1266
+ exp: "exp",
1267
+ sin: "sin",
1268
+ cos: "cos",
1269
+ tan: "tan",
1270
+ asin: "asin",
1271
+ acos: "acos",
1272
+ atan: "atan",
1273
+ };
1274
+
1275
+ const elementaryNames = new Map<string, ElementaryFunction>(
1276
+ elementaryFunctions.map((name) => [mathNames[name], name]),
1277
+ );
1278
+
1279
+ /** The Math functions scan code calls, as a constant call folds: the elementary ones as iec computes them. */
1280
+ const mathFolds = new Map<string, (...values: number[]) => number>([
1281
+ ["abs", Math.abs],
1282
+ ["min", Math.min],
1283
+ ["max", Math.max],
1284
+ ["floor", Math.floor],
1285
+ ["ceil", Math.ceil],
1286
+ ["round", Math.round],
1287
+ ["trunc", Math.trunc],
1288
+ ["sign", Math.sign],
1289
+ ["pow", Math.pow],
1290
+ ["hypot", Math.hypot],
1291
+ ["atan2", Math.atan2],
1292
+ ["log2", Math.log2],
1293
+ ["log1p", Math.log1p],
1294
+ ["expm1", Math.expm1],
1295
+ ["cbrt", Math.cbrt],
1296
+ ["sinh", Math.sinh],
1297
+ ["cosh", Math.cosh],
1298
+ ["tanh", Math.tanh],
1299
+ ["asinh", Math.asinh],
1300
+ ["acosh", Math.acosh],
1301
+ ["atanh", Math.atanh],
1302
+ ["clz32", Math.clz32],
1303
+ ["imul", Math.imul],
1304
+ ["fround", Math.fround],
1305
+ ...elementaryFunctions.map((name): [string, (value: number) => number] => [
1306
+ mathNames[name],
1307
+ elementaryValue[name],
1308
+ ]),
956
1309
  ]);
957
1310
 
958
- /** The SDK function each of JavaScript's Math functions is, among those whose result can be proved finite. */
959
- const elementaryNames = new Map<string, string>([
960
- ["sqrt", "sqrt"],
961
- ["log", "ln"],
962
- ["log10", "log10"],
963
- ["exp", "exp"],
964
- ["sin", "sin"],
965
- ["cos", "cos"],
966
- ["tan", "tan"],
967
- ["asin", "asin"],
968
- ["acos", "acos"],
969
- ["atan", "atan"],
1311
+ /** A rounding's result from a value's whole part toward zero, `whole`, and the value, `held`. */
1312
+ type Rounding = (whole: string, held: string) => string;
1313
+
1314
+ const downward: Rounding = (whole, held) =>
1315
+ `(${whole} > ${held} ? ${whole} - 1.0 : ${whole})`;
1316
+
1317
+ /** Math's roundings of a floating value; round is the floor of the value plus a half. */
1318
+ const roundings = new Map<string, Rounding>([
1319
+ ["floor", downward],
1320
+ ["round", downward],
1321
+ ["ceil", (whole, held) => `(${whole} < ${held} ? ${whole} + 1.0 : ${whole})`],
1322
+ ["trunc", (whole) => whole],
970
1323
  ]);
971
1324
 
972
1325
  /** The floating IEC type a value has, if it is floating. */
973
- const floatIec = (value: Value): string | undefined =>
974
- value.kind === "code" && (value.iec === "REAL" || value.iec === "LREAL")
1326
+ export const floatIec = (value: Value): string | undefined =>
1327
+ value.kind === "code" &&
1328
+ value.iec !== undefined &&
1329
+ elementaryType(value.iec)?.family === "real"
975
1330
  ? value.iec
976
1331
  : undefined;
1332
+
1333
+ /** A slice bound setup fixed, undefined when left out, or null when it is decided at run time. */
1334
+ const sliceBound = (bound: Value | undefined): number | undefined | null => {
1335
+ if (!bound) {
1336
+ return undefined;
1337
+ }
1338
+ if (bound.kind !== "const") {
1339
+ return null;
1340
+ }
1341
+ return typeof bound.value === "number" ? bound.value : undefined;
1342
+ };