@tsplc/tmp-compiler 0.0.0-stage → 0.6.3
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/LICENSE +21 -0
- package/README.md +41 -2
- package/dist/cli.js +2325 -0
- package/dist/cli.js.map +26 -0
- package/dist/clock.js +11 -0
- package/dist/clock.js.map +11 -0
- package/dist/codesys.js +6563 -0
- package/dist/codesys.js.map +51 -0
- package/dist/collections.js +399 -0
- package/dist/collections.js.map +10 -0
- package/dist/index.js +16198 -0
- package/dist/index.js.map +62 -0
- package/dist/ir.js +3948 -0
- package/dist/ir.js.map +35 -0
- package/dist/retain.js +10 -0
- package/dist/retain.js.map +10 -0
- package/dist/signals.js +115 -0
- package/dist/signals.js.map +10 -0
- package/dist/telemetry.js +121 -0
- package/dist/telemetry.js.map +12 -0
- package/package.json +122 -4
- package/src/codesys/config.ts +50 -0
- package/src/codesys/debug.ts +655 -0
- package/src/codesys/emit.ts +185 -0
- package/src/codesys/endpoints.ts +111 -0
- package/src/codesys/engineering.ts +96 -0
- package/src/codesys/explain/expressions.ts +445 -0
- package/src/codesys/explain/flags.ts +134 -0
- package/src/codesys/explain/parameters.ts +53 -0
- package/src/codesys/explain/rows.ts +182 -0
- package/src/codesys/explain/tables.ts +79 -0
- package/src/codesys/explain/tasks.ts +68 -0
- package/src/codesys/explain/writes.ts +497 -0
- package/src/codesys/explain.ts +149 -0
- package/src/codesys/expressions.ts +100 -0
- package/src/codesys/global-lists.ts +284 -0
- package/src/codesys/global-names.ts +66 -0
- package/src/codesys/http.ts +1090 -0
- package/src/codesys/index.ts +13 -0
- package/src/codesys/instrumentation.ts +574 -0
- package/src/codesys/io-paths.ts +149 -0
- package/src/codesys/loops.ts +101 -0
- package/src/codesys/manifest.ts +684 -0
- package/src/codesys/names.ts +58 -0
- package/src/codesys/numeric.ts +516 -0
- package/src/codesys/plan.ts +688 -0
- package/src/codesys/programs.ts +138 -0
- package/src/codesys/publication.ts +99 -0
- package/src/codesys/required.ts +8 -0
- package/src/codesys/routines.ts +247 -0
- package/src/codesys/scan-clock.ts +103 -0
- package/src/codesys/scheduling.ts +96 -0
- package/src/codesys/service-channels.ts +24 -0
- package/src/codesys/sources.ts +118 -0
- package/src/codesys/st-files.ts +219 -0
- package/src/codesys/statements.ts +409 -0
- package/src/codesys/storage.ts +150 -0
- package/src/codesys/symbols.ts +240 -0
- package/src/codesys/task-access.ts +186 -0
- package/src/codesys/telemetry-settings.ts +19 -0
- package/src/codesys/telemetry.ts +852 -0
- package/src/codesys/types.ts +310 -0
- package/src/codesys/vendor.ts +113 -0
- package/src/frontend/analyzer.ts +779 -0
- package/src/frontend/async.ts +530 -0
- package/src/frontend/blocks.ts +578 -0
- package/src/frontend/configuration.ts +83 -0
- package/src/frontend/const-enums.ts +196 -0
- package/src/frontend/const-functions.ts +204 -0
- package/src/frontend/control-flow.ts +787 -0
- package/src/frontend/cooperative.ts +114 -0
- package/src/frontend/coroutines.ts +1344 -0
- package/src/frontend/dialect-names.ts +104 -0
- package/src/frontend/elaborate/array-searches.ts +224 -0
- package/src/frontend/elaborate/assignments.ts +343 -0
- package/src/frontend/elaborate/calls.ts +1342 -0
- package/src/frontend/elaborate/capture-protocol.ts +237 -0
- package/src/frontend/elaborate/capture.ts +388 -0
- package/src/frontend/elaborate/declarations.ts +124 -0
- package/src/frontend/elaborate/dialect.ts +473 -0
- package/src/frontend/elaborate/expressions.ts +2177 -0
- package/src/frontend/elaborate/filtered-arrays.ts +643 -0
- package/src/frontend/elaborate/frame.ts +145 -0
- package/src/frontend/elaborate/generics.ts +123 -0
- package/src/frontend/elaborate/graph.ts +141 -0
- package/src/frontend/elaborate/imports.ts +105 -0
- package/src/frontend/elaborate/index.ts +851 -0
- package/src/frontend/elaborate/initializers.ts +235 -0
- package/src/frontend/elaborate/iterators.ts +1541 -0
- package/src/frontend/elaborate/layouts.ts +1025 -0
- package/src/frontend/elaborate/model.ts +478 -0
- package/src/frontend/elaborate/names.ts +134 -0
- package/src/frontend/elaborate/reduce.ts +900 -0
- package/src/frontend/elaborate/references.ts +727 -0
- package/src/frontend/elaborate/retention.ts +284 -0
- package/src/frontend/elaborate/specialize.ts +1137 -0
- package/src/frontend/elaborate/statements.ts +1220 -0
- package/src/frontend/elaborate/storage.ts +836 -0
- package/src/frontend/elaborate/time-constructors.ts +34 -0
- package/src/frontend/elaborate/values.ts +200 -0
- package/src/frontend/elaborate/writes.ts +415 -0
- package/src/frontend/expressions.ts +1382 -0
- package/src/frontend/generated-names.ts +95 -0
- package/src/frontend/intrinsics.ts +382 -0
- package/src/frontend/lowering-key.ts +23 -0
- package/src/frontend/module-graph.ts +156 -0
- package/src/frontend/positions.ts +359 -0
- package/src/frontend/promise-chains.ts +872 -0
- package/src/frontend/promises.ts +419 -0
- package/src/frontend/routines.ts +239 -0
- package/src/frontend/sdk.ts +187 -0
- package/src/frontend/services.ts +612 -0
- package/src/frontend/statements.ts +871 -0
- package/src/frontend/tasks.ts +526 -0
- package/src/frontend/telemetry.ts +174 -0
- package/src/frontend/types.ts +1073 -0
- package/src/frontend/typescript.ts +659 -0
- package/src/index.ts +9 -0
- package/src/ir/aggregates.ts +291 -0
- package/src/ir/allocation.ts +96 -0
- package/src/ir/conditions.ts +855 -0
- package/src/ir/core-model.ts +289 -0
- package/src/ir/declarations.ts +281 -0
- package/src/ir/diagnostics.ts +68 -0
- package/src/ir/domains.ts +151 -0
- package/src/ir/fold.ts +279 -0
- package/src/ir/identity.ts +19 -0
- package/src/ir/index.ts +137 -0
- package/src/ir/job-errors.ts +69 -0
- package/src/ir/layouts.ts +211 -0
- package/src/ir/link.ts +302 -0
- package/src/ir/model.ts +394 -0
- package/src/ir/normalization-error.ts +10 -0
- package/src/ir/normalize.ts +52 -0
- package/src/ir/numeric.ts +163 -0
- package/src/ir/operands.ts +160 -0
- package/src/ir/ranges.ts +420 -0
- package/src/ir/routine.ts +1116 -0
- package/src/ir/scalars.ts +453 -0
- package/src/ir/share.ts +790 -0
- package/src/ir/short-circuit.ts +140 -0
- package/src/ir/tables.ts +111 -0
- package/src/ir/temporaries.ts +138 -0
- package/src/ir/types.ts +151 -0
- package/src/project/artifacts.ts +424 -0
- package/src/project/cli.ts +211 -0
- package/src/project/debugger.ts +111 -0
- package/src/project/deployments.ts +387 -0
- package/src/project/flags.ts +14 -0
- package/src/project/git.ts +35 -0
- package/src/project/plant.ts +629 -0
- package/src/project/project-commands.ts +507 -0
- package/src/project/project.ts +559 -0
- package/src/project/release.ts +152 -0
- package/src/project/server-check.ts +54 -0
- package/src/project/server.ts +165 -0
- package/src/project/terminal.ts +45 -0
- package/src/runtime/async.ts +207 -0
- package/src/runtime/launch.ts +59 -0
- package/src/runtime/main.ts +59 -0
- package/src/runtime/missing-file.ts +3 -0
- package/src/runtime/process.ts +177 -0
- package/src/runtime/program.ts +109 -0
- package/src/runtime/retain.ts +108 -0
- package/src/runtime/runtime.ts +324 -0
- package/src/runtime/settings.ts +27 -0
- package/src/runtime/storage.ts +456 -0
- package/src/runtime/symbols.ts +97 -0
- package/src/runtime/telemetry.ts +154 -0
- package/src/runtime/transport.ts +168 -0
- package/stdlib/clock.ts +8 -0
- package/stdlib/collections.ts +534 -0
- package/stdlib/plc-time.ts +2 -0
- package/stdlib/retain.ts +4 -0
- package/stdlib/signals.ts +142 -0
- package/stdlib/telemetry.ts +89 -0
- package/types/async.d.ts +87 -0
- package/types/clock.d.ts +8 -0
- package/types/config.d.ts +2 -0
- package/types/data-types.d.ts +31 -0
- package/types/dialect.d.ts +49 -0
- package/types/globals.d.ts +10 -0
- package/types/index.d.ts +212 -0
- package/types/retain.d.ts +12 -0
- package/types/telemetry.d.ts +47 -0
|
@@ -0,0 +1,419 @@
|
|
|
1
|
+
import { type Diagnostic, error } from "@tsplc/compiler/ir";
|
|
2
|
+
import ts from "typescript";
|
|
3
|
+
import {
|
|
4
|
+
asyncWrapAdd,
|
|
5
|
+
cooperativeTasksAlias,
|
|
6
|
+
diagnosticsInstance,
|
|
7
|
+
errorCodeAlias,
|
|
8
|
+
} from "./cooperative";
|
|
9
|
+
import { GeneratedNames } from "./generated-names";
|
|
10
|
+
import { loweringKey } from "./lowering-key";
|
|
11
|
+
import { importSpecifier, namedRoutines, plcSources } from "./module-graph";
|
|
12
|
+
import {
|
|
13
|
+
type Edit,
|
|
14
|
+
edited,
|
|
15
|
+
from,
|
|
16
|
+
joined,
|
|
17
|
+
type Mapped,
|
|
18
|
+
mapped,
|
|
19
|
+
type Positions,
|
|
20
|
+
} from "./positions";
|
|
21
|
+
import { type Chain, chainOf, lowerChain } from "./promise-chains";
|
|
22
|
+
import { namesSdk, sdkModules, symbolAt } from "./sdk";
|
|
23
|
+
import { hasModifier, SemanticError } from "./types";
|
|
24
|
+
|
|
25
|
+
/** A function or method a chain can call or be written in. */
|
|
26
|
+
export type Callable = ts.FunctionDeclaration | ts.MethodDeclaration;
|
|
27
|
+
|
|
28
|
+
interface PromiseLowering {
|
|
29
|
+
sources: Map<string, Mapped>;
|
|
30
|
+
diagnostics: Diagnostic[];
|
|
31
|
+
runtimeBlocks: Map<string, { kind: "mailbox" }>;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** A detached chain's site, and the routine its chain starts with. */
|
|
35
|
+
export interface ChainSite {
|
|
36
|
+
name: string;
|
|
37
|
+
root: ts.Symbol | undefined;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** What lowering one chain needs from the rewrite of the whole program. */
|
|
41
|
+
export interface PromiseContext {
|
|
42
|
+
readonly checker: ts.TypeChecker;
|
|
43
|
+
/** Every function and method by symbol; named callbacks and operations resolve here. */
|
|
44
|
+
readonly routines: ReadonlyMap<ts.Symbol, Callable>;
|
|
45
|
+
/**
|
|
46
|
+
* The sites of detached chains, by the module or class whose cancelAsync cancels them, each with
|
|
47
|
+
* the routine its chain starts with.
|
|
48
|
+
*/
|
|
49
|
+
readonly sites: Map<ts.SourceFile | ts.ClassDeclaration, ChainSite[]>;
|
|
50
|
+
symbol(node: ts.Node): ts.Symbol | undefined;
|
|
51
|
+
/** Whether a node names the SDK declaration `name`. */
|
|
52
|
+
namesSdk(node: ts.Node, name: string): boolean;
|
|
53
|
+
fail(node: ts.Node, message: string): never;
|
|
54
|
+
/** Names for generated declarations, from the source node each stands for. */
|
|
55
|
+
readonly names: GeneratedNames;
|
|
56
|
+
/** Adds generated code to the end of a module, or to a class, mapped to the node it was made for. */
|
|
57
|
+
append(
|
|
58
|
+
scope: ts.SourceFile | ts.ClassDeclaration,
|
|
59
|
+
origin: ts.Node,
|
|
60
|
+
text: string,
|
|
61
|
+
): void;
|
|
62
|
+
/** A type's text as `source` names it: declared elsewhere, it is aliased there and imported. */
|
|
63
|
+
typeText(node: ts.TypeNode, source: ts.SourceFile): string;
|
|
64
|
+
/** Imports the SDK names generated helpers use into `source`, once. */
|
|
65
|
+
ensureImports(source: ts.SourceFile, origin: ts.Node): void;
|
|
66
|
+
/** Marks that generated code reports to the shared diagnostics block. */
|
|
67
|
+
useDiagnostics(node: ts.Node): void;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Normalize promise syntax into named coroutines; scheduling stays in async lowering. */
|
|
71
|
+
export const lowerPromises = (
|
|
72
|
+
program: ts.Program,
|
|
73
|
+
sdk: string,
|
|
74
|
+
positions: Positions,
|
|
75
|
+
root: string,
|
|
76
|
+
): PromiseLowering => {
|
|
77
|
+
const files = plcSources(program);
|
|
78
|
+
const rewrite = new PromiseRewrite(
|
|
79
|
+
program.getTypeChecker(),
|
|
80
|
+
sdk,
|
|
81
|
+
positions,
|
|
82
|
+
files,
|
|
83
|
+
new GeneratedNames(root),
|
|
84
|
+
);
|
|
85
|
+
const diagnostics: Diagnostic[] = [];
|
|
86
|
+
const runtimeBlocks = new Map<string, { kind: "mailbox" }>();
|
|
87
|
+
const { diagnosticsCalls, cancelCalls } = rewriteChains(
|
|
88
|
+
rewrite,
|
|
89
|
+
files,
|
|
90
|
+
diagnostics,
|
|
91
|
+
);
|
|
92
|
+
for (const { node, owner } of cancelCalls) {
|
|
93
|
+
cancelScope(rewrite, node, owner, diagnostics);
|
|
94
|
+
}
|
|
95
|
+
const owner = rewrite.diagnosticsOwner;
|
|
96
|
+
if (owner) {
|
|
97
|
+
const source = owner.getSourceFile();
|
|
98
|
+
rewrite.ensureImports(source, owner);
|
|
99
|
+
rewrite.append(
|
|
100
|
+
source,
|
|
101
|
+
owner,
|
|
102
|
+
`export class TsplcPromiseDiagnostics extends FunctionBlock<{}>{private count:UDINT=0;private lastError:UDINT=0;public report(code:UDINT,count:UDINT):BOOL{this.count=${asyncWrapAdd}<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{}}
|
|
103
|
+
export const ${diagnosticsInstance}=new TsplcPromiseDiagnostics();`,
|
|
104
|
+
);
|
|
105
|
+
runtimeBlocks.set(loweringKey(source.fileName, "TsplcPromiseDiagnostics"), {
|
|
106
|
+
kind: "mailbox",
|
|
107
|
+
});
|
|
108
|
+
for (const file of new Set([
|
|
109
|
+
...rewrite.extendedFiles(),
|
|
110
|
+
...diagnosticsCalls.map((node) => node.getSourceFile()),
|
|
111
|
+
])) {
|
|
112
|
+
if (file !== source) {
|
|
113
|
+
rewrite.append(
|
|
114
|
+
file,
|
|
115
|
+
file,
|
|
116
|
+
`import {${diagnosticsInstance}} from ${importSpecifier(file.fileName, source.fileName)};`,
|
|
117
|
+
);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
for (const call of diagnosticsCalls) {
|
|
121
|
+
rewrite.edit(call, `${diagnosticsInstance}.snapshot()`);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return { sources: rewrite.sources(files), diagnostics, runtimeBlocks };
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Replaces each promise chain in a routine: a detached statement becomes a cooperative site,
|
|
129
|
+
* and a chain used as a value becomes a call to its last helper. Collects the
|
|
130
|
+
* `asyncDiagnostics()` and `cancelAsync()` calls it passes.
|
|
131
|
+
*/
|
|
132
|
+
function rewriteChains(
|
|
133
|
+
rewrite: PromiseRewrite,
|
|
134
|
+
files: readonly ts.SourceFile[],
|
|
135
|
+
diagnostics: Diagnostic[],
|
|
136
|
+
) {
|
|
137
|
+
const diagnosticsCalls: ts.CallExpression[] = [];
|
|
138
|
+
const cancelCalls: { node: ts.CallExpression; owner: Callable }[] = [];
|
|
139
|
+
const lower = (
|
|
140
|
+
node: ts.Node,
|
|
141
|
+
expression: ts.Expression,
|
|
142
|
+
chain: Chain,
|
|
143
|
+
owner: Callable,
|
|
144
|
+
{ detached }: { detached: boolean },
|
|
145
|
+
) => {
|
|
146
|
+
try {
|
|
147
|
+
rewrite.edit(
|
|
148
|
+
node,
|
|
149
|
+
lowerChain(rewrite, expression, chain, owner, { detached }),
|
|
150
|
+
);
|
|
151
|
+
} catch (cause) {
|
|
152
|
+
if (!(cause instanceof SemanticError)) {
|
|
153
|
+
throw cause;
|
|
154
|
+
}
|
|
155
|
+
diagnostics.push(cause.diagnostic);
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
for (const source of files) {
|
|
159
|
+
const visit = (node: ts.Node, owner?: Callable): void => {
|
|
160
|
+
if (ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node)) {
|
|
161
|
+
if (node.body) {
|
|
162
|
+
ts.forEachChild(node.body, (child) => visit(child, node));
|
|
163
|
+
}
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
if (!owner) {
|
|
167
|
+
ts.forEachChild(node, (child) => visit(child));
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
if (
|
|
171
|
+
ts.isCallExpression(node) &&
|
|
172
|
+
rewrite.namesSdk(node.expression, "asyncDiagnostics")
|
|
173
|
+
) {
|
|
174
|
+
rewrite.useDiagnostics(node);
|
|
175
|
+
diagnosticsCalls.push(node);
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
if (
|
|
179
|
+
ts.isCallExpression(node) &&
|
|
180
|
+
rewrite.namesSdk(node.expression, "cancelAsync")
|
|
181
|
+
) {
|
|
182
|
+
cancelCalls.push({ node, owner });
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
if (ts.isExpressionStatement(node)) {
|
|
186
|
+
const expression = ts.isVoidExpression(node.expression)
|
|
187
|
+
? node.expression.expression
|
|
188
|
+
: node.expression;
|
|
189
|
+
const chain = chainOf(rewrite, expression);
|
|
190
|
+
if (chain) {
|
|
191
|
+
if (hasModifier(owner, ts.SyntaxKind.AsyncKeyword)) {
|
|
192
|
+
diagnostics.push(
|
|
193
|
+
rewrite.diagnostic(
|
|
194
|
+
node,
|
|
195
|
+
"Await async work inside an async routine; detached calls belong in synchronous controllers.",
|
|
196
|
+
),
|
|
197
|
+
);
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
lower(node, expression, chain, owner, { detached: true });
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
if (ts.isCallExpression(node)) {
|
|
205
|
+
const chain = chainOf(rewrite, node);
|
|
206
|
+
if (chain?.links.length) {
|
|
207
|
+
lower(node, node, chain, owner, { detached: false });
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
ts.forEachChild(node, (child) => visit(child, owner));
|
|
212
|
+
};
|
|
213
|
+
visit(source);
|
|
214
|
+
}
|
|
215
|
+
return { diagnosticsCalls, cancelCalls };
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* `cancelAsync()` cancels every detached chain of the module, `cancelAsync(this)` of the block, and
|
|
220
|
+
* `cancelAsync(run, ...)` in a module each of the module's chains that starts with one of those
|
|
221
|
+
* routines, which is how a plain program cancels one object's calls.
|
|
222
|
+
*/
|
|
223
|
+
function cancelScope(
|
|
224
|
+
rewrite: PromiseRewrite,
|
|
225
|
+
node: ts.CallExpression,
|
|
226
|
+
owner: Callable,
|
|
227
|
+
diagnostics: Diagnostic[],
|
|
228
|
+
): void {
|
|
229
|
+
const scope =
|
|
230
|
+
ts.isMethodDeclaration(owner) && ts.isClassDeclaration(owner.parent)
|
|
231
|
+
? owner.parent
|
|
232
|
+
: owner.getSourceFile();
|
|
233
|
+
const member = ts.isClassDeclaration(scope);
|
|
234
|
+
const [argument, ...rest] = node.arguments;
|
|
235
|
+
const roots = member
|
|
236
|
+
? undefined
|
|
237
|
+
: node.arguments.map((routine) =>
|
|
238
|
+
ts.isIdentifier(routine) ? rewrite.symbol(routine) : undefined,
|
|
239
|
+
);
|
|
240
|
+
const byRoutine =
|
|
241
|
+
roots !== undefined &&
|
|
242
|
+
roots.length > 0 &&
|
|
243
|
+
roots.every((root) => root !== undefined && rewrite.routines.has(root));
|
|
244
|
+
if (
|
|
245
|
+
argument &&
|
|
246
|
+
!byRoutine &&
|
|
247
|
+
(rest.length || argument.kind !== ts.SyntaxKind.ThisKeyword)
|
|
248
|
+
) {
|
|
249
|
+
diagnostics.push(
|
|
250
|
+
rewrite.diagnostic(
|
|
251
|
+
node,
|
|
252
|
+
"cancelAsync takes this in a controller, or no argument in a module.",
|
|
253
|
+
),
|
|
254
|
+
);
|
|
255
|
+
}
|
|
256
|
+
const name = rewrite.names.name("tsplcCancelScope", node);
|
|
257
|
+
const body = (rewrite.sites.get(scope) ?? [])
|
|
258
|
+
.filter(
|
|
259
|
+
(site) =>
|
|
260
|
+
!byRoutine || (site.root !== undefined && roots.includes(site.root)),
|
|
261
|
+
)
|
|
262
|
+
.map((site) => `${member ? "this." : ""}${site.name}.cancel();`)
|
|
263
|
+
.join("");
|
|
264
|
+
rewrite.append(
|
|
265
|
+
scope,
|
|
266
|
+
node,
|
|
267
|
+
member
|
|
268
|
+
? `private ${name}():void{${body}}`
|
|
269
|
+
: `function ${name}():void{${body}}`,
|
|
270
|
+
);
|
|
271
|
+
rewrite.edit(node, `${member ? "this." : ""}${name}()`);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** The edits and generated code promise lowering makes across the program. */
|
|
275
|
+
class PromiseRewrite implements PromiseContext {
|
|
276
|
+
readonly routines: ReadonlyMap<ts.Symbol, Callable>;
|
|
277
|
+
readonly sites = new Map<ts.SourceFile | ts.ClassDeclaration, ChainSite[]>();
|
|
278
|
+
/** The first node that needs the shared diagnostics block, which its module declares. */
|
|
279
|
+
diagnosticsOwner: ts.Node | undefined;
|
|
280
|
+
/** Generated code by the module it ends or the class it joins. */
|
|
281
|
+
private readonly additions = new Map<
|
|
282
|
+
ts.SourceFile | ts.ClassDeclaration,
|
|
283
|
+
Mapped[]
|
|
284
|
+
>();
|
|
285
|
+
private readonly edits = new Map<ts.SourceFile, Edit[]>();
|
|
286
|
+
private readonly aliases = new Map<ts.Node, string>();
|
|
287
|
+
private readonly typeImports = new Map<ts.SourceFile, Set<string>>();
|
|
288
|
+
private readonly imported = new Set<ts.SourceFile>();
|
|
289
|
+
constructor(
|
|
290
|
+
readonly checker: ts.TypeChecker,
|
|
291
|
+
private readonly sdk: string,
|
|
292
|
+
private readonly positions: Positions,
|
|
293
|
+
files: readonly ts.SourceFile[],
|
|
294
|
+
readonly names: GeneratedNames,
|
|
295
|
+
) {
|
|
296
|
+
this.routines = namedRoutines(files, checker);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
symbol(node: ts.Node): ts.Symbol | undefined {
|
|
300
|
+
return symbolAt(this.checker, node);
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
namesSdk(node: ts.Node, name: string): boolean {
|
|
304
|
+
return namesSdk(this.checker, this.sdk, node, name);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
diagnostic(node: ts.Node, message: string): Diagnostic {
|
|
308
|
+
return error("PLC1012", message, this.positions.node(node));
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
fail(node: ts.Node, message: string): never {
|
|
312
|
+
throw new SemanticError(this.diagnostic(node, message));
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
append(
|
|
316
|
+
scope: ts.SourceFile | ts.ClassDeclaration,
|
|
317
|
+
origin: ts.Node,
|
|
318
|
+
text: string,
|
|
319
|
+
): void {
|
|
320
|
+
this.additions.set(scope, [
|
|
321
|
+
...(this.additions.get(scope) ?? []),
|
|
322
|
+
from(origin, text),
|
|
323
|
+
]);
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
edit(node: ts.Node, text: string): void {
|
|
327
|
+
const source = node.getSourceFile();
|
|
328
|
+
this.edits.set(source, [
|
|
329
|
+
...(this.edits.get(source) ?? []),
|
|
330
|
+
{ start: node.getStart(source), end: node.end, text },
|
|
331
|
+
]);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** The modules generated code has been added to so far. */
|
|
335
|
+
extendedFiles(): ts.SourceFile[] {
|
|
336
|
+
return [...this.additions.keys()].filter(ts.isSourceFile);
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
typeText(node: ts.TypeNode, source: ts.SourceFile): string {
|
|
340
|
+
if (node.kind === ts.SyntaxKind.VoidKeyword) {
|
|
341
|
+
return "void";
|
|
342
|
+
}
|
|
343
|
+
if (node.getSourceFile() === source) {
|
|
344
|
+
return node.getText(source);
|
|
345
|
+
}
|
|
346
|
+
const alias = this.aliases.get(node) ?? this.declareAlias(node);
|
|
347
|
+
const importedAliases = this.typeImports.get(source) ?? new Set<string>();
|
|
348
|
+
if (importedAliases.has(alias)) {
|
|
349
|
+
return alias;
|
|
350
|
+
}
|
|
351
|
+
importedAliases.add(alias);
|
|
352
|
+
this.typeImports.set(source, importedAliases);
|
|
353
|
+
this.append(
|
|
354
|
+
source,
|
|
355
|
+
node,
|
|
356
|
+
`import type {${alias}} from ${importSpecifier(source.fileName, node.getSourceFile().fileName)};`,
|
|
357
|
+
);
|
|
358
|
+
return alias;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/** Exports a type from the module that declares it, so other modules can name it. */
|
|
362
|
+
private declareAlias(node: ts.TypeNode): string {
|
|
363
|
+
const alias = this.names.name("TsplcPromiseType", node);
|
|
364
|
+
this.aliases.set(node, alias);
|
|
365
|
+
this.append(
|
|
366
|
+
node.getSourceFile(),
|
|
367
|
+
node,
|
|
368
|
+
`export type ${alias}=${node.getText(node.getSourceFile())};`,
|
|
369
|
+
);
|
|
370
|
+
return alias;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
ensureImports(source: ts.SourceFile, origin: ts.Node): void {
|
|
374
|
+
if (this.imported.has(source)) {
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
this.imported.add(source);
|
|
378
|
+
this.append(
|
|
379
|
+
source,
|
|
380
|
+
origin,
|
|
381
|
+
`import {cooperativeTasks as ${cooperativeTasksAlias},errorCode as ${errorCodeAlias}} from "${sdkModules.async}";import {wrapAdd as ${asyncWrapAdd}} from "${sdkModules.types}";`,
|
|
382
|
+
);
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
useDiagnostics(node: ts.Node): void {
|
|
386
|
+
this.diagnosticsOwner ??= node;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/** Each changed module's text: its edits, class members appended in place, then its additions. */
|
|
390
|
+
sources(files: readonly ts.SourceFile[]): Map<string, Mapped> {
|
|
391
|
+
for (const [owner, texts] of this.additions) {
|
|
392
|
+
if (!ts.isClassDeclaration(owner)) {
|
|
393
|
+
continue;
|
|
394
|
+
}
|
|
395
|
+
const source = owner.getSourceFile();
|
|
396
|
+
this.edits.set(source, [
|
|
397
|
+
...(this.edits.get(source) ?? []),
|
|
398
|
+
{
|
|
399
|
+
start: owner.end - 1,
|
|
400
|
+
end: owner.end - 1,
|
|
401
|
+
text: mapped`\n${joined(texts, "\n")}`,
|
|
402
|
+
},
|
|
403
|
+
]);
|
|
404
|
+
}
|
|
405
|
+
const sources = new Map<string, Mapped>();
|
|
406
|
+
for (const source of files) {
|
|
407
|
+
const changes = this.edits.get(source) ?? [];
|
|
408
|
+
const extra = this.additions.get(source) ?? [];
|
|
409
|
+
if (!changes.length && !extra.length) {
|
|
410
|
+
continue;
|
|
411
|
+
}
|
|
412
|
+
sources.set(
|
|
413
|
+
source.fileName,
|
|
414
|
+
mapped`${edited(source, changes)}\n${joined(extra, "\n")}`,
|
|
415
|
+
);
|
|
416
|
+
}
|
|
417
|
+
return sources;
|
|
418
|
+
}
|
|
419
|
+
}
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
import type { MethodOwner, PlcFunction, Variable } from "@tsplc/compiler/ir";
|
|
2
|
+
import ts from "typescript";
|
|
3
|
+
import type { Positions } from "./positions";
|
|
4
|
+
import {
|
|
5
|
+
type Fail,
|
|
6
|
+
hasModifier,
|
|
7
|
+
type TypeEnvironment,
|
|
8
|
+
type TypeResolver,
|
|
9
|
+
} from "./types";
|
|
10
|
+
|
|
11
|
+
/** A routine whose signature is admitted and whose body is still to be lowered. */
|
|
12
|
+
interface PendingRoutine {
|
|
13
|
+
node: ts.FunctionDeclaration | ts.MethodDeclaration;
|
|
14
|
+
body: ts.Block;
|
|
15
|
+
fn: PlcFunction;
|
|
16
|
+
/** Each parameter's symbol and the variable it binds. */
|
|
17
|
+
parameters: readonly (readonly [ts.Symbol, Variable])[];
|
|
18
|
+
environment: TypeEnvironment;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Concrete helpers that generic calls may specialize, which bounds recursive specialization. */
|
|
22
|
+
const maxSpecializations = 256;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The routines a module contains: helpers and block methods by symbol, every
|
|
26
|
+
* instance by id, and the worklist of bodies still to lower. Lowering a body can
|
|
27
|
+
* instantiate more generic helpers, which join the worklist.
|
|
28
|
+
*/
|
|
29
|
+
export class RoutineTable {
|
|
30
|
+
private readonly functionsBySymbol = new Map<ts.Symbol, PlcFunction>();
|
|
31
|
+
readonly functions: ReadonlyMap<ts.Symbol, PlcFunction> =
|
|
32
|
+
this.functionsBySymbol;
|
|
33
|
+
private readonly methodsBySymbol = new Map<ts.Symbol, PlcFunction>();
|
|
34
|
+
readonly methods: ReadonlyMap<ts.Symbol, PlcFunction> = this.methodsBySymbol;
|
|
35
|
+
private readonly declarations = new Map<ts.Symbol, ts.FunctionDeclaration>();
|
|
36
|
+
readonly functionDeclarations: ReadonlyMap<
|
|
37
|
+
ts.Symbol,
|
|
38
|
+
ts.FunctionDeclaration
|
|
39
|
+
> = this.declarations;
|
|
40
|
+
private readonly instancesById = new Map<string, PlcFunction>();
|
|
41
|
+
readonly instances: ReadonlyMap<string, PlcFunction> = this.instancesById;
|
|
42
|
+
private readonly worklist: PendingRoutine[] = [];
|
|
43
|
+
readonly pending: readonly PendingRoutine[] = this.worklist;
|
|
44
|
+
private specializations = 0;
|
|
45
|
+
|
|
46
|
+
constructor(
|
|
47
|
+
private readonly checker: ts.TypeChecker,
|
|
48
|
+
private readonly resolver: TypeResolver,
|
|
49
|
+
private readonly positions: Positions,
|
|
50
|
+
private readonly fail: Fail,
|
|
51
|
+
) {}
|
|
52
|
+
|
|
53
|
+
/** Admits a helper declaration; one without type parameters has its single instance now. */
|
|
54
|
+
declareFunction(symbol: ts.Symbol, node: ts.FunctionDeclaration): void {
|
|
55
|
+
this.declarations.set(symbol, node);
|
|
56
|
+
if (!node.typeParameters?.length) {
|
|
57
|
+
this.functionsBySymbol.set(
|
|
58
|
+
symbol,
|
|
59
|
+
this.instantiate(node, [], node, new Map()),
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Admits a block method, which `owner` calls on its instances. */
|
|
65
|
+
declareMethod(
|
|
66
|
+
symbol: ts.Symbol,
|
|
67
|
+
node: ts.MethodDeclaration,
|
|
68
|
+
owner: MethodOwner,
|
|
69
|
+
): void {
|
|
70
|
+
this.methodsBySymbol.set(
|
|
71
|
+
symbol,
|
|
72
|
+
this.instance(node, [], node, new Map(), owner),
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Replaces a pending routine's instance with `fn`, its lowered body. */
|
|
77
|
+
complete(routine: PendingRoutine, fn: PlcFunction): void {
|
|
78
|
+
this.instancesById.set(fn.id, fn);
|
|
79
|
+
const { node } = routine;
|
|
80
|
+
if (
|
|
81
|
+
ts.isFunctionDeclaration(node) &&
|
|
82
|
+
node.name &&
|
|
83
|
+
!node.typeParameters?.length
|
|
84
|
+
) {
|
|
85
|
+
this.functionsBySymbol.set(this.resolver.symbol(node.name), fn);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
instantiate(
|
|
90
|
+
node: ts.FunctionDeclaration | ts.MethodDeclaration,
|
|
91
|
+
arguments_: readonly ts.TypeNode[],
|
|
92
|
+
call: ts.Node,
|
|
93
|
+
outer: TypeEnvironment,
|
|
94
|
+
): PlcFunction {
|
|
95
|
+
return this.instance(node, arguments_, call, outer, null);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
private instance(
|
|
99
|
+
node: ts.FunctionDeclaration | ts.MethodDeclaration,
|
|
100
|
+
arguments_: readonly ts.TypeNode[],
|
|
101
|
+
call: ts.Node,
|
|
102
|
+
outer: TypeEnvironment,
|
|
103
|
+
owner: MethodOwner | null,
|
|
104
|
+
): PlcFunction {
|
|
105
|
+
if (!node.name || !ts.isIdentifier(node.name)) {
|
|
106
|
+
this.fail(node, "PLC1001", "PLC routines need identifier names.");
|
|
107
|
+
}
|
|
108
|
+
const routineName = node.name.text;
|
|
109
|
+
const { environment, suffix } = this.resolver.bindings(
|
|
110
|
+
node.typeParameters,
|
|
111
|
+
arguments_,
|
|
112
|
+
outer,
|
|
113
|
+
call,
|
|
114
|
+
);
|
|
115
|
+
const id = `${this.resolver.id(node, routineName)}${suffix ? `<${suffix}>` : ""}`;
|
|
116
|
+
const existing = this.instancesById.get(id);
|
|
117
|
+
if (existing) {
|
|
118
|
+
return existing;
|
|
119
|
+
}
|
|
120
|
+
if (suffix && this.specializations >= maxSpecializations) {
|
|
121
|
+
this.fail(
|
|
122
|
+
call,
|
|
123
|
+
"PLC2001",
|
|
124
|
+
`Generic specialization exceeds ${maxSpecializations} concrete helpers; recursive specialization is unsupported.`,
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
const body = node.body;
|
|
128
|
+
if (!body) {
|
|
129
|
+
throw new Error(`Routine ${id} has no implementation to lower.`);
|
|
130
|
+
}
|
|
131
|
+
const parameters = node.parameters.map((parameter) => {
|
|
132
|
+
if (
|
|
133
|
+
!ts.isIdentifier(parameter.name) ||
|
|
134
|
+
!parameter.type ||
|
|
135
|
+
parameter.initializer ||
|
|
136
|
+
parameter.questionToken ||
|
|
137
|
+
parameter.dotDotDotToken
|
|
138
|
+
) {
|
|
139
|
+
this.fail(
|
|
140
|
+
parameter,
|
|
141
|
+
"PLC2001",
|
|
142
|
+
"PLC parameters need names and explicit types; optional/rest/default parameters are unsupported.",
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
const type = this.resolver.resolve(parameter.type, environment);
|
|
146
|
+
const block = this.resolver.types.get(type.type)?.kind === "block";
|
|
147
|
+
if (type.mode !== "inOut" && !block && !this.resolver.isValue(type)) {
|
|
148
|
+
this.fail(
|
|
149
|
+
parameter,
|
|
150
|
+
"PLC2001",
|
|
151
|
+
"Parameters require value types or InOut borrows.",
|
|
152
|
+
);
|
|
153
|
+
}
|
|
154
|
+
if (type.io) {
|
|
155
|
+
this.fail(
|
|
156
|
+
parameter,
|
|
157
|
+
"PLC2001",
|
|
158
|
+
"Parameters cannot use logical I/O wrappers.",
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
const mode = this.resolver.parameterMode(type);
|
|
162
|
+
const variable: Variable = {
|
|
163
|
+
id: `${this.resolver.id(parameter, parameter.name.text)}@${id}`,
|
|
164
|
+
name: parameter.name.text,
|
|
165
|
+
type: type.type,
|
|
166
|
+
storage: "parameter",
|
|
167
|
+
mutable: mode === "inOut",
|
|
168
|
+
...(mode && { mode }),
|
|
169
|
+
retention: "none",
|
|
170
|
+
span: this.positions.node(parameter),
|
|
171
|
+
};
|
|
172
|
+
return [this.resolver.symbol(parameter.name), variable] as const;
|
|
173
|
+
});
|
|
174
|
+
const result = this.result(node, environment);
|
|
175
|
+
const fn: PlcFunction = {
|
|
176
|
+
id,
|
|
177
|
+
name: `${routineName}${suffix ? `_${suffix}` : ""}`,
|
|
178
|
+
parameters: parameters.map(([, variable]) => variable),
|
|
179
|
+
locals: [],
|
|
180
|
+
body: [],
|
|
181
|
+
span: this.positions.node(node),
|
|
182
|
+
...(result && { result }),
|
|
183
|
+
...(owner && { owner }),
|
|
184
|
+
};
|
|
185
|
+
this.instancesById.set(id, fn);
|
|
186
|
+
if (suffix) {
|
|
187
|
+
this.specializations++;
|
|
188
|
+
}
|
|
189
|
+
this.worklist.push({ node, body, fn, parameters, environment });
|
|
190
|
+
return fn;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** The type a routine returns; undefined when it returns nothing. */
|
|
194
|
+
private result(
|
|
195
|
+
node: ts.FunctionDeclaration | ts.MethodDeclaration,
|
|
196
|
+
environment: TypeEnvironment,
|
|
197
|
+
): string | undefined {
|
|
198
|
+
if (!node.type) {
|
|
199
|
+
const signature = this.checker.getSignatureFromDeclaration(node);
|
|
200
|
+
if (
|
|
201
|
+
!signature ||
|
|
202
|
+
!(
|
|
203
|
+
this.checker.getReturnTypeOfSignature(signature).flags &
|
|
204
|
+
ts.TypeFlags.Void
|
|
205
|
+
)
|
|
206
|
+
) {
|
|
207
|
+
this.fail(node, "PLC2001", "Annotate helper results explicitly.");
|
|
208
|
+
}
|
|
209
|
+
return undefined;
|
|
210
|
+
}
|
|
211
|
+
if (node.type.kind === ts.SyntaxKind.VoidKeyword) {
|
|
212
|
+
return undefined;
|
|
213
|
+
}
|
|
214
|
+
const type = this.resolver.resolve(node.type, environment);
|
|
215
|
+
if (!this.resolver.isValue(type)) {
|
|
216
|
+
this.fail(node.type, "PLC2001", "Helper results require value types.");
|
|
217
|
+
}
|
|
218
|
+
if (type.io) {
|
|
219
|
+
this.fail(
|
|
220
|
+
node.type,
|
|
221
|
+
"PLC4002",
|
|
222
|
+
"Helper results cannot use I/O wrappers.",
|
|
223
|
+
);
|
|
224
|
+
}
|
|
225
|
+
return type.type;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
export const methodAccess = (
|
|
230
|
+
method: ts.MethodDeclaration,
|
|
231
|
+
): MethodOwner["access"] => {
|
|
232
|
+
if (hasModifier(method, ts.SyntaxKind.PrivateKeyword)) {
|
|
233
|
+
return "private";
|
|
234
|
+
}
|
|
235
|
+
if (hasModifier(method, ts.SyntaxKind.ProtectedKeyword)) {
|
|
236
|
+
return "protected";
|
|
237
|
+
}
|
|
238
|
+
return "public";
|
|
239
|
+
};
|