@tsplc/compiler 0.2.17 → 0.2.18

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 (157) hide show
  1. package/README.md +2 -2
  2. package/dist/cli.js +920 -943
  3. package/dist/cli.js.map +13 -10
  4. package/dist/codesys.js +3893 -3352
  5. package/dist/codesys.js.map +29 -20
  6. package/dist/elaborate-capture.js +33 -17
  7. package/dist/elaborate-capture.js.map +3 -3
  8. package/dist/index.js +8787 -6855
  9. package/dist/index.js.map +40 -20
  10. package/dist/ir.js +1575 -1072
  11. package/dist/ir.js.map +21 -17
  12. package/dist/math.js.map +2 -2
  13. package/dist/project.js +154 -60
  14. package/dist/project.js.map +5 -5
  15. package/dist/telemetry.js +27 -9
  16. package/dist/telemetry.js.map +5 -5
  17. package/package.json +112 -112
  18. package/src/codesys/config.ts +50 -0
  19. package/src/codesys/debug.ts +670 -0
  20. package/src/codesys/emit.ts +142 -0
  21. package/src/codesys/engineering.ts +109 -0
  22. package/src/codesys/expressions.ts +92 -0
  23. package/src/codesys/global-lists.ts +250 -0
  24. package/src/codesys/global-names.ts +68 -0
  25. package/src/codesys/http.ts +890 -0
  26. package/src/codesys/index.ts +30 -0
  27. package/src/codesys/instrumentation.ts +430 -0
  28. package/src/codesys/io-paths.ts +140 -0
  29. package/src/codesys/manifest.ts +643 -0
  30. package/src/codesys/names.ts +81 -0
  31. package/src/codesys/numeric.ts +409 -0
  32. package/src/codesys/operands.ts +62 -0
  33. package/src/codesys/plan.ts +605 -0
  34. package/src/codesys/programs.ts +53 -0
  35. package/src/codesys/publication.ts +171 -0
  36. package/src/codesys/routines.ts +603 -0
  37. package/src/codesys/sources.ts +71 -0
  38. package/src/codesys/st-files.ts +115 -0
  39. package/src/codesys/storage.ts +97 -0
  40. package/src/codesys/symbols.ts +220 -0
  41. package/src/codesys/task-access.ts +320 -0
  42. package/src/codesys/telemetry.ts +732 -0
  43. package/src/codesys/types.ts +250 -0
  44. package/src/codesys/vendor.ts +150 -0
  45. package/src/frontend/analyzer.ts +794 -0
  46. package/src/frontend/async.ts +317 -1137
  47. package/src/frontend/blocks.ts +537 -403
  48. package/src/frontend/configuration.ts +176 -144
  49. package/src/frontend/const-functions.ts +183 -148
  50. package/src/frontend/cooperative.ts +73 -43
  51. package/src/frontend/coroutines.ts +1032 -0
  52. package/src/frontend/elaborate/calls.ts +535 -0
  53. package/src/frontend/elaborate/capture.ts +157 -101
  54. package/src/frontend/elaborate/dialect.ts +257 -0
  55. package/src/frontend/elaborate/expressions.ts +992 -0
  56. package/src/frontend/elaborate/frame.ts +53 -0
  57. package/src/frontend/elaborate/graph.ts +116 -71
  58. package/src/frontend/elaborate/imports.ts +70 -0
  59. package/src/frontend/elaborate/index.ts +435 -331
  60. package/src/frontend/elaborate/initializers.ts +198 -0
  61. package/src/frontend/elaborate/layouts.ts +591 -384
  62. package/src/frontend/elaborate/model.ts +264 -169
  63. package/src/frontend/elaborate/specialize.ts +343 -2586
  64. package/src/frontend/elaborate/statements.ts +606 -0
  65. package/src/frontend/elaborate/storage.ts +546 -0
  66. package/src/frontend/elaborate/values.ts +58 -0
  67. package/src/frontend/elaborate/writes.ts +100 -0
  68. package/src/frontend/exposure.ts +172 -140
  69. package/src/frontend/expressions.ts +1383 -0
  70. package/src/frontend/intrinsics.ts +337 -0
  71. package/src/frontend/module-graph.ts +89 -59
  72. package/src/frontend/positions.ts +271 -200
  73. package/src/frontend/promise-chains.ts +897 -0
  74. package/src/frontend/promises.ts +390 -747
  75. package/src/frontend/routines.ts +181 -0
  76. package/src/frontend/sdk.ts +82 -0
  77. package/src/frontend/services.ts +506 -372
  78. package/src/frontend/statements.ts +855 -0
  79. package/src/frontend/tasks.ts +471 -0
  80. package/src/frontend/telemetry.ts +174 -0
  81. package/src/frontend/types.ts +845 -551
  82. package/src/frontend/typescript.ts +323 -2543
  83. package/src/index.ts +5 -5
  84. package/src/ir/aggregates.ts +275 -0
  85. package/src/ir/allocation.ts +84 -0
  86. package/src/ir/core-model.ts +146 -0
  87. package/src/ir/declarations.ts +295 -0
  88. package/src/ir/diagnostics.ts +61 -0
  89. package/src/ir/domains.ts +152 -0
  90. package/src/ir/fold.ts +342 -0
  91. package/src/ir/index.ts +90 -0
  92. package/{ir/errors.ts → src/ir/job-errors.ts} +12 -10
  93. package/src/ir/layouts.ts +181 -0
  94. package/src/ir/link.ts +354 -0
  95. package/src/ir/model.ts +386 -0
  96. package/{ir → src/ir}/normalization-error.ts +4 -4
  97. package/src/ir/normalize.ts +70 -0
  98. package/src/ir/numeric.ts +171 -0
  99. package/src/ir/ranges.ts +256 -0
  100. package/src/ir/routine.ts +1163 -0
  101. package/src/ir/scalars.ts +321 -0
  102. package/src/ir/types.ts +127 -0
  103. package/src/project/artifacts.ts +342 -0
  104. package/src/project/cli.ts +177 -0
  105. package/src/project/debugger.ts +82 -0
  106. package/src/project/index.ts +6 -0
  107. package/src/project/plant.ts +467 -0
  108. package/src/project/project-commands.ts +372 -0
  109. package/src/project/project.ts +457 -0
  110. package/src/project/release.ts +153 -0
  111. package/src/project/server.ts +150 -0
  112. package/src/project/terminal.ts +32 -0
  113. package/stdlib/math.ts +14 -10
  114. package/stdlib/telemetry.ts +71 -47
  115. package/types/async.d.ts +46 -40
  116. package/types/data-types.d.ts +26 -26
  117. package/types/globals.d.ts +41 -38
  118. package/types/index.d.ts +96 -51
  119. package/types/plc.d.ts +3 -4
  120. package/types/telemetry.d.ts +14 -14
  121. package/backends/codesys/config.ts +0 -54
  122. package/backends/codesys/debug.ts +0 -509
  123. package/backends/codesys/emit.ts +0 -1738
  124. package/backends/codesys/engineering.ts +0 -88
  125. package/backends/codesys/global-names.ts +0 -49
  126. package/backends/codesys/http.ts +0 -675
  127. package/backends/codesys/index.ts +0 -13
  128. package/backends/codesys/io-paths.ts +0 -105
  129. package/backends/codesys/manifest.ts +0 -312
  130. package/backends/codesys/names.ts +0 -76
  131. package/backends/codesys/numeric.ts +0 -356
  132. package/backends/codesys/plan.ts +0 -457
  133. package/backends/codesys/publication.ts +0 -59
  134. package/backends/codesys/storage.ts +0 -70
  135. package/backends/codesys/task-access.ts +0 -293
  136. package/backends/codesys/telemetry.ts +0 -593
  137. package/backends/codesys/types.ts +0 -179
  138. package/backends/codesys/vendor.ts +0 -108
  139. package/ir/aggregates.ts +0 -333
  140. package/ir/allocation.ts +0 -74
  141. package/ir/core-model.ts +0 -129
  142. package/ir/core.ts +0 -64
  143. package/ir/declarations.ts +0 -208
  144. package/ir/diagnostics.ts +0 -43
  145. package/ir/domains.ts +0 -96
  146. package/ir/index.ts +0 -8
  147. package/ir/link.ts +0 -185
  148. package/ir/model.ts +0 -346
  149. package/ir/routine.ts +0 -859
  150. package/ir/scalars.ts +0 -675
  151. package/ir/types.ts +0 -76
  152. package/project/artifacts.ts +0 -277
  153. package/project/cli.ts +0 -395
  154. package/project/index.ts +0 -1
  155. package/project/plant.ts +0 -509
  156. package/project/project.ts +0 -358
  157. package/project/server.ts +0 -113
@@ -1,1154 +1,334 @@
1
1
  import { runtimeSources } from "./module-graph.ts";
2
2
  import ts from "typescript";
3
- import { dirname, resolve, relative } from "node:path";
4
- import { cooperativeSite, taskSite } from "./cooperative.ts";
5
- import { staticString } from "./configuration.ts";
6
- import { error, type Diagnostic, type FunctionBlock, type PlcProgram } from "@tsplc/compiler/ir";
3
+ import { resolve } from "node:path";
4
+ import { namesSdk, symbolAt } from "./sdk.ts";
5
+ import { lowerCoroutine } from "./coroutines.ts";
6
+ import { lowerTaskDefinitions } from "./tasks.ts";
7
+ import { SemanticError, hasModifier } from "./types.ts";
7
8
  import {
8
- copied,
9
- edited,
10
- from,
11
- joined,
12
- mapped,
13
- slice,
14
- type Edit,
15
- type Mapped,
16
- type Part,
17
- type Positions,
9
+ error,
10
+ type Diagnostic,
11
+ type FunctionBlock,
12
+ type PlcProgram,
13
+ } from "@tsplc/compiler/ir";
14
+ import {
15
+ edited,
16
+ from,
17
+ joined,
18
+ mapped,
19
+ slice,
20
+ type Edit,
21
+ type Mapped,
22
+ type Positions,
18
23
  } from "./positions.ts";
19
24
 
20
- type Job = NonNullable<FunctionBlock["job"]>;
25
+ export type Job = NonNullable<FunctionBlock["job"]>;
26
+ /** A named async function or method. */
27
+ export type Routine = (ts.FunctionDeclaration | ts.MethodDeclaration) & {
28
+ readonly name: ts.PropertyName;
29
+ };
21
30
 
22
31
  export interface AsyncLowering {
23
- sources: Map<string, Mapped>;
24
- blocks: Map<string, NonNullable<FunctionBlock["runtime"]>>;
25
- /** The async function each generated block runs, by `<file>:<block>`. */
26
- jobs: Map<string, Job>;
27
- programs: Record<string, { module: string; export: string }>;
28
- schedules: Map<string, NonNullable<PlcProgram["background"]>>;
29
- diagnostics: Diagnostic[];
30
- continuations: Map<string, NonNullable<PlcProgram["continuation"]>>;
32
+ sources: Map<string, Mapped>;
33
+ blocks: Map<string, NonNullable<FunctionBlock["runtime"]>>;
34
+ /** The async function each generated block runs, by `<file>:<block>`. */
35
+ jobs: Map<string, Job>;
36
+ programs: Record<string, { module: string; export: string }>;
37
+ schedules: Map<string, NonNullable<PlcProgram["background"]>>;
38
+ diagnostics: Diagnostic[];
39
+ continuations: Map<string, NonNullable<PlcProgram["continuation"]>>;
40
+ }
41
+
42
+ /** The names of the members an async method's coroutine adds to its block. */
43
+ export interface MethodMembers {
44
+ start: string;
45
+ reset: string;
46
+ snapshot: string;
47
+ advance: string;
31
48
  }
32
49
 
33
- /** Statements that end in a semicolon. */
34
- const terminated = (node: ts.Node) =>
35
- ts.isExpressionStatement(node) ||
36
- ts.isVariableStatement(node) ||
37
- ts.isReturnStatement(node) ||
38
- ts.isThrowStatement(node) ||
39
- ts.isBreakOrContinueStatement(node);
50
+ /** What every part of async lowering shares while it rewrites the program. */
51
+ export interface AsyncContext {
52
+ checker: ts.TypeChecker;
53
+ positions: Positions;
54
+ result: AsyncLowering;
55
+ /** Async routines by symbol. */
56
+ functions: ReadonlyMap<ts.Symbol, Routine>;
57
+ /** Async methods by symbol, with the members their coroutine adds. */
58
+ methods: ReadonlyMap<ts.Symbol, MethodMembers>;
59
+ /** Polls and background jobs that block instances run, by block symbol. */
60
+ ownedContinuations: Map<ts.Symbol, string[]>;
61
+ ownedJobs: Map<
62
+ ts.Symbol,
63
+ { method: string; schedule: NonNullable<PlcProgram["background"]> }[]
64
+ >;
65
+ symbol: (node: ts.Node) => ts.Symbol | undefined;
66
+ /** Whether a node names the SDK declaration `name`. */
67
+ namesSdk: (node: ts.Node, name: string) => boolean;
68
+ fail: (node: ts.Node, message: string) => never;
69
+ /** The next number for a generated name. */
70
+ sequence: () => number;
71
+ }
72
+
73
+ /** One source file being rewritten: edits to its text and declarations added around it. */
74
+ export interface SourceRewrite {
75
+ source: ts.SourceFile;
76
+ replacements: Edit[];
77
+ extra: Mapped[];
78
+ }
40
79
 
41
- /** The call an await waits on. */
42
- const awaitedCall = (node: ts.Node) => (ts.isAwaitExpression(node) ? node.expression : node);
80
+ const isAsyncRoutine = (node: ts.Node): node is Routine =>
81
+ (ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node)) &&
82
+ node.name !== undefined &&
83
+ hasModifier(node, ts.SyntaxKind.AsyncKeyword);
43
84
 
44
- const copyValue = (value: Part, aggregate: boolean) => (aggregate ? mapped`copy(${value})` : value);
85
+ const asyncDiagnostic = (
86
+ positions: Positions,
87
+ node: ts.Node,
88
+ message: string,
89
+ ): Diagnostic => error("PLC1010", message, positions.node(node));
45
90
 
46
91
  /** Lower suspension into ordinary typed blocks before the PLC semantic pass. */
47
92
  export const lowerAsync = (
48
- program: ts.Program,
49
- sdk: string,
50
- positions: Positions,
93
+ program: ts.Program,
94
+ sdk: string,
95
+ positions: Positions,
51
96
  ): AsyncLowering => {
52
- const result: AsyncLowering = {
53
- sources: new Map(),
54
- blocks: new Map(),
55
- jobs: new Map(),
56
- programs: {},
57
- schedules: new Map(),
58
- diagnostics: [],
59
- continuations: new Map(),
60
- };
61
- const checker = program.getTypeChecker();
62
- const symbol = (node: ts.Node): ts.Symbol | undefined => {
63
- let s = checker.getSymbolAtLocation(node);
64
- while (s && s.flags & ts.SymbolFlags.Alias) s = checker.getAliasedSymbol(s);
65
- return s;
66
- };
67
- const official = (node: ts.Node, name: string) => {
68
- const s = symbol(node);
69
- return (
70
- s?.name === name &&
71
- s.declarations?.some((d) => d.getSourceFile().fileName.startsWith(dirname(sdk) + "/"))
72
- );
73
- };
74
- const diagnosticFor = (node: ts.Node, message: string): Diagnostic =>
75
- error("PLC1010", message, positions.node(node));
76
- const fail: (node: ts.Node, message: string) => never = (node, message) => {
77
- throw { asyncDiagnostic: diagnosticFor(node, message) };
78
- };
79
- type Routine = ts.FunctionDeclaration | ts.MethodDeclaration;
80
- const functions = new Map<ts.Symbol, Routine>();
81
- const methods = new Map<
82
- ts.Symbol,
83
- { start: string; reset: string; snapshot: string; advance: string }
84
- >();
85
- for (const source of runtimeSources(program)) {
86
- if (source.isDeclarationFile) continue;
87
- for (const statement of source.statements) {
88
- const routines = ts.isClassDeclaration(statement)
89
- ? statement.members.filter(ts.isMethodDeclaration)
90
- : [statement];
91
- for (const fn of routines) {
92
- if (
93
- (!ts.isFunctionDeclaration(fn) && !ts.isMethodDeclaration(fn)) ||
94
- !fn.name ||
95
- !fn.modifiers?.some((m) => m.kind === ts.SyntaxKind.AsyncKeyword)
96
- )
97
- continue;
98
- functions.set(symbol(fn.name)!, fn);
99
- if (ts.isMethodDeclaration(fn)) {
100
- const prefix = `tsplcAsync${fn.name.getText(source)}${fn.getStart(source)}`;
101
- methods.set(symbol(fn.name)!, {
102
- start: prefix + "Start",
103
- reset: prefix + "Reset",
104
- snapshot: prefix + "Snapshot",
105
- advance: prefix + "Advance",
106
- });
107
- }
108
- }
109
- }
110
- }
111
- if (!functions.size) return result;
112
- const aliasPrefix = (fn: Routine) =>
113
- `TsplcAsync${fn.name!.getText(fn.getSourceFile())}${fn.getStart(fn.getSourceFile())}`;
114
- let sequence = 0;
115
- const ownedContinuations = new Map<ts.Symbol, string[]>();
116
- const ownedJobs = new Map<
117
- ts.Symbol,
118
- { method: string; schedule: NonNullable<PlcProgram["background"]> }[]
119
- >();
120
- for (const source of runtimeSources(program)) {
121
- if (source.isDeclarationFile) continue;
122
- try {
123
- const replacements: Edit[] = [],
124
- extra: Mapped[] = [];
125
- const text = (node: ts.Node) => node.getText(source);
126
- for (const fn of functions.values()) {
127
- if (fn.getSourceFile() !== source) continue;
128
- const method = methods.get(symbol(fn.name!)!);
129
- if (!fn.name || !functions.has(symbol(fn.name)!)) continue;
130
- if (
131
- !fn.body ||
132
- fn.typeParameters?.length ||
133
- !fn.type ||
134
- !ts.isTypeReferenceNode(fn.type) ||
135
- fn.type.typeName.getText(source) !== "Promise" ||
136
- fn.type.typeArguments?.length !== 1
137
- )
138
- fail(
139
- fn,
140
- "Async functions require concrete parameters and an explicit Promise<T> result.",
141
- );
142
- const returnsVoid = fn.type.typeArguments[0]!.kind === ts.SyntaxKind.VoidKeyword;
143
- const returnType = returnsVoid ? "BOOL" : text(fn.type.typeArguments[0]!);
144
- const resultAggregate = Boolean(
145
- checker.getTypeFromTypeNode(fn.type.typeArguments[0]!).flags & ts.TypeFlags.Object,
146
- );
147
- const fields = new Map<ts.Symbol, { name: string; type: string; aggregate: boolean }>();
148
- const parameters = fn.parameters.map((p, index) => {
149
- if (
150
- !ts.isIdentifier(p.name) ||
151
- !p.type ||
152
- p.initializer ||
153
- p.questionToken ||
154
- p.dotDotDotToken
155
- )
156
- fail(p, "Async parameters require explicit concrete value types.");
157
- if (/\bInOut\b/.test(text(p.type)))
158
- fail(p, "InOut cannot cross an async suspension; pass a value snapshot.");
159
- fields.set(symbol(p.name)!, {
160
- name: `argument${index}`,
161
- type: text(p.type),
162
- aggregate: Boolean(checker.getTypeFromTypeNode(p.type).flags & ts.TypeFlags.Object),
163
- });
164
- return {
165
- name: p.name.text,
166
- type: text(p.type),
167
- aggregate: Boolean(checker.getTypeFromTypeNode(p.type).flags & ts.TypeFlags.Object),
168
- field: `argument${index}`,
169
- };
170
- });
171
- const containsAwait = (node: ts.Node): boolean =>
172
- ts.isAwaitExpression(node) || node.getChildren(source).some(containsAwait);
173
- const collect = (node: ts.Node) => {
174
- if (ts.isForStatement(node)) {
175
- if (containsAwait(node))
176
- fail(node, "Await inside loops is not supported yet; use bounded async calls.");
177
- return;
178
- }
179
- if (ts.isFunctionLike(node) && node !== fn)
180
- fail(node, "Closures and nested functions are not supported in async PLC routines.");
181
- if (ts.isCatchClause(node)) {
182
- const declaration = node.variableDeclaration;
183
- if (declaration) {
184
- if (!ts.isIdentifier(declaration.name))
185
- fail(declaration, "Catch requires a named error code or no binding.");
186
- fields.set(symbol(declaration.name)!, {
187
- name: `caught${fields.size}`,
188
- type: "UDINT",
189
- aggregate: false,
190
- });
191
- }
192
- collect(node.block);
193
- return;
194
- }
195
- if (ts.isVariableDeclaration(node)) {
196
- if (!ts.isIdentifier(node.name) || !node.initializer)
197
- fail(node, "Async locals need names and initializers.");
198
- let type = node.type ? text(node.type) : undefined;
199
- if (!type) {
200
- if (
201
- node.initializer.kind === ts.SyntaxKind.TrueKeyword ||
202
- node.initializer.kind === ts.SyntaxKind.FalseKeyword
203
- )
204
- type = "BOOL";
205
- else if (
206
- ts.isAwaitExpression(node.initializer) &&
207
- ts.isCallExpression(node.initializer.expression)
208
- ) {
209
- const call = node.initializer.expression;
210
- const target = ts.isPropertyAccessExpression(call.expression)
211
- ? call.expression.name
212
- : call.expression;
213
- const called = functions.get(symbol(target)!);
214
- if (called?.type && ts.isTypeReferenceNode(called.type)) {
215
- type = called.type.typeArguments![0]!.getText(called.getSourceFile());
216
- if (called.getSourceFile() !== source) {
217
- type = `${aliasPrefix(called)}Result`;
218
- const path = relative(
219
- dirname(source.fileName),
220
- called.getSourceFile().fileName,
221
- ).replaceAll("\\", "/");
222
- const statement = `import type {${type}} from ${JSON.stringify(path.startsWith(".") ? path : `./${path}`)};`;
223
- if (!extra.some((item) => item.text === statement))
224
- extra.push(from(node, statement));
225
- }
226
- }
227
- }
228
- if (!type) fail(node, "Annotate async locals with their concrete PLC type.");
229
- }
230
- fields.set(symbol(node.name)!, {
231
- name: `local${fields.size}`,
232
- type,
233
- aggregate: Boolean(checker.getTypeAtLocation(node).flags & ts.TypeFlags.Object),
234
- });
235
- }
236
- ts.forEachChild(node, collect);
237
- };
238
- collect(fn.body);
239
- // The user's text with locals moved onto the block, so positions in it map exactly.
240
- const rewrite = (node: ts.Node): Mapped => {
241
- const edits: Edit[] = [];
242
- const visit = (n: ts.Node): void => {
243
- const replacement = (() => {
244
- if (
245
- method &&
246
- ts.isPropertyAccessExpression(n) &&
247
- n.expression.kind === ts.SyntaxKind.ThisKeyword
248
- )
249
- return `this[${JSON.stringify(n.name.text)}]`;
250
- if (
251
- ts.isIdentifier(n) &&
252
- !(ts.isPropertyAccessExpression(n.parent) && n.parent.name === n) &&
253
- !(ts.isPropertyAssignment(n.parent) && n.parent.name === n)
254
- ) {
255
- const field = fields.get(symbol(n)!);
256
- if (field) return `this.${field.name}`;
257
- }
258
- if (ts.isShorthandPropertyAssignment(n)) {
259
- const value = checker.getShorthandAssignmentValueSymbol(n),
260
- field = value && fields.get(value);
261
- if (field) return `${n.name.text}: this.${field.name}`;
262
- }
263
- return undefined;
264
- })();
265
- if (replacement === undefined) ts.forEachChild(n, visit);
266
- else edits.push({ start: n.getStart(source), end: n.end, text: replacement });
267
- };
268
- visit(node);
269
- const text = copied(node);
270
- const start = node.getStart(source);
271
- const result = edited(
272
- text,
273
- edits.map((edit) => ({ ...edit, start: edit.start - start, end: edit.end - start })),
274
- );
275
- // A statement written without its semicolon is followed by more code here.
276
- return terminated(node) && !result.text.endsWith(";") ? mapped`${result};` : result;
277
- };
278
- const nodes = new Map<number, Mapped>();
279
- const yielding = new Set<number>();
280
- const steps: Job["steps"][number][] = [];
281
- let nextId = 1;
282
- /** A step of the job: `body` runs while it is current; `origin` is the source it runs. */
283
- const state = (
284
- body: Part,
285
- origin: ts.Node,
286
- kind: Job["steps"][number]["kind"],
287
- yields = false,
288
- ) => {
289
- const id = nextId++;
290
- nodes.set(id, from(origin, body));
291
- steps.push({
292
- step: id,
293
- kind,
294
- span: positions.node(origin),
295
- text: positions.excerpt(kind === "await" ? awaitedCall(origin) : origin),
296
- });
297
- if (yields) yielding.add(id);
298
- return id;
299
- };
300
- const children: string[] = [],
301
- resets: string[] = [],
302
- cancels: string[] = [];
303
- const finish = (value: Part) =>
304
- mapped`this.value = ${copyValue(value, resultAggregate)}; this.busy = false; this.done = true; this.step = 0;`;
305
- const failure = (error: Part) =>
306
- mapped`this.error = ${error}; if(this.error === 0)this.error=4; this.busy = false; this.done = true; this.step = 0;`;
307
- type Reject = (error: Part, cancellable?: boolean) => Part;
308
- const awaitState = (
309
- awaited: ts.AwaitExpression | ts.CallExpression,
310
- target: string | undefined,
311
- next: number,
312
- reject: Reject,
313
- ): number => {
314
- const expression = ts.isAwaitExpression(awaited) ? awaited.expression : awaited;
315
- if (!ts.isCallExpression(expression))
316
- fail(awaited, "Await requires a tsPLC operation or a statically named async function.");
317
- const call = expression,
318
- name = ts.isPropertyAccessExpression(call.expression)
319
- ? call.expression.name
320
- : call.expression;
321
- const child = `child${children.length}`;
322
- if (official(name, "sleep")) {
323
- if (call.arguments.length !== 1 || call.typeArguments?.length || target)
324
- fail(call, "sleep takes one TIME and returns void.");
325
- children.push(`private ${child} = new OnDelayTimer();`);
326
- resets.push(`this.${child}.update({enabled:false,duration:ms(0)});`);
327
- const poll = state(
328
- mapped`this.${child}.update({enabled:true,duration:${rewrite(call.arguments[0]!)}}); if(this.${child}.out.done) { this.step = ${next}; }`,
329
- awaited,
330
- "await",
331
- );
332
- return state(
333
- mapped`this.${child}.update({enabled:true,duration:${rewrite(call.arguments[0]!)}});this.step=${poll};`,
334
- awaited,
335
- "await",
336
- true,
337
- );
338
- }
339
- if (official(name, "fetch") || official(name, "opcuaCall")) {
340
- const rpc = official(name, "opcuaCall");
341
- if (
342
- call.arguments.length < 1 ||
343
- call.arguments.length > 2 ||
344
- !call.typeArguments?.length ||
345
- call.typeArguments.length > 2
346
- )
347
- fail(
348
- call,
349
- "fetch<Response, Request?> requires a URL and optional { method, json } options.",
350
- );
351
- const url = staticString(checker, call.arguments[0]!);
352
- if (url === undefined)
353
- fail(
354
- call.arguments[0]!,
355
- "fetch URL must be a literal or compile-time const string; configuration properties must be readonly.",
356
- );
357
- const options = rpc ? undefined : call.arguments[1];
358
- if (options && !ts.isObjectLiteralExpression(options))
359
- fail(options, "fetch options must be an inline { method, json } object.");
360
- let method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" = rpc ? "POST" : "GET";
361
- let json: ts.Expression | undefined = rpc ? call.arguments[1] : undefined;
362
- if (options && ts.isObjectLiteralExpression(options))
363
- for (const property of options.properties) {
364
- if (!ts.isPropertyAssignment(property) || !ts.isIdentifier(property.name))
365
- fail(property, "fetch options require named properties.");
366
- if (property.name.text === "method") {
367
- const value = staticString(checker, property.initializer);
368
- if (
369
- value !== "GET" &&
370
- value !== "POST" &&
371
- value !== "PUT" &&
372
- value !== "PATCH" &&
373
- value !== "DELETE"
374
- )
375
- fail(property, "Unsupported fetch method.");
376
- method = value;
377
- } else if (property.name.text === "json") json = property.initializer;
378
- else fail(property, "Unsupported fetch option.");
379
- }
380
- if (method === "GET" && json) fail(call, "GET requests cannot contain json.");
381
- const responseType = text(call.typeArguments[0]!),
382
- httpName = `Tsplc${rpc ? "Rpc" : "Http"}${sequence++}`;
383
- let requestType = `${httpName}Request`;
384
- if (!json) extra.push(from(call, `interface ${requestType} {reserved:BOOL}`));
385
- if (json) {
386
- if (call.typeArguments[1]) requestType = text(call.typeArguments[1]);
387
- else {
388
- const layout = checker.getTypeAtLocation(json);
389
- if (!layout.aliasSymbol && (!layout.symbol || layout.symbol.name === "__type"))
390
- fail(
391
- json,
392
- "Annotate json with a named PLC record or supply the Request type argument.",
393
- );
394
- requestType = checker.typeToString(
395
- layout,
396
- json,
397
- ts.TypeFormatFlags.NoTruncation |
398
- ts.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope,
399
- );
400
- }
401
- }
402
- extra.push(
403
- from(
404
- call,
405
- `interface ${httpName}Input {start:BOOL;cancel:BOOL;request:${requestType}}
406
- interface ${httpName}Output {busy:BOOL;done:BOOL;error:UDINT;result:${responseType}}
407
- class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { protected execute(input:${httpName}Input):${httpName}Output {return {busy:false,done:false,error:0,result:defaultValue<${responseType}>()};} }`,
408
- ),
409
- );
410
- result.blocks.set(
411
- `${source.fileName}:${httpName}`,
412
- rpc
413
- ? { kind: "rpc", path: url }
414
- : {
415
- kind: "http",
416
- url,
417
- method,
418
- json: Boolean(json),
419
- },
420
- );
421
- children.push(`private ${child} = new ${httpName}();`);
422
- resets.push(
423
- `this.${child}.update({start:false,cancel:false,request:defaultValue<${requestType}>()});`,
424
- );
425
- cancels.push(
426
- `this.${child}.update({start:false,cancel:true,request:defaultValue<${requestType}>()});`,
427
- );
428
- return state(
429
- mapped`this.${child}.update({start:true,cancel:false,request:${json ? rewrite(json) : `defaultValue<${requestType}>()`}}); if(this.${child}.out.done) { if(this.${child}.out.error !== 0) {${reject(`this.${child}.out.error`, true)}} else {${target ? mapped`${target} = ${copyValue(`this.${child}.out.result`, Boolean(checker.getAwaitedType(checker.getTypeAtLocation(call))!.flags & ts.TypeFlags.Object))};` : ""}this.step = ${next};} }`,
430
- awaited,
431
- "await",
432
- );
433
- }
434
- const jobDeclaration = symbol(name)?.declarations?.find(
435
- (node) => ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node),
436
- );
437
- const jobInitializer =
438
- jobDeclaration &&
439
- (ts.isVariableDeclaration(jobDeclaration) || ts.isPropertyDeclaration(jobDeclaration))
440
- ? jobDeclaration.initializer
441
- : undefined;
442
- if (
443
- jobInitializer &&
444
- ts.isCallExpression(jobInitializer) &&
445
- ts.isPropertyAccessExpression(jobInitializer.expression) &&
446
- official(jobInitializer.expression.expression, "backgroundTasks") &&
447
- jobInitializer.expression.name.text === "define"
448
- ) {
449
- const receiver = rewrite(call.expression),
450
- borrow = `borrow${children.length}`;
451
- children.push(`private ${borrow}:BOOL=false;`);
452
- resets.push(`this.${borrow}=false;`);
453
- cancels.push(
454
- `if(this.${borrow}){${receiver}.cancel();const borrowed=${receiver}.snapshot();if(!borrowed.valid||borrowed.busy)return;if(!${receiver}.reset())return;this.${borrow}=false;}`,
455
- );
456
- const poll = state(
457
- mapped`const borrowed=${receiver}.snapshot();if(borrowed.valid&&borrowed.done){if(${receiver}.reset()){this.${borrow}=false;if(borrowed.error!==0){${reject("borrowed.error", true)}}else{${target ? mapped`${target}=${copyValue("borrowed.result", Boolean(checker.getAwaitedType(checker.getTypeAtLocation(call))!.flags & ts.TypeFlags.Object))};` : ""}this.step=${next};}}}`,
458
- awaited,
459
- "await",
460
- );
461
- return state(
462
- mapped`const available=${receiver}.snapshot();if(!available.valid)return;if(available.busy||available.done){${reject("7")}}else{const accepted:BOOL=${receiver}.start(${joined(call.arguments.map(rewrite), ",")});if(accepted){this.${borrow}=true;this.step=${poll};}}`,
463
- awaited,
464
- "await",
465
- true,
466
- );
467
- }
468
- const called = functions.get(symbol(name)!);
469
- if (!called) fail(call, "Await requires a known async helper or SDK operation.");
470
- const calledMethod = methods.get(symbol(name)!);
471
- if (calledMethod) {
472
- if (!ts.isPropertyAccessExpression(call.expression))
473
- fail(call, "Async methods require a static receiver.");
474
- const receiver = rewrite(call.expression.expression);
475
- const borrow = `methodBorrow${children.length}`;
476
- children.push(`private ${borrow}:BOOL=false;`);
477
- resets.push(
478
- `if(this.${borrow}){${receiver}.${calledMethod.reset}();this.${borrow}=false;}`,
479
- );
480
- cancels.push(
481
- `if(this.${borrow}){${receiver}.${calledMethod.advance}({cancel:true});const cancellingChild=${receiver}.${calledMethod.snapshot}();if(cancellingChild.busy)return;${receiver}.${calledMethod.reset}();this.${borrow}=false;}`,
482
- );
483
- const poll = state(
484
- mapped`${receiver}.${calledMethod.advance}({cancel:false});const childState=${receiver}.${calledMethod.snapshot}();if(childState.done){${receiver}.${calledMethod.reset}();this.${borrow}=false;if(childState.error!==0){${reject("childState.error", true)}}else{${target ? mapped`${target}=${copyValue("childState.result", Boolean(checker.getAwaitedType(checker.getTypeAtLocation(call))!.flags & ts.TypeFlags.Object))};` : ""}this.step=${next};}}`,
485
- awaited,
486
- "await",
487
- );
488
- return state(
489
- mapped`const accepted:BOOL=${receiver}.${calledMethod.start}(${joined(call.arguments.map(rewrite), ",")});if(!accepted){${reject("7")}}else{this.${borrow}=true;${receiver}.${calledMethod.advance}({cancel:false});this.step=${poll};}`,
490
- awaited,
491
- "await",
492
- true,
493
- );
494
- }
495
- if (!ts.isIdentifier(call.expression))
496
- fail(call, "Async helpers require a static function.");
497
- children.push(`private ${child} = new ${text(call.expression)}();`);
498
- resets.push(`this.${child}.reset();`);
499
- cancels.push(
500
- `this.${child}.update({cancel:true});const cancellingChild=this.${child}.snapshot();if(cancellingChild.busy)return;`,
501
- );
502
- const poll = state(
503
- mapped`this.${child}.update({cancel:false}); const childState = this.${child}.snapshot(); if(childState.done) {if(childState.error !== 0) {${reject("childState.error", true)}} else {${target ? mapped`${target} = ${copyValue("childState.result", Boolean(checker.getAwaitedType(checker.getTypeAtLocation(call))!.flags & ts.TypeFlags.Object))};` : ""}this.step = ${next};} }`,
504
- awaited,
505
- "await",
506
- );
507
- return state(
508
- mapped`const accepted:BOOL = this.${child}.start(${joined(call.arguments.map(rewrite), ",")}); if(accepted){this.${child}.update({cancel:false});this.step = ${poll};}`,
509
- awaited,
510
- "await",
511
- true,
512
- );
513
- };
514
- const block = (
515
- statements: readonly ts.Statement[],
516
- next: number,
517
- reject: Reject = failure,
518
- ): number => {
519
- let entry = next;
520
- for (const stmt of [...statements].reverse()) {
521
- if (ts.isBlock(stmt)) {
522
- entry = block(stmt.statements, entry, reject);
523
- continue;
524
- }
525
- if (ts.isIfStatement(stmt)) {
526
- const yes = block([stmt.thenStatement], entry, reject),
527
- no = stmt.elseStatement ? block([stmt.elseStatement], entry, reject) : entry;
528
- entry = state(
529
- mapped`if(${rewrite(stmt.expression)}) this.step = ${yes}; else this.step = ${no};`,
530
- stmt.expression,
531
- "statement",
532
- );
533
- continue;
534
- }
535
- if (ts.isTryStatement(stmt)) {
536
- if (!stmt.catchClause || stmt.finallyBlock)
537
- fail(stmt, "Async try requires catch; finally is not supported yet.");
538
- const caught = block(stmt.catchClause.block.statements, entry, reject);
539
- const declaration = stmt.catchClause.variableDeclaration;
540
- const field = declaration && fields.get(symbol(declaration.name)!);
541
- entry = block(stmt.tryBlock.statements, entry, (error, cancellable) => {
542
- const recover = mapped`${field ? mapped`this.${field.name} = ${error};` : ""}this.step = ${caught};`;
543
- return cancellable
544
- ? mapped`if(${error} === 1) {${failure(error)}} else {${recover}}`
545
- : recover;
546
- });
547
- continue;
548
- }
549
- if (ts.isThrowStatement(stmt)) {
550
- if (
551
- !checker.isTypeAssignableTo(
552
- checker.getTypeAtLocation(stmt.expression),
553
- checker.getNumberType(),
554
- )
555
- )
556
- fail(stmt, "Async throw requires a numeric error code.");
557
- entry = state(reject(rewrite(stmt.expression)), stmt, "throw");
558
- continue;
559
- }
560
- if (ts.isReturnStatement(stmt)) {
561
- if (!stmt.expression) {
562
- if (!returnsVoid) fail(stmt, "Async routines must return a value.");
563
- entry = state(finish("true"), stmt, "return");
564
- continue;
565
- }
566
- const adopted =
567
- ts.isCallExpression(stmt.expression) &&
568
- checker.getAwaitedType(checker.getTypeAtLocation(stmt.expression)) !==
569
- checker.getTypeAtLocation(stmt.expression)
570
- ? stmt.expression
571
- : undefined;
572
- const suspension = ts.isAwaitExpression(stmt.expression) ? stmt.expression : adopted;
573
- entry = suspension
574
- ? awaitState(
575
- suspension,
576
- returnsVoid ? undefined : "this.value",
577
- state(finish(returnsVoid ? "true" : "this.value"), stmt, "return"),
578
- reject,
579
- )
580
- : state(finish(rewrite(stmt.expression)), stmt, "return");
581
- continue;
582
- }
583
- if (ts.isVariableStatement(stmt)) {
584
- for (const dec of [...stmt.declarationList.declarations].reverse()) {
585
- const field = fields.get(symbol(dec.name)!);
586
- if (!field || !dec.initializer) fail(dec, "Invalid async local.");
587
- const target = `this.${field.name}`;
588
- entry = ts.isAwaitExpression(dec.initializer)
589
- ? awaitState(dec.initializer, target, entry, reject)
590
- : state(
591
- mapped`${target} = ${copyValue(rewrite(dec.initializer), field.aggregate)}; this.step = ${entry};`,
592
- dec,
593
- "statement",
594
- );
595
- }
596
- continue;
597
- }
598
- if (ts.isExpressionStatement(stmt) && ts.isAwaitExpression(stmt.expression)) {
599
- entry = awaitState(stmt.expression, undefined, entry, reject);
600
- continue;
601
- }
602
- if (containsAwait(stmt))
603
- fail(
604
- stmt,
605
- "This suspension position is not supported; await into a named local or return.",
606
- );
607
- if (ts.isWhileStatement(stmt) || ts.isDoStatement(stmt))
608
- fail(stmt, "Unbounded loops are not supported in async routines.");
609
- entry = state(mapped`${rewrite(stmt)} this.step = ${entry};`, stmt, "statement");
610
- }
611
- return entry;
612
- };
613
- // Running off the end of the body: a void routine returns, any other fails.
614
- const end = fn.body.getLastToken(source)!;
615
- const entry = block(
616
- fn.body.statements,
617
- returnsVoid ? state(finish("true"), end, "return") : state(failure("4"), end, "throw"),
618
- );
619
- const exported = fn.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword)
620
- ? "export "
621
- : "";
622
- const aliases = `export type ${aliasPrefix(fn)}Result = ${returnType};\n${parameters.map((p, i) => `export type ${aliasPrefix(fn)}Argument${i} = ${p.type};`).join("\n")}`;
623
- const generated = mapped`${aliases}\n${exported}class ${fn.name!.getText(source)} extends FunctionBlock<{cancel:BOOL}> {
624
- private step:UINT=0; private cancelling:BOOL=false; private busy:BOOL=false; private done:BOOL=false; private error:UDINT=0; private value:${returnType}=defaultValue<${returnType}>();
625
- ${[...fields.values()].map((f) => `private ${f.name}:${f.type}=defaultValue<${f.type}>();`).join("\n")}
626
- ${children.join("\n")}
627
- start(${parameters.map((p) => `${p.name}:${p.type}`).join(",")}):BOOL {if(this.busy || this.done)return false; ${parameters.map((p) => `this.${p.field} = ${copyValue(p.name, p.aggregate)};`).join(" ")} ${resets.join(" ")} this.value = defaultValue<${returnType}>(); this.error=0;this.cancelling=false;this.busy=true;this.done=false;this.step=${entry};return true;}
628
- reset():void {${resets.join(" ")} this.busy=false;this.cancelling=false;this.done=false;this.error=0;this.step=0;}
629
- snapshot():{busy:BOOL;done:BOOL;error:UDINT;result:${returnType}} {return {busy:this.busy,done:this.done,error:this.error,result:${copyValue("this.value", resultAggregate)}};}
630
- protected execute(input:{cancel:BOOL}):void {if(!this.busy)return;if(input.cancel)this.cancelling=true;if(this.cancelling){${cancels.map((cancel) => `{${cancel}}`).join(" ")}${failure("1")}return;}for(let transition:DINT=0;transition<${nodes.size + 1};transition++){const previous:UINT=this.step;switch(this.step){${joined(
631
- [...nodes].map(([id, body]) => mapped`case ${id}: {${body}} break;`),
632
- "\n",
633
- )} }if(!this.busy||this.step===previous${[...yielding].map((id) => `||previous===${id}`).join("")})return;}}
97
+ const result: AsyncLowering = {
98
+ sources: new Map(),
99
+ blocks: new Map(),
100
+ jobs: new Map(),
101
+ programs: {},
102
+ schedules: new Map(),
103
+ diagnostics: [],
104
+ continuations: new Map(),
105
+ };
106
+ const checker = program.getTypeChecker();
107
+ const symbol = (node: ts.Node) => symbolAt(checker, node);
108
+ const fail: (node: ts.Node, message: string) => never = (node, message) => {
109
+ throw new SemanticError(asyncDiagnostic(positions, node, message));
110
+ };
111
+ const { functions, methods } = asyncRoutines(program, symbol);
112
+ if (!functions.size) {
113
+ return result;
114
+ }
115
+ let sequence = 0;
116
+ const context: AsyncContext = {
117
+ checker,
118
+ positions,
119
+ result,
120
+ functions,
121
+ methods,
122
+ ownedContinuations: new Map(),
123
+ ownedJobs: new Map(),
124
+ symbol,
125
+ namesSdk: (node, name) => namesSdk(checker, sdk, node, name),
126
+ fail,
127
+ sequence: () => sequence++,
128
+ };
129
+ const sources = runtimeSources(program).filter(
130
+ (source) => !source.isDeclarationFile,
131
+ );
132
+ for (const source of sources) {
133
+ rewriteSource(context, source);
134
+ }
135
+ for (const source of sources) {
136
+ addInstanceEntries(context, source);
137
+ }
138
+ return result;
139
+ };
634
140
 
635
- }`;
636
- if (!method) {
637
- replacements.push({ start: fn.getStart(source), end: fn.end, text: generated });
638
- result.jobs.set(`${source.fileName}:${fn.name.getText(source)}`, {
639
- name: fn.name.getText(source),
640
- span: positions.node(fn),
641
- steps,
642
- });
643
- } else {
644
- // The block's members join the method's class, renamed apart from its own members.
645
- const parsed = ts.createSourceFile(
646
- source.fileName,
647
- generated.text,
648
- ts.ScriptTarget.Latest,
649
- true,
650
- );
651
- const worker = parsed.statements.find(ts.isClassDeclaration)!;
652
- const names = new Map(
653
- worker.members.map((member) => [
654
- member.name!.getText(parsed),
655
- `tsplcAsync${fn.getStart(source)}_${member.name!.getText(parsed)}`,
656
- ]),
657
- );
658
- names.set("start", method.start);
659
- names.set("reset", method.reset);
660
- names.set("snapshot", method.snapshot);
661
- names.set("execute", method.advance);
662
- // Only the members remain, one per line.
663
- const members = worker.members;
664
- const edits: Edit[] = [
665
- ...members.map((member, index) => ({
666
- start: index ? members[index - 1]!.end : 0,
667
- end: member.getStart(parsed),
668
- text: index ? "\n" : "",
669
- })),
670
- { start: members.at(-1)!.end, end: generated.text.length, text: "" },
671
- ];
672
- const visit = (node: ts.Node): void => {
673
- if (
674
- ts.isElementAccessExpression(node) &&
675
- node.expression.kind === ts.SyntaxKind.ThisKeyword &&
676
- ts.isStringLiteral(node.argumentExpression)
677
- ) {
678
- edits.push({
679
- start: node.getStart(parsed),
680
- end: node.end,
681
- text: `this.${node.argumentExpression.text}`,
682
- });
683
- return;
684
- }
685
- const renamed =
686
- (ts.isPropertyAccessExpression(node) &&
687
- node.expression.kind === ts.SyntaxKind.ThisKeyword) ||
688
- ts.isPropertyDeclaration(node) ||
689
- ts.isMethodDeclaration(node)
690
- ? node.name
691
- : undefined;
692
- if (renamed && ts.isIdentifier(renamed) && names.has(renamed.text)) {
693
- const name = names.get(renamed.text)!;
694
- // Generated methods are called from the owner's other members.
695
- const modifiers = ts.isMethodDeclaration(node) ? node.modifiers : undefined;
696
- if (modifiers?.length)
697
- edits.push({
698
- start: modifiers[0]!.getStart(parsed),
699
- end: modifiers.at(-1)!.end,
700
- text: "public",
701
- });
702
- edits.push({
703
- start: renamed.getStart(parsed),
704
- end: renamed.end,
705
- text: ts.isMethodDeclaration(node) && !modifiers?.length ? `public ${name}` : name,
706
- });
707
- if (ts.isPropertyAccessExpression(node)) return;
708
- }
709
- ts.forEachChild(node, visit);
710
- };
711
- visit(worker);
712
- replacements.push({
713
- start: fn.getStart(source),
714
- end: fn.end,
715
- text: edited(generated, edits),
716
- });
717
- }
718
- }
719
- const workTypes = (fn: Routine, dec: ts.VariableDeclaration | ts.PropertyDeclaration) => {
720
- const reference = fn.type as ts.TypeReferenceNode;
721
- const returnType =
722
- reference.typeArguments![0]!.kind === ts.SyntaxKind.VoidKeyword
723
- ? "BOOL"
724
- : reference.typeArguments![0]!.getText(fn.getSourceFile());
725
- // Types in the job module must be visible: use the original inferred Promise result annotation at the definition boundary.
726
- const signature = checker.getSignatureFromDeclaration(fn)!;
727
- const promised = checker.getAwaitedType(checker.getReturnTypeOfSignature(signature))!;
728
- const resultType =
729
- promised.flags & ts.TypeFlags.Void
730
- ? "BOOL"
731
- : checker.typeToString(
732
- promised,
733
- dec,
734
- ts.TypeFormatFlags.NoTruncation |
735
- ts.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope,
736
- );
737
- const params = fn.parameters.map((p, i) => ({
738
- field: `argument${i}`,
739
- name: `argument${i}`,
740
- aggregate: Boolean(checker.getTypeAtLocation(p).flags & ts.TypeFlags.Object),
741
- type: checker.typeToString(
742
- checker.getTypeAtLocation(p),
743
- dec,
744
- ts.TypeFormatFlags.NoTruncation | ts.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope,
745
- ),
746
- }));
747
- // Preserve PLC widths erased by the TS checker when declarations share the module.
748
- for (let i = 0; i < params.length; i++)
749
- if (fn.getSourceFile() === source)
750
- params[i]!.type = fn.parameters[i]!.type!.getText(source);
751
- let valueType = fn.getSourceFile() === source ? returnType : resultType;
752
- if (fn.getSourceFile() !== source) {
753
- const prefix = aliasPrefix(fn);
754
- valueType = `${prefix}Result`;
755
- for (let i = 0; i < params.length; i++) params[i]!.type = `${prefix}Argument${i}`;
756
- const path = relative(dirname(source.fileName), fn.getSourceFile().fileName).replaceAll(
757
- "\\",
758
- "/",
759
- );
760
- extra.push(
761
- from(
762
- dec,
763
- `import type {${valueType},${params.map((p) => p.type).join(",")}} from ${JSON.stringify(path.startsWith(".") ? path : `./${path}`)};`,
764
- ),
765
- );
766
- }
767
- const valueAggregate = Boolean(promised.flags & ts.TypeFlags.Object);
768
- return { params, valueType, valueAggregate };
769
- };
770
- const definitions = source.statements.flatMap<
771
- ts.VariableDeclaration | ts.PropertyDeclaration
772
- >((stmt) => {
773
- if (ts.isVariableStatement(stmt)) return [...stmt.declarationList.declarations];
774
- if (ts.isClassDeclaration(stmt)) return stmt.members.filter(ts.isPropertyDeclaration);
775
- return [];
776
- });
777
- for (const dec of definitions) {
778
- const owner = ts.isPropertyDeclaration(dec) ? dec.parent : undefined;
779
- const init = dec.initializer;
780
- if (
781
- !init ||
782
- !ts.isCallExpression(init) ||
783
- !ts.isPropertyAccessExpression(init.expression) ||
784
- (!official(init.expression.expression, "backgroundTasks") &&
785
- !official(init.expression.expression, "cooperativeTasks") &&
786
- !official(init.expression.expression, "tasks")) ||
787
- init.expression.name.text !== "define"
788
- )
789
- continue;
790
- if (official(init.expression.expression, "tasks")) {
791
- const fn = functions.get(symbol(init.arguments[0] ?? init)!);
792
- if (!ts.isIdentifier(dec.name) || init.arguments.length !== 1 || !fn?.type)
793
- fail(init, "tasks.define requires one named async function with a return type.");
794
- const { params, valueType, valueAggregate } = workTypes(fn, dec);
795
- const worker = `tsplcTaskWorker${sequence++}`;
796
- const receiver = `this.${worker}`;
797
- const site = taskSite(
798
- dec.name.text,
799
- params,
800
- {
801
- start: `${receiver}.start`,
802
- advance: `${receiver}.update`,
803
- snapshot: `${receiver}.snapshot`,
804
- reset: `${receiver}.reset`,
805
- declaration: `private ${worker}=new ${init.arguments[0]!.getText(source)}();`,
806
- },
807
- Boolean(owner),
808
- { type: valueType, aggregate: valueAggregate },
809
- );
810
- if (owner) {
811
- if (!owner.name) fail(owner, "Task owners require a named block.");
812
- replacements.push({ start: dec.getStart(source), end: dec.end, text: site.body });
813
- ownedContinuations.set(symbol(owner.name)!, [
814
- ...(ownedContinuations.get(symbol(owner.name)!) ?? []),
815
- site.poll,
816
- ]);
817
- const visit = (node: ts.Node): void => {
818
- if (
819
- ts.isCallExpression(node) &&
820
- ts.isPropertyAccessExpression(node.expression) &&
821
- ts.isPropertyAccessExpression(node.expression.expression) &&
822
- node.expression.expression.expression.kind === ts.SyntaxKind.ThisKeyword &&
823
- symbol(node.expression.expression.name) === symbol(dec.name)
824
- ) {
825
- const renamed = site.renames.get(node.expression.name.text);
826
- if (renamed)
827
- replacements.push({
828
- start: node.expression.getStart(source),
829
- end: node.expression.end,
830
- text: `this.${renamed}`,
831
- });
832
- }
833
- ts.forEachChild(node, visit);
834
- };
835
- visit(owner);
836
- } else {
837
- const name = `TsplcTaskSite${sequence++}`,
838
- entry = `tsplcContinuation${sequence++}`;
839
- extra.push(
840
- from(
841
- dec,
842
- `class ${name} extends FunctionBlock<{}>{${site.body}protected execute(input:{}):void{}}
843
- export function ${entry}():void{${dec.name.text}.poll();}`,
844
- ),
845
- );
846
- replacements.push({
847
- start: init.getStart(source),
848
- end: init.end,
849
- text: `new ${name}()`,
850
- });
851
- result.programs[entry] = { module: resolve(source.fileName), export: entry };
852
- result.continuations.set(entry, {
853
- instance: dec.name.text,
854
- file: positions.node(dec).file,
855
- });
856
- }
857
- continue;
858
- }
859
- const cooperative = official(init.expression.expression, "cooperativeTasks");
860
- if (cooperative) {
861
- if (!ts.isIdentifier(dec.name) || init.arguments.length !== 1)
862
- fail(init, "Invalid compiler-owned continuation slot.");
863
- const workNode = init.arguments[0]!;
864
- const work = functions.get(
865
- symbol(ts.isPropertyAccessExpression(workNode) ? workNode.name : workNode)!,
866
- );
867
- if (!work) fail(workNode, "A continuation requires a named async routine.");
868
- const params = work.parameters.map((parameter, index) => ({
869
- name: `argument${index}`,
870
- type: parameter.type!.getText(work.getSourceFile()),
871
- aggregate: Boolean(checker.getTypeAtLocation(parameter).flags & ts.TypeFlags.Object),
872
- }));
873
- const workMethod = methods.get(symbol(work.name!)!);
874
- const worker = `tsplcCooperativeWorker${sequence++}`;
875
- const receiver = workMethod ? "this" : `this.${worker}`;
876
- const site = cooperativeSite(
877
- dec.name.text,
878
- params,
879
- {
880
- start: `${receiver}.${workMethod?.start ?? "start"}`,
881
- advance: `${receiver}.${workMethod?.advance ?? "update"}`,
882
- snapshot: `${receiver}.${workMethod?.snapshot ?? "snapshot"}`,
883
- reset: `${receiver}.${workMethod?.reset ?? "reset"}`,
884
- declaration: workMethod ? "" : `private ${worker}=new ${workNode.getText(source)}();`,
885
- },
886
- Boolean(owner),
887
- );
888
- if (owner) {
889
- if (!owner.name) fail(owner, "Continuation owners require a named block.");
890
- replacements.push({ start: dec.getStart(source), end: dec.end, text: site.body });
891
- ownedContinuations.set(symbol(owner.name)!, [
892
- ...(ownedContinuations.get(symbol(owner.name)!) ?? []),
893
- site.poll,
894
- ]);
895
- const visit = (node: ts.Node): void => {
896
- if (
897
- ts.isCallExpression(node) &&
898
- ts.isPropertyAccessExpression(node.expression) &&
899
- ts.isPropertyAccessExpression(node.expression.expression) &&
900
- node.expression.expression.expression.kind === ts.SyntaxKind.ThisKeyword &&
901
- symbol(node.expression.expression.name) === symbol(dec.name)
902
- ) {
903
- const renamed =
904
- node.expression.name.text === "start"
905
- ? site.start
906
- : node.expression.name.text === "cancel"
907
- ? site.cancel
908
- : undefined;
909
- if (renamed)
910
- replacements.push({
911
- start: node.expression.getStart(source),
912
- end: node.expression.end,
913
- text: `this.${renamed}`,
914
- });
915
- }
916
- ts.forEachChild(node, visit);
917
- };
918
- visit(owner);
919
- } else {
920
- const name = `TsplcCooperativeSite${sequence++}`,
921
- entry = `tsplcContinuation${sequence++}`;
922
- extra.push(
923
- from(
924
- dec,
925
- `class ${name} extends FunctionBlock<{}>{${site.body}protected execute(input:{}):void{}}
926
- export function ${entry}():void{${dec.name.text}.poll();}`,
927
- ),
928
- );
929
- replacements.push({
930
- start: init.getStart(source),
931
- end: init.end,
932
- text: `new ${name}()`,
933
- });
934
- result.programs[entry] = { module: resolve(source.fileName), export: entry };
935
- result.continuations.set(entry, {
936
- instance: dec.name.text,
937
- file: positions.node(dec).file,
938
- });
939
- }
940
- continue;
941
- }
942
- if (
943
- !ts.isIdentifier(dec.name) ||
944
- init.arguments.length !== 2 ||
945
- !ts.isObjectLiteralExpression(init.arguments[1]!)
946
- )
947
- fail(
948
- dec,
949
- "Define background tasks at module scope or as function-block fields with a named async function and scheduling options.",
950
- );
951
- const fn = functions.get(symbol(init.arguments[0]!)!);
952
- if (!fn?.type || !ts.isTypeReferenceNode(fn.type))
953
- fail(init, "backgroundTasks.define requires a named async function.");
954
- const { params, valueType, valueAggregate } = workTypes(fn, dec);
955
- const mailbox = `TsplcMailbox${sequence++}`,
956
- worker = `tsplcWorker${sequence++}`,
957
- entry = `tsplcBackground${sequence++}`;
958
- const requestType = `{ready:BOOL;${params.map((p) => `${p.field}:${p.type}`).join(";")}}`;
959
- const snapshotType = `{valid:BOOL;busy:BOOL;done:BOOL;cancelRequested:BOOL;error:UDINT;result:${valueType}}`;
960
- const emptySnapshot = `{valid:true,busy:this.pending || this.active,done:this.completed,cancelRequested:this.cancelRequested,error:this.failure,result:${copyValue("this.value", valueAggregate)}}`;
961
- extra.push(
962
- from(
963
- dec,
964
- `class ${mailbox} extends FunctionBlock<{}> {
965
- private pending:BOOL=false;private active:BOOL=false;private completed:BOOL=false;private cancelRequested:BOOL=false;private failure:UDINT=0;private value:${valueType}=defaultValue<${valueType}>();
966
- ${params.map((p) => `private ${p.field}:${p.type}=defaultValue<${p.type}>();`).join("\n")}
967
- start(${params.map((p) => `${p.name}:${p.type}`).join(",")}):BOOL {if(this.pending || this.active || this.completed)return false;${params.map((p) => `this.${p.field}=${copyValue(p.name, p.aggregate)};`).join("")}this.pending=true;return true;}
968
- take():${requestType} {const ready:BOOL=this.pending; if(ready){this.pending=false;this.active=true;}return {ready,${params.map((p) => `${p.field}:${copyValue(`this.${p.field}`, p.aggregate)}`).join(",")}};}
969
- publish(value:${valueType},error:UDINT):BOOL {if(!this.active)return false;if(this.cancelRequested){this.value=defaultValue<${valueType}>();this.failure=1;}else{this.value=${copyValue("value", valueAggregate)};this.failure=error;}this.active=false;this.completed=true;this.cancelRequested=false;return true;}
970
- snapshot():${snapshotType} {return ${emptySnapshot};}
971
- cancel():BOOL {if(this.pending){this.pending=false;this.completed=true;this.failure=1;return true;}if(this.active){this.cancelRequested=true;return true;}return false;}
972
- reset():BOOL {if(this.pending || this.active)return false;this.completed=false;this.failure=0;this.cancelRequested=false;this.value=defaultValue<${valueType}>();return true;}
973
- protected execute(input:{}):void {}
141
+ /** Async functions and methods by symbol; methods also get the names of their coroutine members. */
142
+ function asyncRoutines(
143
+ program: ts.Program,
144
+ symbol: (node: ts.Node) => ts.Symbol | undefined,
145
+ ) {
146
+ const functions = new Map<ts.Symbol, Routine>();
147
+ const methods = new Map<ts.Symbol, MethodMembers>();
148
+ for (const source of runtimeSources(program)) {
149
+ if (source.isDeclarationFile) {
150
+ continue;
151
+ }
152
+ for (const statement of source.statements) {
153
+ const routines = ts.isClassDeclaration(statement)
154
+ ? statement.members.filter(ts.isMethodDeclaration)
155
+ : [statement];
156
+ for (const fn of routines) {
157
+ if (!isAsyncRoutine(fn)) {
158
+ continue;
159
+ }
160
+ functions.set(symbol(fn.name)!, fn);
161
+ if (ts.isMethodDeclaration(fn)) {
162
+ const prefix = `tsplcAsync${fn.name.getText(source)}${fn.getStart(source)}`;
163
+ methods.set(symbol(fn.name)!, {
164
+ start: prefix + "Start",
165
+ reset: prefix + "Reset",
166
+ snapshot: prefix + "Snapshot",
167
+ advance: prefix + "Advance",
168
+ });
169
+ }
170
+ }
171
+ }
172
+ }
173
+ return { functions, methods };
174
+ }
175
+
176
+ /**
177
+ * Replaces a source's async routines and task definitions with generated blocks. A source
178
+ * that fails is left as written and reports why.
179
+ */
180
+ function rewriteSource(context: AsyncContext, source: ts.SourceFile): void {
181
+ try {
182
+ const replacements: Edit[] = [];
183
+ const extra: Mapped[] = [];
184
+ const file = { source, replacements, extra };
185
+ for (const fn of context.functions.values()) {
186
+ if (fn.getSourceFile() === source) {
187
+ lowerCoroutine(context, file, fn);
188
+ }
189
+ }
190
+ lowerTaskDefinitions(context, file);
191
+ if (!replacements.length) {
192
+ return;
193
+ }
194
+ // Generated classes go first, other declarations last.
195
+ const added = joined(extra, "\n");
196
+ const generated = ts.createSourceFile(
197
+ source.fileName,
198
+ added.text,
199
+ ts.ScriptTarget.Latest,
200
+ true,
201
+ );
202
+ const part = (node: ts.Node) =>
203
+ slice(added, node.getStart(generated), node.end);
204
+ const before = generated.statements.filter(ts.isClassDeclaration).map(part);
205
+ const after = generated.statements
206
+ .filter((statement) => !ts.isClassDeclaration(statement))
207
+ .map(part);
208
+ context.result.sources.set(
209
+ source.fileName,
210
+ mapped`${joined(before, "\n")}\n${edited(source, replacements)}\n${joined(after, "\n")}`,
211
+ );
212
+ } catch (cause) {
213
+ if (!(cause instanceof SemanticError)) {
214
+ throw cause;
215
+ }
216
+ context.result.diagnostics.push(cause.diagnostic);
217
+ }
218
+ }
219
+
220
+ /**
221
+ * A block that owns continuations or background jobs runs them through its instances, so each
222
+ * module-level instance gets an entry point per poll and job.
223
+ */
224
+ function addInstanceEntries(
225
+ context: AsyncContext,
226
+ source: ts.SourceFile,
227
+ ): void {
228
+ const { positions, result } = context;
229
+ const entries: Mapped[] = [];
230
+ const visit = (node: ts.Node): void => {
231
+ const instance = allocatedInstances(context.checker, source, node);
232
+ const jobs =
233
+ instance && context.ownedJobs.get(context.symbol(instance.block)!);
234
+ const polls =
235
+ instance &&
236
+ context.ownedContinuations.get(context.symbol(instance.block)!);
237
+ if (!instance || (!jobs && !polls)) {
238
+ ts.forEachChild(node, visit);
239
+ return;
240
+ }
241
+ const declaration = node.parent;
242
+ if (
243
+ !ts.isVariableDeclaration(declaration) ||
244
+ !ts.isIdentifier(declaration.name) ||
245
+ !ts.isVariableDeclarationList(declaration.parent) ||
246
+ !ts.isVariableStatement(declaration.parent.parent) ||
247
+ !ts.isSourceFile(declaration.parent.parent.parent) ||
248
+ (jobs && instance.first !== undefined)
249
+ ) {
250
+ result.diagnostics.push(
251
+ asyncDiagnostic(
252
+ positions,
253
+ node,
254
+ "Function blocks with background jobs require module-level named instances.",
255
+ ),
256
+ );
257
+ return;
258
+ }
259
+ const name = declaration.name.text;
260
+ for (const poll of polls ?? []) {
261
+ const entry = `tsplcContinuation${context.sequence()}`;
262
+ entries.push(
263
+ from(
264
+ node,
265
+ instance.first === undefined
266
+ ? `export function ${entry}():void{${name}.${poll}();}`
267
+ : `export function ${entry}():void{for(let element:DINT=${instance.first};element<=${instance.last};element++){${name}[element].${poll}();}}`,
268
+ ),
269
+ );
270
+ result.programs[entry] = {
271
+ module: resolve(source.fileName),
272
+ export: entry,
273
+ };
274
+ result.continuations.set(entry, {
275
+ instance: name,
276
+ file: positions.node(declaration).file,
277
+ });
278
+ }
279
+ for (const job of jobs ?? []) {
280
+ const entry = `tsplcBackground${context.sequence()}`;
281
+ entries.push(
282
+ from(node, `export function ${entry}():void{${name}.${job.method}();}`),
283
+ );
284
+ result.programs[entry] = {
285
+ module: resolve(source.fileName),
286
+ export: entry,
287
+ };
288
+ result.schedules.set(entry, { ...job.schedule, worker: name });
289
+ }
290
+ ts.forEachChild(node, visit);
291
+ };
292
+ visit(source);
293
+ if (entries.length) {
294
+ result.sources.set(
295
+ source.fileName,
296
+ mapped`${result.sources.get(source.fileName) ?? edited(source, [])}\n${joined(entries, "\n")}`,
297
+ );
298
+ }
299
+ }
300
+
301
+ /**
302
+ * The block instances an expression allocates: `new Block()` one instance, and
303
+ * `defaultValue<FixedArray<Block, N, Lower>>()` one per element.
304
+ */
305
+ function allocatedInstances(
306
+ checker: ts.TypeChecker,
307
+ source: ts.SourceFile,
308
+ node: ts.Node,
309
+ ): { block: ts.Node; first?: number; last?: number } | undefined {
310
+ if (ts.isNewExpression(node)) {
311
+ return { block: node.expression };
312
+ }
313
+ const type = ts.isCallExpression(node) ? node.typeArguments?.[0] : undefined;
314
+ const [element, length, lower] =
315
+ type &&
316
+ ts.isTypeReferenceNode(type) &&
317
+ type.typeName.getText(source) === "FixedArray"
318
+ ? (type.typeArguments ?? [])
319
+ : [];
320
+ if (!element || !ts.isTypeReferenceNode(element) || !length) {
321
+ return undefined;
322
+ }
323
+ // A literal, or a table's `(typeof table)["length"]`.
324
+ const integer = (node: ts.TypeNode) => {
325
+ const literal = checker.getTypeFromTypeNode(node);
326
+ return literal.isNumberLiteral() ? literal.value : NaN;
327
+ };
328
+ const first = lower ? integer(lower) : 0;
329
+ return {
330
+ block: element.typeName,
331
+ first,
332
+ last: first + integer(length) - 1,
333
+ };
974
334
  }
975
- `,
976
- ),
977
- );
978
- const receiver = owner ? `this.${dec.name.text}` : dec.name.text;
979
- const workerReceiver = owner ? `this.${worker}` : worker;
980
- const run = `const request=${receiver}.take();if(request.ready){const accepted:BOOL=${workerReceiver}.start(${params.map((p) => `request.${p.field}`).join(",")});}const control=${receiver}.snapshot();if(!control.valid)return;${workerReceiver}.update({cancel:control.cancelRequested});const state=${workerReceiver}.snapshot();if(state.done){const published:BOOL=${receiver}.publish(state.result,state.error);if(published)${workerReceiver}.reset();}`;
981
- if (owner) {
982
- if (!owner.name) fail(owner, "Background job owners need a named function block.");
983
- replacements.push({
984
- start: owner.end - 1,
985
- end: owner.end - 1,
986
- text: from(
987
- dec,
988
- `private ${worker}=new ${text(init.arguments[0]!)}();public ${entry}():void{${run}}`,
989
- ),
990
- });
991
- result.blocks.set(`${source.fileName}:${owner.name.text}`, { kind: "backgroundHost" });
992
- } else
993
- extra.push(
994
- from(
995
- dec,
996
- `const ${worker}=new ${text(init.arguments[0]!)}();export function ${entry}():void{${run}}`,
997
- ),
998
- );
999
- result.blocks.set(`${source.fileName}:${mailbox}`, { kind: "mailbox" });
1000
- const opts = new Map(
1001
- init.arguments[1]!.properties.filter(ts.isPropertyAssignment).map((p) => [
1002
- p.name.getText(source),
1003
- p.initializer,
1004
- ]),
1005
- );
1006
- const interval = opts.get("interval"),
1007
- priority = opts.get("priority");
1008
- if (
1009
- !interval ||
1010
- !ts.isCallExpression(interval) ||
1011
- interval.arguments.length !== 1 ||
1012
- !ts.isNumericLiteral(interval.arguments[0]!) ||
1013
- !priority ||
1014
- !ts.isNumericLiteral(priority) ||
1015
- !["ms", "seconds"].some((n) => official(interval.expression, n))
1016
- )
1017
- fail(init, "Background schedules require a literal ms/seconds interval and priority.");
1018
- const milliseconds =
1019
- Number(interval.arguments[0]!.text) *
1020
- (official(interval.expression, "seconds") ? 1000 : 1);
1021
- const taskPriority = Number(priority.text);
1022
- if (
1023
- !Number.isSafeInteger(milliseconds) ||
1024
- milliseconds <= 0 ||
1025
- milliseconds > 4294967295 ||
1026
- !Number.isInteger(taskPriority) ||
1027
- taskPriority < 1 ||
1028
- taskPriority > 31
1029
- )
1030
- fail(
1031
- init,
1032
- "Background interval must be positive and priority must be an integer in 1..31.",
1033
- );
1034
- const schedule = {
1035
- intervalNanoseconds: String(BigInt(milliseconds) * 1000000n),
1036
- priority: taskPriority,
1037
- mailbox: dec.name.text,
1038
- worker,
1039
- };
1040
- if (owner) {
1041
- const key = symbol(owner.name!)!;
1042
- ownedJobs.set(key, [...(ownedJobs.get(key) ?? []), { method: entry, schedule }]);
1043
- } else {
1044
- result.programs[entry] = { module: resolve(source.fileName), export: entry };
1045
- result.schedules.set(entry, schedule);
1046
- }
1047
- replacements.push({
1048
- start: init.getStart(source),
1049
- end: init.end,
1050
- text: `new ${mailbox}()`,
1051
- });
1052
- }
1053
- if (replacements.length) {
1054
- // Generated classes go first, other declarations last.
1055
- const added = joined(extra, "\n");
1056
- const generated = ts.createSourceFile(
1057
- source.fileName,
1058
- added.text,
1059
- ts.ScriptTarget.Latest,
1060
- true,
1061
- );
1062
- const part = (node: ts.Node) => slice(added, node.getStart(generated), node.end);
1063
- const before = generated.statements.filter(ts.isClassDeclaration).map(part);
1064
- const after = generated.statements.filter((n) => !ts.isClassDeclaration(n)).map(part);
1065
- result.sources.set(
1066
- source.fileName,
1067
- mapped`${joined(before, "\n")}\n${edited(source, replacements)}\n${joined(after, "\n")}`,
1068
- );
1069
- }
1070
- } catch (cause) {
1071
- if (typeof cause === "object" && cause !== null && "asyncDiagnostic" in cause)
1072
- result.diagnostics.push(cause.asyncDiagnostic as Diagnostic);
1073
- else throw cause;
1074
- }
1075
- }
1076
- for (const source of runtimeSources(program)) {
1077
- if (source.isDeclarationFile) continue;
1078
- const entries: Mapped[] = [];
1079
- // `new Block()` allocates one instance; `defaultValue<FixedArray<Block, N, Lower>>()` one per element.
1080
- const allocated = (node: ts.Node) => {
1081
- if (ts.isNewExpression(node)) return { block: node.expression };
1082
- const type = ts.isCallExpression(node) ? node.typeArguments?.[0] : undefined;
1083
- const [element, length, lower] =
1084
- type && ts.isTypeReferenceNode(type) && type.typeName.getText(source) === "FixedArray"
1085
- ? (type.typeArguments ?? [])
1086
- : [];
1087
- if (!element || !ts.isTypeReferenceNode(element) || !length) return undefined;
1088
- // A literal, or a table's `(typeof table)["length"]`.
1089
- const integer = (node: ts.TypeNode) => {
1090
- const type = checker.getTypeFromTypeNode(node);
1091
- return type.isNumberLiteral() ? type.value : NaN;
1092
- };
1093
- const first = lower ? integer(lower) : 0;
1094
- return { block: element.typeName, first, last: first + integer(length) - 1 };
1095
- };
1096
- const visit = (node: ts.Node): void => {
1097
- const instance = allocated(node);
1098
- if (instance) {
1099
- const jobs = ownedJobs.get(symbol(instance.block)!);
1100
- const polls = ownedContinuations.get(symbol(instance.block)!);
1101
- if (jobs || polls) {
1102
- const declaration = node.parent;
1103
- if (
1104
- !ts.isVariableDeclaration(declaration) ||
1105
- !ts.isIdentifier(declaration.name) ||
1106
- !ts.isVariableDeclarationList(declaration.parent) ||
1107
- !ts.isVariableStatement(declaration.parent.parent) ||
1108
- !ts.isSourceFile(declaration.parent.parent.parent) ||
1109
- (jobs && instance.first !== undefined)
1110
- ) {
1111
- result.diagnostics.push(
1112
- diagnosticFor(
1113
- node,
1114
- "Function blocks with background jobs require module-level named instances.",
1115
- ),
1116
- );
1117
- return;
1118
- }
1119
- const name = declaration.name.text;
1120
- for (const poll of polls ?? []) {
1121
- const entry = `tsplcContinuation${sequence++}`;
1122
- entries.push(
1123
- from(
1124
- node,
1125
- instance.first === undefined
1126
- ? `export function ${entry}():void{${name}.${poll}();}`
1127
- : `export function ${entry}():void{for(let element:DINT=${instance.first};element<=${instance.last};element++){${name}[element].${poll}();}}`,
1128
- ),
1129
- );
1130
- result.programs[entry] = { module: resolve(source.fileName), export: entry };
1131
- result.continuations.set(entry, {
1132
- instance: name,
1133
- file: positions.node(declaration).file,
1134
- });
1135
- }
1136
- for (const job of jobs ?? []) {
1137
- const entry = `tsplcBackground${sequence++}`;
1138
- entries.push(from(node, `export function ${entry}():void{${name}.${job.method}();}`));
1139
- result.programs[entry] = { module: resolve(source.fileName), export: entry };
1140
- result.schedules.set(entry, { ...job.schedule, worker: name });
1141
- }
1142
- }
1143
- }
1144
- ts.forEachChild(node, visit);
1145
- };
1146
- visit(source);
1147
- if (entries.length)
1148
- result.sources.set(
1149
- source.fileName,
1150
- mapped`${result.sources.get(source.fileName) ?? edited(source, [])}\n${joined(entries, "\n")}`,
1151
- );
1152
- }
1153
- return result;
1154
- };