@tsplc/compiler 0.2.17 → 0.2.19
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
package/src/frontend/promises.ts
CHANGED
|
@@ -1,756 +1,399 @@
|
|
|
1
|
-
import { runtimeSources } from "./module-graph.ts";
|
|
1
|
+
import { importSpecifier, runtimeSources } from "./module-graph.ts";
|
|
2
2
|
import ts from "typescript";
|
|
3
|
-
import {
|
|
3
|
+
import { namesSdk, symbolAt } from "./sdk.ts";
|
|
4
4
|
import { error, type Diagnostic } from "@tsplc/compiler/ir";
|
|
5
|
+
import { chainOf, lowerChain } from "./promise-chains.ts";
|
|
6
|
+
import { SemanticError, hasModifier } from "./types.ts";
|
|
5
7
|
import {
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
8
|
+
edited,
|
|
9
|
+
from,
|
|
10
|
+
joined,
|
|
11
|
+
mapped,
|
|
12
|
+
type Edit,
|
|
13
|
+
type Mapped,
|
|
14
|
+
type Positions,
|
|
13
15
|
} from "./positions.ts";
|
|
14
16
|
|
|
15
|
-
type Routine = ts.FunctionDeclaration | ts.MethodDeclaration;
|
|
16
|
-
|
|
17
|
-
interface
|
|
18
|
-
|
|
19
|
-
|
|
17
|
+
export type Routine = ts.FunctionDeclaration | ts.MethodDeclaration;
|
|
18
|
+
|
|
19
|
+
interface PromiseLowering {
|
|
20
|
+
sources: Map<string, Mapped>;
|
|
21
|
+
diagnostics: Diagnostic[];
|
|
22
|
+
runtimeBlocks: Map<string, { kind: "mailbox" }>;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** What lowering one chain needs from the rewrite of the whole program. */
|
|
26
|
+
export interface PromiseContext {
|
|
27
|
+
readonly checker: ts.TypeChecker;
|
|
28
|
+
/** Every function and method by symbol; named callbacks and operations resolve here. */
|
|
29
|
+
readonly routines: ReadonlyMap<ts.Symbol, Routine>;
|
|
30
|
+
/** The sites of detached chains, by the module or class whose cancelAsync cancels them. */
|
|
31
|
+
readonly sites: Map<ts.SourceFile | ts.ClassDeclaration, string[]>;
|
|
32
|
+
symbol(node: ts.Node): ts.Symbol | undefined;
|
|
33
|
+
/** Whether a node names the SDK declaration `name`. */
|
|
34
|
+
namesSdk(node: ts.Node, name: string): boolean;
|
|
35
|
+
fail(node: ts.Node, message: string): never;
|
|
36
|
+
/** The next number for a generated name. */
|
|
37
|
+
sequence(): number;
|
|
38
|
+
/** Adds generated code to the end of a module, or to a class, mapped to the node it was made for. */
|
|
39
|
+
append(
|
|
40
|
+
scope: ts.SourceFile | ts.ClassDeclaration,
|
|
41
|
+
origin: ts.Node,
|
|
42
|
+
text: string,
|
|
43
|
+
): void;
|
|
44
|
+
/** A type's text as `source` names it: declared elsewhere, it is aliased there and imported. */
|
|
45
|
+
typeText(node: ts.TypeNode, source: ts.SourceFile): string;
|
|
46
|
+
/** Imports the SDK names generated helpers use into `source`, once. */
|
|
47
|
+
ensureImports(source: ts.SourceFile, origin: ts.Node): void;
|
|
48
|
+
/** Marks that generated code reports to the shared diagnostics block. */
|
|
49
|
+
useDiagnostics(node: ts.Node): void;
|
|
20
50
|
}
|
|
21
51
|
|
|
52
|
+
/** The name of the shared diagnostics instance that detached chains report failures to. */
|
|
53
|
+
const diagnosticsInstance = "tsplcPromiseDiagnostics";
|
|
54
|
+
|
|
22
55
|
/** Normalize promise syntax into named coroutines; scheduling stays in async lowering. */
|
|
23
|
-
export const lowerPromises = (
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
}
|
|
78
|
-
const asyncRoutine = (node: ts.Node) => {
|
|
79
|
-
const fn = routines.get(symbol(node)!);
|
|
80
|
-
return fn?.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword)
|
|
81
|
-
? fn
|
|
82
|
-
: undefined;
|
|
83
|
-
};
|
|
84
|
-
const job = (node: ts.Node) => {
|
|
85
|
-
const declaration = symbol(node)?.declarations?.find(
|
|
86
|
-
(value) => ts.isVariableDeclaration(value) || ts.isPropertyDeclaration(value),
|
|
87
|
-
);
|
|
88
|
-
if (
|
|
89
|
-
!declaration ||
|
|
90
|
-
(!ts.isVariableDeclaration(declaration) && !ts.isPropertyDeclaration(declaration))
|
|
91
|
-
)
|
|
92
|
-
return;
|
|
93
|
-
const init = declaration.initializer;
|
|
94
|
-
if (
|
|
95
|
-
!init ||
|
|
96
|
-
!ts.isCallExpression(init) ||
|
|
97
|
-
!ts.isPropertyAccessExpression(init.expression) ||
|
|
98
|
-
!official(init.expression.expression, "backgroundTasks") ||
|
|
99
|
-
init.expression.name.text !== "define"
|
|
100
|
-
)
|
|
101
|
-
return;
|
|
102
|
-
return asyncRoutine(init.arguments[0]!);
|
|
103
|
-
};
|
|
104
|
-
const operation = (call: ts.CallExpression) =>
|
|
105
|
-
asyncRoutine(
|
|
106
|
-
ts.isPropertyAccessExpression(call.expression) ? call.expression.name : call.expression,
|
|
107
|
-
) ??
|
|
108
|
-
job(ts.isPropertyAccessExpression(call.expression) ? call.expression.name : call.expression);
|
|
109
|
-
const isSdk = (call: ts.CallExpression, name: string) =>
|
|
110
|
-
official(
|
|
111
|
-
ts.isPropertyAccessExpression(call.expression) ? call.expression.name : call.expression,
|
|
112
|
-
name,
|
|
113
|
-
);
|
|
114
|
-
const split = (
|
|
115
|
-
expression: ts.Expression,
|
|
116
|
-
): { root: ts.CallExpression; parts: Part[] } | undefined => {
|
|
117
|
-
if (!ts.isCallExpression(expression)) return;
|
|
118
|
-
if (
|
|
119
|
-
ts.isPropertyAccessExpression(expression.expression) &&
|
|
120
|
-
["then", "catch"].includes(expression.expression.name.text)
|
|
121
|
-
) {
|
|
122
|
-
const prefix = split(expression.expression.expression);
|
|
123
|
-
if (!prefix) return;
|
|
124
|
-
return {
|
|
125
|
-
root: prefix.root,
|
|
126
|
-
parts: [
|
|
127
|
-
...prefix.parts,
|
|
128
|
-
{
|
|
129
|
-
kind: expression.expression.name.text === "then" ? "then" : "catch",
|
|
130
|
-
handlers: expression.arguments,
|
|
131
|
-
},
|
|
132
|
-
],
|
|
133
|
-
};
|
|
134
|
-
}
|
|
135
|
-
if (operation(expression) || isSdk(expression, "sleep") || isSdk(expression, "fetch"))
|
|
136
|
-
return { root: expression, parts: [] };
|
|
137
|
-
};
|
|
138
|
-
const aliases = new Map<ts.Node, string>();
|
|
139
|
-
const typeImports = new Map<ts.SourceFile, Set<string>>();
|
|
140
|
-
const typeText = (node: ts.TypeNode, source: ts.SourceFile): string => {
|
|
141
|
-
if (node.kind === ts.SyntaxKind.VoidKeyword) return "void";
|
|
142
|
-
if (node.getSourceFile() === source) return node.getText(source);
|
|
143
|
-
let alias = aliases.get(node);
|
|
144
|
-
if (!alias) {
|
|
145
|
-
alias = `TsplcPromiseType${sequence++}`;
|
|
146
|
-
aliases.set(node, alias);
|
|
147
|
-
append(
|
|
148
|
-
node.getSourceFile(),
|
|
149
|
-
node,
|
|
150
|
-
`export type ${alias}=${node.getText(node.getSourceFile())};`,
|
|
151
|
-
);
|
|
152
|
-
}
|
|
153
|
-
const path = relative(dirname(source.fileName), node.getSourceFile().fileName).replaceAll(
|
|
154
|
-
"\\",
|
|
155
|
-
"/",
|
|
156
|
-
);
|
|
157
|
-
const importedAliases = typeImports.get(source) ?? new Set<string>();
|
|
158
|
-
if (importedAliases.has(alias)) return alias;
|
|
159
|
-
importedAliases.add(alias);
|
|
160
|
-
typeImports.set(source, importedAliases);
|
|
161
|
-
append(
|
|
162
|
-
source,
|
|
163
|
-
node,
|
|
164
|
-
`import type {${alias}} from ${JSON.stringify(path.startsWith(".") ? path : `./${path}`)};`,
|
|
165
|
-
);
|
|
166
|
-
return alias;
|
|
167
|
-
};
|
|
168
|
-
const expressionType = (node: ts.Expression, source: ts.SourceFile): string => {
|
|
169
|
-
if (
|
|
170
|
-
ts.isCallExpression(node) &&
|
|
171
|
-
node.typeArguments?.[0] &&
|
|
172
|
-
(official(node.expression, "defaultValue") ||
|
|
173
|
-
official(node.expression, "copy") ||
|
|
174
|
-
["exact", "wrap", "wrapAdd", "wrapMultiply", "saturate"].some((name) =>
|
|
175
|
-
official(node.expression, name),
|
|
176
|
-
))
|
|
177
|
-
)
|
|
178
|
-
return typeText(node.typeArguments[0], source);
|
|
179
|
-
const name = ts.isPropertyAccessExpression(node) ? node.name : node;
|
|
180
|
-
const declaration = symbol(name)?.declarations?.find(
|
|
181
|
-
(value) =>
|
|
182
|
-
(ts.isVariableDeclaration(value) ||
|
|
183
|
-
ts.isParameter(value) ||
|
|
184
|
-
ts.isPropertyDeclaration(value) ||
|
|
185
|
-
ts.isPropertySignature(value)) &&
|
|
186
|
-
value.type,
|
|
187
|
-
);
|
|
188
|
-
if (
|
|
189
|
-
declaration &&
|
|
190
|
-
(ts.isVariableDeclaration(declaration) ||
|
|
191
|
-
ts.isParameter(declaration) ||
|
|
192
|
-
ts.isPropertyDeclaration(declaration) ||
|
|
193
|
-
ts.isPropertySignature(declaration)) &&
|
|
194
|
-
declaration.type
|
|
195
|
-
)
|
|
196
|
-
return typeText(declaration.type, source);
|
|
197
|
-
const type = checker.getTypeAtLocation(node);
|
|
198
|
-
if (type.flags & ts.TypeFlags.BooleanLike) return "BOOL";
|
|
199
|
-
if (type.flags & ts.TypeFlags.Void) return "void";
|
|
200
|
-
if (type.symbol && type.symbol.name !== "__type" && type.flags & ts.TypeFlags.Object)
|
|
201
|
-
return checker.typeToString(
|
|
202
|
-
type,
|
|
203
|
-
node,
|
|
204
|
-
ts.TypeFormatFlags.NoTruncation | ts.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope,
|
|
205
|
-
);
|
|
206
|
-
fail(
|
|
207
|
-
node,
|
|
208
|
-
"Annotate this value with its concrete PLC type before using it in an async continuation.",
|
|
209
|
-
);
|
|
210
|
-
};
|
|
211
|
-
const isAggregate = (type: ts.Type | undefined) =>
|
|
212
|
-
Boolean(type && type.flags & ts.TypeFlags.Object);
|
|
213
|
-
const isPromise = (node: ts.Node) => {
|
|
214
|
-
const type = checker.getTypeAtLocation(node);
|
|
215
|
-
return checker.getAwaitedType(type) !== type;
|
|
216
|
-
};
|
|
217
|
-
const printer = ts.createPrinter();
|
|
218
|
-
const replaceNames = (node: ts.Node, names: ReadonlyMap<ts.Symbol, string>): string => {
|
|
219
|
-
const transformed = ts.transform(node, [
|
|
220
|
-
(context) => (root) => {
|
|
221
|
-
const visit = (value: ts.Node): ts.VisitResult<ts.Node> => {
|
|
222
|
-
if (
|
|
223
|
-
ts.isReturnStatement(value) &&
|
|
224
|
-
value.expression &&
|
|
225
|
-
!ts.isAwaitExpression(value.expression) &&
|
|
226
|
-
isPromise(value.expression)
|
|
227
|
-
) {
|
|
228
|
-
return ts.factory.updateReturnStatement(
|
|
229
|
-
value,
|
|
230
|
-
ts.factory.createAwaitExpression(
|
|
231
|
-
ts.visitNode(value.expression, visit) as ts.Expression,
|
|
232
|
-
),
|
|
233
|
-
);
|
|
234
|
-
}
|
|
235
|
-
if (ts.isShorthandPropertyAssignment(value)) {
|
|
236
|
-
const key = checker.getShorthandAssignmentValueSymbol(value);
|
|
237
|
-
const name = key && names.get(key);
|
|
238
|
-
if (name)
|
|
239
|
-
return ts.factory.createPropertyAssignment(
|
|
240
|
-
value.name,
|
|
241
|
-
ts.factory.createIdentifier(name),
|
|
242
|
-
);
|
|
243
|
-
}
|
|
244
|
-
if (
|
|
245
|
-
ts.isIdentifier(value) &&
|
|
246
|
-
!(ts.isPropertyAccessExpression(value.parent) && value.parent.name === value) &&
|
|
247
|
-
!(ts.isPropertyAssignment(value.parent) && value.parent.name === value)
|
|
248
|
-
) {
|
|
249
|
-
const name = names.get(symbol(value)!);
|
|
250
|
-
if (name) return ts.factory.createIdentifier(name);
|
|
251
|
-
}
|
|
252
|
-
return ts.visitEachChild(value, visit, context);
|
|
253
|
-
};
|
|
254
|
-
return ts.visitNode(root, visit) as typeof root;
|
|
255
|
-
},
|
|
256
|
-
]);
|
|
257
|
-
const value = printer.printNode(
|
|
258
|
-
ts.EmitHint.Unspecified,
|
|
259
|
-
transformed.transformed[0]!,
|
|
260
|
-
node.getSourceFile(),
|
|
261
|
-
);
|
|
262
|
-
transformed.dispose();
|
|
263
|
-
return value;
|
|
264
|
-
};
|
|
265
|
-
const hasBorrow = (node: ts.TypeNode, seen = new Set<ts.Symbol>()): boolean => {
|
|
266
|
-
if (ts.isTypeReferenceNode(node)) {
|
|
267
|
-
if (official(node.typeName, "InOut")) return true;
|
|
268
|
-
const key = symbol(node.typeName);
|
|
269
|
-
if (key && !seen.has(key)) {
|
|
270
|
-
seen.add(key);
|
|
271
|
-
for (const declaration of key.declarations ?? []) {
|
|
272
|
-
if (
|
|
273
|
-
ts.isInterfaceDeclaration(declaration) &&
|
|
274
|
-
declaration.members.some(
|
|
275
|
-
(member) =>
|
|
276
|
-
ts.isPropertySignature(member) && member.type && hasBorrow(member.type, seen),
|
|
277
|
-
)
|
|
278
|
-
)
|
|
279
|
-
return true;
|
|
280
|
-
if (ts.isTypeAliasDeclaration(declaration) && hasBorrow(declaration.type, seen))
|
|
281
|
-
return true;
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
|
-
}
|
|
285
|
-
return node.getChildren().some((child) => ts.isTypeNode(child) && hasBorrow(child, seen));
|
|
286
|
-
};
|
|
287
|
-
/** The first node that needs the shared diagnostics block, which its module declares. */
|
|
288
|
-
let diagnosticOwner: ts.Node | undefined;
|
|
289
|
-
const diag = () => {
|
|
290
|
-
if (!diagnosticOwner) throw new Error("Missing async diagnostics owner");
|
|
291
|
-
return "tsplcPromiseDiagnostics";
|
|
292
|
-
};
|
|
293
|
-
const imported = new Set<ts.SourceFile>();
|
|
294
|
-
const ensureImports = (source: ts.SourceFile, origin: ts.Node) => {
|
|
295
|
-
if (imported.has(source)) return;
|
|
296
|
-
imported.add(source);
|
|
297
|
-
append(
|
|
298
|
-
source,
|
|
299
|
-
origin,
|
|
300
|
-
`import {cooperativeTasks as tsplcCooperative,errorCode as tsplcErrorCode} from "@tsplc/compiler/async";import {wrapAdd as tsplcAsyncWrapAdd} from "@tsplc/compiler/types";`,
|
|
301
|
-
);
|
|
302
|
-
};
|
|
303
|
-
const scopes = new Map<ts.SourceFile | ts.ClassDeclaration, string[]>();
|
|
304
|
-
const make = (
|
|
305
|
-
expression: ts.Expression,
|
|
306
|
-
owner: ts.FunctionDeclaration | ts.MethodDeclaration,
|
|
307
|
-
detached: boolean,
|
|
308
|
-
): string => {
|
|
309
|
-
const parsed = split(expression);
|
|
310
|
-
if (!parsed) fail(expression, "Expected a statically resolved async call.");
|
|
311
|
-
const source = expression.getSourceFile();
|
|
312
|
-
const classOwner =
|
|
313
|
-
ts.isMethodDeclaration(owner) && ts.isClassDeclaration(owner.parent)
|
|
314
|
-
? owner.parent
|
|
315
|
-
: undefined;
|
|
316
|
-
ensureImports(source, expression);
|
|
317
|
-
diagnosticOwner ??= expression;
|
|
318
|
-
const captures = new Map<ts.Symbol, { name: string; type: string; argument: string }>();
|
|
319
|
-
const collectCaptures = (handler: Handler) => {
|
|
320
|
-
const visit = (node: ts.Node): void => {
|
|
321
|
-
if (
|
|
322
|
-
ts.isIdentifier(node) &&
|
|
323
|
-
!(ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) &&
|
|
324
|
-
!(ts.isPropertyAssignment(node.parent) && node.parent.name === node)
|
|
325
|
-
) {
|
|
326
|
-
const key = ts.isShorthandPropertyAssignment(node.parent)
|
|
327
|
-
? checker.getShorthandAssignmentValueSymbol(node.parent)
|
|
328
|
-
: symbol(node);
|
|
329
|
-
const declaration = key?.valueDeclaration;
|
|
330
|
-
if (
|
|
331
|
-
declaration &&
|
|
332
|
-
(ts.isVariableDeclaration(declaration) || ts.isParameter(declaration))
|
|
333
|
-
) {
|
|
334
|
-
let scope: ts.Node | undefined = declaration.parent;
|
|
335
|
-
while (scope && !ts.isFunctionLike(scope)) scope = scope.parent;
|
|
336
|
-
if (scope === owner && !captures.has(key!)) {
|
|
337
|
-
if (
|
|
338
|
-
ts.isVariableDeclaration(declaration) &&
|
|
339
|
-
(!ts.isVariableDeclarationList(declaration.parent) ||
|
|
340
|
-
!(declaration.parent.flags & ts.NodeFlags.Const))
|
|
341
|
-
)
|
|
342
|
-
fail(
|
|
343
|
-
node,
|
|
344
|
-
"Continuation captures must be const values; store mutable state on the controller instead.",
|
|
345
|
-
);
|
|
346
|
-
if (!declaration.type)
|
|
347
|
-
fail(node, "Annotate a captured value with its concrete PLC type.");
|
|
348
|
-
if (hasBorrow(declaration.type))
|
|
349
|
-
fail(
|
|
350
|
-
node,
|
|
351
|
-
"A continuation cannot capture borrowed InOut storage; capture values or use controller state.",
|
|
352
|
-
);
|
|
353
|
-
captures.set(key!, {
|
|
354
|
-
name: `capture${captures.size}`,
|
|
355
|
-
type: typeText(declaration.type, source),
|
|
356
|
-
argument: node.text,
|
|
357
|
-
});
|
|
358
|
-
}
|
|
359
|
-
}
|
|
360
|
-
}
|
|
361
|
-
ts.forEachChild(node, visit);
|
|
362
|
-
};
|
|
363
|
-
visit(handler.body!);
|
|
364
|
-
};
|
|
365
|
-
for (const part of parsed.parts)
|
|
366
|
-
for (const value of part.handlers) {
|
|
367
|
-
if (
|
|
368
|
-
value.kind === ts.SyntaxKind.UndefinedKeyword ||
|
|
369
|
-
value.kind === ts.SyntaxKind.NullKeyword
|
|
370
|
-
)
|
|
371
|
-
continue;
|
|
372
|
-
if (ts.isArrowFunction(value) || ts.isFunctionExpression(value)) collectCaptures(value);
|
|
373
|
-
}
|
|
374
|
-
const captureNames = new Map([...captures].map(([key, value]) => [key, value.name]));
|
|
375
|
-
const root = parsed.root,
|
|
376
|
-
fn = operation(root);
|
|
377
|
-
let resultAggregate = isAggregate(checker.getAwaitedType(checker.getTypeAtLocation(root)));
|
|
378
|
-
const arguments_: { name: string; type: string; expression: string }[] = [];
|
|
379
|
-
let invocation: string, resultType: string;
|
|
380
|
-
if (fn) {
|
|
381
|
-
const node = fn.type;
|
|
382
|
-
if (!node || !ts.isTypeReferenceNode(node) || !node.typeArguments?.[0])
|
|
383
|
-
fail(fn, "Async calls need an explicit Promise<T> result.");
|
|
384
|
-
resultType = typeText(node.typeArguments[0], source);
|
|
385
|
-
fn.parameters.forEach((parameter, index) => {
|
|
386
|
-
if (!parameter.type || !root.arguments[index])
|
|
387
|
-
fail(root, "Async argument count differs from its concrete signature.");
|
|
388
|
-
arguments_.push({
|
|
389
|
-
name: `argument${index}`,
|
|
390
|
-
type: typeText(parameter.type, source),
|
|
391
|
-
expression: root.arguments[index]!.getText(source),
|
|
392
|
-
});
|
|
393
|
-
});
|
|
394
|
-
invocation = `${root.expression.getText(source)}(${arguments_.map((value) => value.name).join(",")})`;
|
|
395
|
-
} else if (isSdk(root, "sleep")) {
|
|
396
|
-
if (root.arguments.length !== 1) fail(root, "sleep requires one TIME argument.");
|
|
397
|
-
arguments_.push({
|
|
398
|
-
name: "argument0",
|
|
399
|
-
type: "TIME",
|
|
400
|
-
expression: root.arguments[0]!.getText(source),
|
|
401
|
-
});
|
|
402
|
-
invocation = `${root.expression.getText(source)}(argument0)`;
|
|
403
|
-
resultType = "void";
|
|
404
|
-
} else {
|
|
405
|
-
const response = root.typeArguments?.[0];
|
|
406
|
-
if (!response) fail(root, "fetch requires a typed response.");
|
|
407
|
-
resultType = typeText(response, source);
|
|
408
|
-
const options = root.arguments[1];
|
|
409
|
-
if (options && !ts.isObjectLiteralExpression(options))
|
|
410
|
-
fail(options, "fetch options must be an inline object.");
|
|
411
|
-
let optionText = "";
|
|
412
|
-
if (options && ts.isObjectLiteralExpression(options))
|
|
413
|
-
optionText = options.properties
|
|
414
|
-
.map((property) => {
|
|
415
|
-
if (!ts.isPropertyAssignment(property)) fail(property, "fetch requires named options.");
|
|
416
|
-
if (property.name.getText(source) !== "json") return property.getText(source);
|
|
417
|
-
arguments_.push({
|
|
418
|
-
name: "argument0",
|
|
419
|
-
type: expressionType(property.initializer, source),
|
|
420
|
-
expression: property.initializer.getText(source),
|
|
421
|
-
});
|
|
422
|
-
return "json:argument0";
|
|
423
|
-
})
|
|
424
|
-
.join(",");
|
|
425
|
-
invocation = `${root.expression.getText(source)}<${root.typeArguments!.map((type) => type.getText(source)).join(",")}>(${root.arguments[0]!.getText(source)}${options ? `,{${optionText}}` : ""})`;
|
|
426
|
-
}
|
|
427
|
-
const params = [
|
|
428
|
-
...arguments_,
|
|
429
|
-
...[...captures.values()].map((value) => ({
|
|
430
|
-
name: value.name,
|
|
431
|
-
type: value.type,
|
|
432
|
-
expression: value.argument,
|
|
433
|
-
})),
|
|
434
|
-
];
|
|
435
|
-
const signature = params.map((value) => `${value.name}:${value.type}`).join(","),
|
|
436
|
-
args = params.map((value) => value.name).join(",");
|
|
437
|
-
const addHelper = (
|
|
438
|
-
name: string,
|
|
439
|
-
body: string,
|
|
440
|
-
type: string,
|
|
441
|
-
extra?: { type: string; argument: string },
|
|
442
|
-
) => {
|
|
443
|
-
const text = `${classOwner ? "private " : "export "}async ${classOwner ? "" : "function "}${name}(${[signature, extra ? `promiseInput:${extra.type}` : ""].filter(Boolean).join(",")}):Promise<${type}>{${body}}`;
|
|
444
|
-
append(classOwner ?? source, expression, text);
|
|
445
|
-
return `${classOwner ? "this." : ""}${name}(${[args, extra?.argument ?? ""].filter(Boolean).join(",")})`;
|
|
446
|
-
};
|
|
447
|
-
const finish = (call: string, type: string, discard = false) =>
|
|
448
|
-
type === "void" || discard ? `await ${call};return;` : `return await ${call};`;
|
|
449
|
-
let prefix = addHelper(
|
|
450
|
-
`tsplcPromiseOperation${sequence++}`,
|
|
451
|
-
finish(invocation, resultType),
|
|
452
|
-
resultType,
|
|
453
|
-
);
|
|
454
|
-
const handler = (
|
|
455
|
-
expression: ts.Expression | undefined,
|
|
456
|
-
inputType: string,
|
|
457
|
-
input: string,
|
|
458
|
-
): { call: string; type: string; aggregate: boolean } | undefined => {
|
|
459
|
-
if (
|
|
460
|
-
!expression ||
|
|
461
|
-
expression.kind === ts.SyntaxKind.NullKeyword ||
|
|
462
|
-
(ts.isIdentifier(expression) && expression.text === "undefined")
|
|
463
|
-
)
|
|
464
|
-
return;
|
|
465
|
-
let declaration: Handler;
|
|
466
|
-
if (ts.isArrowFunction(expression) || ts.isFunctionExpression(expression))
|
|
467
|
-
declaration = expression;
|
|
468
|
-
else {
|
|
469
|
-
const named = routines.get(symbol(expression)!);
|
|
470
|
-
if (!named || !ts.isFunctionDeclaration(named))
|
|
471
|
-
fail(
|
|
472
|
-
expression,
|
|
473
|
-
"Use a named function or inline arrow; bind instance methods with an arrow.",
|
|
474
|
-
);
|
|
475
|
-
declaration = named;
|
|
476
|
-
}
|
|
477
|
-
const callbackSignature = checker.getSignatureFromDeclaration(declaration);
|
|
478
|
-
const aggregate = isAggregate(
|
|
479
|
-
callbackSignature &&
|
|
480
|
-
checker.getAwaitedType(checker.getReturnTypeOfSignature(callbackSignature)),
|
|
481
|
-
);
|
|
482
|
-
if (!declaration.body || declaration.parameters.length > 1)
|
|
483
|
-
fail(declaration, "Promise callbacks take at most one value.");
|
|
484
|
-
if (declaration.getSourceFile() !== source) {
|
|
485
|
-
const result = declaration.type;
|
|
486
|
-
if (!result) fail(declaration, "Annotate callback results with their concrete PLC type.");
|
|
487
|
-
let output = result;
|
|
488
|
-
if (
|
|
489
|
-
ts.isTypeReferenceNode(result) &&
|
|
490
|
-
result.typeName.getText(declaration.getSourceFile()) === "Promise"
|
|
491
|
-
)
|
|
492
|
-
output = result.typeArguments![0]!;
|
|
493
|
-
// Named callbacks retain their original module and access to its private state.
|
|
494
|
-
const callbackType = typeText(output, source);
|
|
495
|
-
const name = expression.getText(source);
|
|
496
|
-
if (declaration.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword))
|
|
497
|
-
return {
|
|
498
|
-
call: `${name}(${declaration.parameters.length ? input : ""})`,
|
|
499
|
-
type: callbackType,
|
|
500
|
-
aggregate,
|
|
501
|
-
};
|
|
502
|
-
return {
|
|
503
|
-
call: addHelper(
|
|
504
|
-
`tsplcPromiseNamed${sequence++}`,
|
|
505
|
-
callbackType === "void"
|
|
506
|
-
? `${name}(${declaration.parameters.length ? "promiseInput" : ""});return;`
|
|
507
|
-
: `return ${name}(${declaration.parameters.length ? "promiseInput" : ""});`,
|
|
508
|
-
callbackType,
|
|
509
|
-
declaration.parameters.length ? { type: inputType, argument: input } : undefined,
|
|
510
|
-
),
|
|
511
|
-
type: callbackType,
|
|
512
|
-
aggregate,
|
|
513
|
-
};
|
|
514
|
-
}
|
|
515
|
-
const names = new Map(captureNames);
|
|
516
|
-
const parameter = declaration.parameters[0];
|
|
517
|
-
if (parameter) {
|
|
518
|
-
if (!ts.isIdentifier(parameter.name))
|
|
519
|
-
fail(parameter, "Promise callback parameters need names.");
|
|
520
|
-
names.set(symbol(parameter.name)!, "promiseValue");
|
|
521
|
-
}
|
|
522
|
-
let type: string;
|
|
523
|
-
if (declaration.type) {
|
|
524
|
-
const annotation = declaration.type;
|
|
525
|
-
type =
|
|
526
|
-
ts.isTypeReferenceNode(annotation) && annotation.typeName.getText(source) === "Promise"
|
|
527
|
-
? typeText(annotation.typeArguments![0]!, source)
|
|
528
|
-
: typeText(annotation, source);
|
|
529
|
-
} else {
|
|
530
|
-
const resolved = checker.getSignatureFromDeclaration(declaration);
|
|
531
|
-
const inferred =
|
|
532
|
-
resolved && checker.getAwaitedType(checker.getReturnTypeOfSignature(resolved));
|
|
533
|
-
if (inferred?.flags && inferred.flags & ts.TypeFlags.Void) type = "void";
|
|
534
|
-
else if (
|
|
535
|
-
!ts.isBlock(declaration.body) &&
|
|
536
|
-
ts.isIdentifier(declaration.body) &&
|
|
537
|
-
parameter &&
|
|
538
|
-
symbol(declaration.body) === symbol(parameter.name)
|
|
539
|
-
)
|
|
540
|
-
type = inputType;
|
|
541
|
-
else if (!ts.isBlock(declaration.body)) {
|
|
542
|
-
const returned = ts.isCallExpression(declaration.body)
|
|
543
|
-
? operation(declaration.body)
|
|
544
|
-
: undefined;
|
|
545
|
-
type =
|
|
546
|
-
returned?.type && ts.isTypeReferenceNode(returned.type)
|
|
547
|
-
? typeText(returned.type.typeArguments![0]!, source)
|
|
548
|
-
: expressionType(declaration.body, source);
|
|
549
|
-
} else
|
|
550
|
-
fail(declaration, "Annotate a callback that returns a value with its concrete PLC type.");
|
|
551
|
-
}
|
|
552
|
-
const name = `tsplcPromiseHandler${sequence++}`;
|
|
553
|
-
const body = replaceNames(declaration.body, names);
|
|
554
|
-
const code = ts.isBlock(declaration.body)
|
|
555
|
-
? body.slice(1, -1)
|
|
556
|
-
: type === "void"
|
|
557
|
-
? `${body};return;`
|
|
558
|
-
: `return ${isPromise(declaration.body) ? "await " : ""}${body};`;
|
|
559
|
-
const handlerParams = [
|
|
560
|
-
...(parameter && inputType !== "void" ? [`promiseValue:${inputType}`] : []),
|
|
561
|
-
...params.map((value) => `${value.name}:${value.type}`),
|
|
562
|
-
].join(",");
|
|
563
|
-
const text = `${classOwner ? "private " : "export "}async ${classOwner ? "" : "function "}${name}(${handlerParams}):Promise<${type}>{${code}}`;
|
|
564
|
-
append(classOwner ?? source, declaration, text);
|
|
565
|
-
return {
|
|
566
|
-
call: `${classOwner ? "this." : ""}${name}(${[...(parameter && inputType !== "void" ? [input] : []), ...params.map((value) => value.name)].join(",")})`,
|
|
567
|
-
type,
|
|
568
|
-
aggregate,
|
|
569
|
-
};
|
|
570
|
-
};
|
|
571
|
-
for (const [index, part] of parsed.parts.entries()) {
|
|
572
|
-
const terminal = detached && index === parsed.parts.length - 1;
|
|
573
|
-
const fulfilled =
|
|
574
|
-
part.kind === "then" ? handler(part.handlers[0], resultType, "promiseResult") : undefined;
|
|
575
|
-
const rejected = handler(
|
|
576
|
-
part.handlers[part.kind === "catch" ? 0 : 1],
|
|
577
|
-
"UDINT",
|
|
578
|
-
"tsplcErrorCode(promiseError)",
|
|
579
|
-
);
|
|
580
|
-
if (!fulfilled && !rejected) continue;
|
|
581
|
-
const output = terminal ? "void" : (fulfilled?.type ?? resultType);
|
|
582
|
-
if (rejected && !terminal && rejected.type !== output)
|
|
583
|
-
fail(
|
|
584
|
-
expression,
|
|
585
|
-
"A recovery callback must return the same PLC type as the fulfilled branch.",
|
|
586
|
-
);
|
|
587
|
-
const success = fulfilled
|
|
588
|
-
? finish(fulfilled.call, fulfilled.type, terminal)
|
|
589
|
-
: resultType === "void" || terminal
|
|
590
|
-
? "return;"
|
|
591
|
-
: "return promiseResult;";
|
|
592
|
-
const load =
|
|
593
|
-
resultType === "void"
|
|
594
|
-
? `await ${prefix};`
|
|
595
|
-
: `const promiseResult:${resultType}=await ${prefix};`;
|
|
596
|
-
let body: string;
|
|
597
|
-
if (rejected && fulfilled) {
|
|
598
|
-
const stored =
|
|
599
|
-
resultType === "void"
|
|
600
|
-
? ""
|
|
601
|
-
: `let promiseResult:${resultType}=defaultValue<${resultType}>();`;
|
|
602
|
-
const attempt =
|
|
603
|
-
resultType === "void"
|
|
604
|
-
? `await ${prefix};`
|
|
605
|
-
: `const loaded:${resultType}=await ${prefix};promiseResult=${resultAggregate ? "copy(loaded)" : "loaded"};`;
|
|
606
|
-
body = `${stored}let succeeded:BOOL=false;let rejection:UDINT=0;try{${attempt}succeeded=true;}catch(promiseError){rejection=tsplcErrorCode(promiseError);}if(!succeeded){${finish(rejected.call.replace("tsplcErrorCode(promiseError)", "rejection"), rejected.type, terminal)}}${success}`;
|
|
607
|
-
} else if (rejected)
|
|
608
|
-
body = `try{${load}${success}}catch(promiseError){${finish(rejected.call, rejected.type, terminal)}}`;
|
|
609
|
-
else body = `${load}${success}`;
|
|
610
|
-
prefix = addHelper(`tsplcPromiseChain${sequence++}`, body, output);
|
|
611
|
-
resultType = output;
|
|
612
|
-
resultAggregate = terminal ? false : (fulfilled?.aggregate ?? resultAggregate);
|
|
613
|
-
}
|
|
614
|
-
if (!detached)
|
|
615
|
-
return prefix.replace(`(${args})`, `(${params.map((value) => value.expression).join(",")})`);
|
|
616
|
-
const site = `tsplcPromiseSite${sequence++}`;
|
|
617
|
-
const callable = prefix.slice(0, prefix.indexOf("("));
|
|
618
|
-
const declaration = `${classOwner ? "private " : "const "}${site}=tsplcCooperative.define(${callable});`;
|
|
619
|
-
append(classOwner ?? source, expression, declaration);
|
|
620
|
-
const scope = classOwner ?? source;
|
|
621
|
-
scopes.set(scope, [...(scopes.get(scope) ?? []), site]);
|
|
622
|
-
return `${classOwner ? "this." : ""}${site}.start(${params.map((value) => value.expression).join(",")});`;
|
|
623
|
-
};
|
|
624
|
-
const diagnosticsCalls: ts.CallExpression[] = [],
|
|
625
|
-
cancelCalls: {
|
|
626
|
-
node: ts.CallExpression;
|
|
627
|
-
owner: ts.FunctionDeclaration | ts.MethodDeclaration;
|
|
628
|
-
}[] = [];
|
|
629
|
-
for (const source of files) {
|
|
630
|
-
const visit = (node: ts.Node, owner?: ts.FunctionDeclaration | ts.MethodDeclaration): void => {
|
|
631
|
-
if (ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node)) {
|
|
632
|
-
if (node.body) ts.forEachChild(node.body, (child) => visit(child, node));
|
|
633
|
-
return;
|
|
634
|
-
}
|
|
635
|
-
if (!owner) {
|
|
636
|
-
ts.forEachChild(node, (child) => visit(child));
|
|
637
|
-
return;
|
|
638
|
-
}
|
|
639
|
-
if (ts.isCallExpression(node) && official(node.expression, "asyncDiagnostics")) {
|
|
640
|
-
diagnosticOwner ??= node;
|
|
641
|
-
diagnosticsCalls.push(node);
|
|
642
|
-
return;
|
|
643
|
-
}
|
|
644
|
-
if (ts.isCallExpression(node) && official(node.expression, "cancelAsync")) {
|
|
645
|
-
cancelCalls.push({ node, owner });
|
|
646
|
-
return;
|
|
647
|
-
}
|
|
648
|
-
const asynchronous = owner.modifiers?.some(
|
|
649
|
-
(modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword,
|
|
650
|
-
);
|
|
651
|
-
if (ts.isExpressionStatement(node)) {
|
|
652
|
-
const expression = ts.isVoidExpression(node.expression)
|
|
653
|
-
? node.expression.expression
|
|
654
|
-
: node.expression;
|
|
655
|
-
if (split(expression)) {
|
|
656
|
-
if (asynchronous) {
|
|
657
|
-
diagnostics.push(
|
|
658
|
-
diagnosticFor(
|
|
659
|
-
node,
|
|
660
|
-
"Await async work inside an async routine; detached calls belong in synchronous controllers.",
|
|
661
|
-
),
|
|
662
|
-
);
|
|
663
|
-
return;
|
|
664
|
-
}
|
|
665
|
-
try {
|
|
666
|
-
edit(node, make(expression, owner, true));
|
|
667
|
-
} catch (cause) {
|
|
668
|
-
if (typeof cause === "object" && cause !== null && "promiseDiagnostic" in cause)
|
|
669
|
-
diagnostics.push(cause.promiseDiagnostic as Diagnostic);
|
|
670
|
-
else throw cause;
|
|
671
|
-
}
|
|
672
|
-
return;
|
|
673
|
-
}
|
|
674
|
-
}
|
|
675
|
-
if (ts.isCallExpression(node)) {
|
|
676
|
-
const chain = split(node);
|
|
677
|
-
if (chain?.parts.length) {
|
|
678
|
-
try {
|
|
679
|
-
edit(node, make(node, owner, false));
|
|
680
|
-
} catch (cause) {
|
|
681
|
-
if (typeof cause === "object" && cause !== null && "promiseDiagnostic" in cause)
|
|
682
|
-
diagnostics.push(cause.promiseDiagnostic as Diagnostic);
|
|
683
|
-
else throw cause;
|
|
684
|
-
}
|
|
685
|
-
return;
|
|
686
|
-
}
|
|
687
|
-
}
|
|
688
|
-
ts.forEachChild(node, (child) => visit(child, owner));
|
|
689
|
-
};
|
|
690
|
-
visit(source);
|
|
691
|
-
}
|
|
692
|
-
for (const { node, owner } of cancelCalls) {
|
|
693
|
-
const scope =
|
|
694
|
-
ts.isMethodDeclaration(owner) && ts.isClassDeclaration(owner.parent)
|
|
695
|
-
? owner.parent
|
|
696
|
-
: owner.getSourceFile();
|
|
697
|
-
if (
|
|
698
|
-
node.arguments.length &&
|
|
699
|
-
(node.arguments.length !== 1 || node.arguments[0]!.kind !== ts.SyntaxKind.ThisKeyword)
|
|
700
|
-
)
|
|
701
|
-
diagnostics.push(
|
|
702
|
-
diagnosticFor(node, "cancelAsync takes this in a controller, or no argument in a module."),
|
|
703
|
-
);
|
|
704
|
-
const name = `tsplcCancelScope${sequence++}`;
|
|
705
|
-
const body = (scopes.get(scope) ?? [])
|
|
706
|
-
.map((site) => `${ts.isClassDeclaration(scope) ? "this." : ""}${site}.cancel();`)
|
|
707
|
-
.join("");
|
|
708
|
-
append(
|
|
709
|
-
scope,
|
|
710
|
-
node,
|
|
711
|
-
ts.isClassDeclaration(scope)
|
|
712
|
-
? `private ${name}():void{${body}}`
|
|
713
|
-
: `function ${name}():void{${body}}`,
|
|
714
|
-
);
|
|
715
|
-
edit(node, `${ts.isClassDeclaration(scope) ? "this." : ""}${name}()`);
|
|
716
|
-
}
|
|
717
|
-
if (diagnosticOwner) {
|
|
718
|
-
const source = diagnosticOwner.getSourceFile();
|
|
719
|
-
ensureImports(source, diagnosticOwner);
|
|
720
|
-
append(
|
|
721
|
-
source,
|
|
722
|
-
diagnosticOwner,
|
|
723
|
-
`export class TsplcPromiseDiagnostics extends FunctionBlock<{}>{private count:UDINT=0;private lastError:UDINT=0;public report(code:UDINT,count:UDINT):BOOL{this.count=tsplcAsyncWrapAdd<UDINT>(this.count,count);this.lastError=code;return true;}public snapshot():{valid:BOOL;count:UDINT;lastError:UDINT}{return {valid:true,count:this.count,lastError:this.lastError};}protected execute(input:{}):void{}}
|
|
724
|
-
export const tsplcPromiseDiagnostics=new TsplcPromiseDiagnostics();`,
|
|
725
|
-
);
|
|
726
|
-
runtimeBlocks.set(`${source.fileName}:TsplcPromiseDiagnostics`, { kind: "mailbox" });
|
|
727
|
-
for (const file of new Set([
|
|
728
|
-
...additions.keys(),
|
|
729
|
-
...diagnosticsCalls.map((node) => node.getSourceFile()),
|
|
730
|
-
])) {
|
|
731
|
-
if (file !== source) {
|
|
732
|
-
const path = relative(dirname(file.fileName), source.fileName).replaceAll("\\", "/");
|
|
733
|
-
append(
|
|
734
|
-
file,
|
|
735
|
-
file,
|
|
736
|
-
`import {${diag()}} from ${JSON.stringify(path.startsWith(".") ? path : `./${path}`)};`,
|
|
737
|
-
);
|
|
738
|
-
}
|
|
739
|
-
}
|
|
740
|
-
for (const call of diagnosticsCalls) edit(call, `${diag()}.snapshot()`);
|
|
741
|
-
}
|
|
742
|
-
for (const [owner, texts] of methods) {
|
|
743
|
-
const source = owner.getSourceFile();
|
|
744
|
-
edits.set(source, [
|
|
745
|
-
...(edits.get(source) ?? []),
|
|
746
|
-
{ start: owner.end - 1, end: owner.end - 1, text: mapped`\n${joined(texts, "\n")}` },
|
|
747
|
-
]);
|
|
748
|
-
}
|
|
749
|
-
for (const source of files) {
|
|
750
|
-
const changes = edits.get(source) ?? [],
|
|
751
|
-
extra = additions.get(source) ?? [];
|
|
752
|
-
if (!changes.length && !extra.length) continue;
|
|
753
|
-
sources.set(source.fileName, mapped`${edited(source, changes)}\n${joined(extra, "\n")}`);
|
|
754
|
-
}
|
|
755
|
-
return { sources, diagnostics, runtimeBlocks };
|
|
56
|
+
export const lowerPromises = (
|
|
57
|
+
program: ts.Program,
|
|
58
|
+
sdk: string,
|
|
59
|
+
positions: Positions,
|
|
60
|
+
): PromiseLowering => {
|
|
61
|
+
const files = runtimeSources(program).filter(
|
|
62
|
+
(source) => !source.isDeclarationFile,
|
|
63
|
+
);
|
|
64
|
+
const rewrite = new PromiseRewrite(
|
|
65
|
+
program.getTypeChecker(),
|
|
66
|
+
sdk,
|
|
67
|
+
positions,
|
|
68
|
+
files,
|
|
69
|
+
);
|
|
70
|
+
const diagnostics: Diagnostic[] = [];
|
|
71
|
+
const runtimeBlocks = new Map<string, { kind: "mailbox" }>();
|
|
72
|
+
const { diagnosticsCalls, cancelCalls } = rewriteChains(
|
|
73
|
+
rewrite,
|
|
74
|
+
files,
|
|
75
|
+
diagnostics,
|
|
76
|
+
);
|
|
77
|
+
for (const { node, owner } of cancelCalls) {
|
|
78
|
+
cancelScope(rewrite, node, owner, diagnostics);
|
|
79
|
+
}
|
|
80
|
+
const owner = rewrite.diagnosticsOwner;
|
|
81
|
+
if (owner) {
|
|
82
|
+
const source = owner.getSourceFile();
|
|
83
|
+
rewrite.ensureImports(source, owner);
|
|
84
|
+
rewrite.append(
|
|
85
|
+
source,
|
|
86
|
+
owner,
|
|
87
|
+
`export class TsplcPromiseDiagnostics extends FunctionBlock<{}>{private count:UDINT=0;private lastError:UDINT=0;public report(code:UDINT,count:UDINT):BOOL{this.count=tsplcAsyncWrapAdd<UDINT>(this.count,count);this.lastError=code;return true;}public snapshot():{valid:BOOL;count:UDINT;lastError:UDINT}{return {valid:true,count:this.count,lastError:this.lastError};}protected execute(input:{}):void{}}
|
|
88
|
+
export const ${diagnosticsInstance}=new TsplcPromiseDiagnostics();`,
|
|
89
|
+
);
|
|
90
|
+
runtimeBlocks.set(`${source.fileName}:TsplcPromiseDiagnostics`, {
|
|
91
|
+
kind: "mailbox",
|
|
92
|
+
});
|
|
93
|
+
for (const file of new Set([
|
|
94
|
+
...rewrite.extendedFiles(),
|
|
95
|
+
...diagnosticsCalls.map((node) => node.getSourceFile()),
|
|
96
|
+
])) {
|
|
97
|
+
if (file !== source) {
|
|
98
|
+
rewrite.append(
|
|
99
|
+
file,
|
|
100
|
+
file,
|
|
101
|
+
`import {${diagnosticsInstance}} from ${importSpecifier(file.fileName, source.fileName)};`,
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
for (const call of diagnosticsCalls) {
|
|
106
|
+
rewrite.edit(call, `${diagnosticsInstance}.snapshot()`);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return { sources: rewrite.sources(files), diagnostics, runtimeBlocks };
|
|
756
110
|
};
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Replaces each promise chain in a routine: a detached statement becomes a cooperative site,
|
|
114
|
+
* and a chain used as a value becomes a call to its last helper. Collects the
|
|
115
|
+
* `asyncDiagnostics()` and `cancelAsync()` calls it passes.
|
|
116
|
+
*/
|
|
117
|
+
function rewriteChains(
|
|
118
|
+
rewrite: PromiseRewrite,
|
|
119
|
+
files: readonly ts.SourceFile[],
|
|
120
|
+
diagnostics: Diagnostic[],
|
|
121
|
+
) {
|
|
122
|
+
const diagnosticsCalls: ts.CallExpression[] = [];
|
|
123
|
+
const cancelCalls: { node: ts.CallExpression; owner: Routine }[] = [];
|
|
124
|
+
const lower = (
|
|
125
|
+
node: ts.Node,
|
|
126
|
+
expression: ts.Expression,
|
|
127
|
+
owner: Routine,
|
|
128
|
+
{ detached }: { detached: boolean },
|
|
129
|
+
) => {
|
|
130
|
+
try {
|
|
131
|
+
rewrite.edit(node, lowerChain(rewrite, expression, owner, detached));
|
|
132
|
+
} catch (cause) {
|
|
133
|
+
if (!(cause instanceof SemanticError)) {
|
|
134
|
+
throw cause;
|
|
135
|
+
}
|
|
136
|
+
diagnostics.push(cause.diagnostic);
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
for (const source of files) {
|
|
140
|
+
const visit = (node: ts.Node, owner?: Routine): void => {
|
|
141
|
+
if (ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node)) {
|
|
142
|
+
if (node.body) {
|
|
143
|
+
ts.forEachChild(node.body, (child) => visit(child, node));
|
|
144
|
+
}
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
if (!owner) {
|
|
148
|
+
ts.forEachChild(node, (child) => visit(child));
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
if (
|
|
152
|
+
ts.isCallExpression(node) &&
|
|
153
|
+
rewrite.namesSdk(node.expression, "asyncDiagnostics")
|
|
154
|
+
) {
|
|
155
|
+
rewrite.useDiagnostics(node);
|
|
156
|
+
diagnosticsCalls.push(node);
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
if (
|
|
160
|
+
ts.isCallExpression(node) &&
|
|
161
|
+
rewrite.namesSdk(node.expression, "cancelAsync")
|
|
162
|
+
) {
|
|
163
|
+
cancelCalls.push({ node, owner });
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
if (ts.isExpressionStatement(node)) {
|
|
167
|
+
const expression = ts.isVoidExpression(node.expression)
|
|
168
|
+
? node.expression.expression
|
|
169
|
+
: node.expression;
|
|
170
|
+
if (chainOf(rewrite, expression)) {
|
|
171
|
+
if (hasModifier(owner, ts.SyntaxKind.AsyncKeyword)) {
|
|
172
|
+
diagnostics.push(
|
|
173
|
+
rewrite.diagnostic(
|
|
174
|
+
node,
|
|
175
|
+
"Await async work inside an async routine; detached calls belong in synchronous controllers.",
|
|
176
|
+
),
|
|
177
|
+
);
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
lower(node, expression, owner, { detached: true });
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
if (ts.isCallExpression(node) && chainOf(rewrite, node)?.links.length) {
|
|
185
|
+
lower(node, node, owner, { detached: false });
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
ts.forEachChild(node, (child) => visit(child, owner));
|
|
189
|
+
};
|
|
190
|
+
visit(source);
|
|
191
|
+
}
|
|
192
|
+
return { diagnosticsCalls, cancelCalls };
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** `cancelAsync()` cancels every detached chain of the module, or `cancelAsync(this)` of the block. */
|
|
196
|
+
function cancelScope(
|
|
197
|
+
rewrite: PromiseRewrite,
|
|
198
|
+
node: ts.CallExpression,
|
|
199
|
+
owner: Routine,
|
|
200
|
+
diagnostics: Diagnostic[],
|
|
201
|
+
): void {
|
|
202
|
+
const scope =
|
|
203
|
+
ts.isMethodDeclaration(owner) && ts.isClassDeclaration(owner.parent)
|
|
204
|
+
? owner.parent
|
|
205
|
+
: owner.getSourceFile();
|
|
206
|
+
if (
|
|
207
|
+
node.arguments.length &&
|
|
208
|
+
(node.arguments.length !== 1 ||
|
|
209
|
+
node.arguments[0]!.kind !== ts.SyntaxKind.ThisKeyword)
|
|
210
|
+
) {
|
|
211
|
+
diagnostics.push(
|
|
212
|
+
rewrite.diagnostic(
|
|
213
|
+
node,
|
|
214
|
+
"cancelAsync takes this in a controller, or no argument in a module.",
|
|
215
|
+
),
|
|
216
|
+
);
|
|
217
|
+
}
|
|
218
|
+
const name = `tsplcCancelScope${rewrite.sequence()}`;
|
|
219
|
+
const member = ts.isClassDeclaration(scope);
|
|
220
|
+
const body = (rewrite.sites.get(scope) ?? [])
|
|
221
|
+
.map((site) => `${member ? "this." : ""}${site}.cancel();`)
|
|
222
|
+
.join("");
|
|
223
|
+
rewrite.append(
|
|
224
|
+
scope,
|
|
225
|
+
node,
|
|
226
|
+
member
|
|
227
|
+
? `private ${name}():void{${body}}`
|
|
228
|
+
: `function ${name}():void{${body}}`,
|
|
229
|
+
);
|
|
230
|
+
rewrite.edit(node, `${member ? "this." : ""}${name}()`);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** The edits and generated code promise lowering makes across the program. */
|
|
234
|
+
class PromiseRewrite implements PromiseContext {
|
|
235
|
+
readonly routines = new Map<ts.Symbol, Routine>();
|
|
236
|
+
readonly sites = new Map<ts.SourceFile | ts.ClassDeclaration, string[]>();
|
|
237
|
+
/** The first node that needs the shared diagnostics block, which its module declares. */
|
|
238
|
+
diagnosticsOwner: ts.Node | undefined;
|
|
239
|
+
private readonly additions = new Map<ts.SourceFile, Mapped[]>();
|
|
240
|
+
private readonly edits = new Map<ts.SourceFile, Edit[]>();
|
|
241
|
+
private readonly members = new Map<ts.ClassDeclaration, Mapped[]>();
|
|
242
|
+
private readonly aliases = new Map<ts.Node, string>();
|
|
243
|
+
private readonly typeImports = new Map<ts.SourceFile, Set<string>>();
|
|
244
|
+
private readonly imported = new Set<ts.SourceFile>();
|
|
245
|
+
private nextName = 0;
|
|
246
|
+
|
|
247
|
+
constructor(
|
|
248
|
+
readonly checker: ts.TypeChecker,
|
|
249
|
+
private readonly sdk: string,
|
|
250
|
+
private readonly positions: Positions,
|
|
251
|
+
files: readonly ts.SourceFile[],
|
|
252
|
+
) {
|
|
253
|
+
for (const source of files) {
|
|
254
|
+
for (const statement of source.statements) {
|
|
255
|
+
const candidates = ts.isClassDeclaration(statement)
|
|
256
|
+
? statement.members.filter(ts.isMethodDeclaration)
|
|
257
|
+
: [statement];
|
|
258
|
+
for (const candidate of candidates) {
|
|
259
|
+
if (
|
|
260
|
+
(ts.isFunctionDeclaration(candidate) ||
|
|
261
|
+
ts.isMethodDeclaration(candidate)) &&
|
|
262
|
+
candidate.name
|
|
263
|
+
) {
|
|
264
|
+
this.routines.set(this.symbol(candidate.name)!, candidate);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
symbol(node: ts.Node): ts.Symbol | undefined {
|
|
272
|
+
return symbolAt(this.checker, node);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
namesSdk(node: ts.Node, name: string): boolean {
|
|
276
|
+
return namesSdk(this.checker, this.sdk, node, name);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
diagnostic(node: ts.Node, message: string): Diagnostic {
|
|
280
|
+
return error("PLC1012", message, this.positions.node(node));
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
fail(node: ts.Node, message: string): never {
|
|
284
|
+
throw new SemanticError(this.diagnostic(node, message));
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
sequence(): number {
|
|
288
|
+
return this.nextName++;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
append(
|
|
292
|
+
scope: ts.SourceFile | ts.ClassDeclaration,
|
|
293
|
+
origin: ts.Node,
|
|
294
|
+
text: string,
|
|
295
|
+
): void {
|
|
296
|
+
if (ts.isClassDeclaration(scope)) {
|
|
297
|
+
this.members.set(scope, [
|
|
298
|
+
...(this.members.get(scope) ?? []),
|
|
299
|
+
from(origin, text),
|
|
300
|
+
]);
|
|
301
|
+
} else {
|
|
302
|
+
this.additions.set(scope, [
|
|
303
|
+
...(this.additions.get(scope) ?? []),
|
|
304
|
+
from(origin, text),
|
|
305
|
+
]);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
edit(node: ts.Node, text: string): void {
|
|
310
|
+
const source = node.getSourceFile();
|
|
311
|
+
this.edits.set(source, [
|
|
312
|
+
...(this.edits.get(source) ?? []),
|
|
313
|
+
{ start: node.getStart(source), end: node.end, text },
|
|
314
|
+
]);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** The modules generated code has been added to so far. */
|
|
318
|
+
extendedFiles(): Iterable<ts.SourceFile> {
|
|
319
|
+
return this.additions.keys();
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
typeText(node: ts.TypeNode, source: ts.SourceFile): string {
|
|
323
|
+
if (node.kind === ts.SyntaxKind.VoidKeyword) {
|
|
324
|
+
return "void";
|
|
325
|
+
}
|
|
326
|
+
if (node.getSourceFile() === source) {
|
|
327
|
+
return node.getText(source);
|
|
328
|
+
}
|
|
329
|
+
const alias = this.aliases.get(node) ?? this.declareAlias(node);
|
|
330
|
+
const importedAliases = this.typeImports.get(source) ?? new Set<string>();
|
|
331
|
+
if (importedAliases.has(alias)) {
|
|
332
|
+
return alias;
|
|
333
|
+
}
|
|
334
|
+
importedAliases.add(alias);
|
|
335
|
+
this.typeImports.set(source, importedAliases);
|
|
336
|
+
this.append(
|
|
337
|
+
source,
|
|
338
|
+
node,
|
|
339
|
+
`import type {${alias}} from ${importSpecifier(source.fileName, node.getSourceFile().fileName)};`,
|
|
340
|
+
);
|
|
341
|
+
return alias;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/** Exports a type from the module that declares it, so other modules can name it. */
|
|
345
|
+
private declareAlias(node: ts.TypeNode): string {
|
|
346
|
+
const alias = `TsplcPromiseType${this.sequence()}`;
|
|
347
|
+
this.aliases.set(node, alias);
|
|
348
|
+
this.append(
|
|
349
|
+
node.getSourceFile(),
|
|
350
|
+
node,
|
|
351
|
+
`export type ${alias}=${node.getText(node.getSourceFile())};`,
|
|
352
|
+
);
|
|
353
|
+
return alias;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
ensureImports(source: ts.SourceFile, origin: ts.Node): void {
|
|
357
|
+
if (this.imported.has(source)) {
|
|
358
|
+
return;
|
|
359
|
+
}
|
|
360
|
+
this.imported.add(source);
|
|
361
|
+
this.append(
|
|
362
|
+
source,
|
|
363
|
+
origin,
|
|
364
|
+
`import {cooperativeTasks as tsplcCooperative,errorCode as tsplcErrorCode} from "@tsplc/compiler/async";import {wrapAdd as tsplcAsyncWrapAdd} from "@tsplc/compiler/types";`,
|
|
365
|
+
);
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
useDiagnostics(node: ts.Node): void {
|
|
369
|
+
this.diagnosticsOwner ??= node;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/** Each changed module's text: its edits, class members appended in place, then its additions. */
|
|
373
|
+
sources(files: readonly ts.SourceFile[]): Map<string, Mapped> {
|
|
374
|
+
for (const [owner, texts] of this.members) {
|
|
375
|
+
const source = owner.getSourceFile();
|
|
376
|
+
this.edits.set(source, [
|
|
377
|
+
...(this.edits.get(source) ?? []),
|
|
378
|
+
{
|
|
379
|
+
start: owner.end - 1,
|
|
380
|
+
end: owner.end - 1,
|
|
381
|
+
text: mapped`\n${joined(texts, "\n")}`,
|
|
382
|
+
},
|
|
383
|
+
]);
|
|
384
|
+
}
|
|
385
|
+
const sources = new Map<string, Mapped>();
|
|
386
|
+
for (const source of files) {
|
|
387
|
+
const changes = this.edits.get(source) ?? [];
|
|
388
|
+
const extra = this.additions.get(source) ?? [];
|
|
389
|
+
if (!changes.length && !extra.length) {
|
|
390
|
+
continue;
|
|
391
|
+
}
|
|
392
|
+
sources.set(
|
|
393
|
+
source.fileName,
|
|
394
|
+
mapped`${edited(source, changes)}\n${joined(extra, "\n")}`,
|
|
395
|
+
);
|
|
396
|
+
}
|
|
397
|
+
return sources;
|
|
398
|
+
}
|
|
399
|
+
}
|