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