@tsplc/compiler 0.5.4 → 0.5.6
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/dist/bun-runtime.js +14 -2
- package/dist/bun-runtime.js.map +4 -4
- package/dist/codesys.js +46 -2
- package/dist/codesys.js.map +3 -3
- package/dist/collections.js +395 -0
- package/dist/collections.js.map +10 -0
- package/dist/elaborate-capture.js +64 -5
- package/dist/elaborate-capture.js.map +4 -4
- package/dist/index.js +5345 -1074
- package/dist/index.js.map +32 -25
- package/dist/ir.js +122 -1
- package/dist/ir.js.map +6 -6
- package/package.json +14 -9
- package/src/codesys/numeric.ts +61 -0
- package/src/frontend/control-flow.ts +752 -0
- package/src/frontend/coroutines.ts +171 -7
- package/src/frontend/elaborate/array-searches.ts +216 -0
- package/src/frontend/elaborate/assignments.ts +352 -0
- package/src/frontend/elaborate/calls.ts +488 -49
- package/src/frontend/elaborate/capture-protocol.ts +19 -0
- package/src/frontend/elaborate/capture.ts +82 -3
- package/src/frontend/elaborate/dialect.ts +118 -4
- package/src/frontend/elaborate/expressions.ts +927 -80
- package/src/frontend/elaborate/filtered-arrays.ts +607 -0
- package/src/frontend/elaborate/frame.ts +44 -1
- package/src/frontend/elaborate/generics.ts +137 -0
- package/src/frontend/elaborate/graph.ts +91 -0
- package/src/frontend/elaborate/imports.ts +14 -15
- package/src/frontend/elaborate/index.ts +30 -5
- package/src/frontend/elaborate/initializers.ts +15 -1
- package/src/frontend/elaborate/iterators.ts +1677 -0
- package/src/frontend/elaborate/layouts.ts +41 -19
- package/src/frontend/elaborate/model.ts +64 -8
- package/src/frontend/elaborate/references.ts +749 -0
- package/src/frontend/elaborate/specialize.ts +459 -29
- package/src/frontend/elaborate/statements.ts +552 -133
- package/src/frontend/elaborate/storage.ts +151 -10
- package/src/frontend/elaborate/values.ts +72 -0
- package/src/frontend/elaborate/writes.ts +302 -1
- package/src/frontend/intrinsics.ts +32 -0
- package/src/frontend/module-graph.ts +2 -1
- package/src/frontend/positions.ts +12 -5
- package/src/frontend/sdk.ts +7 -1
- package/src/frontend/typescript.ts +5 -1
- package/src/ir/core-model.ts +2 -6
- package/src/ir/fold.ts +30 -1
- package/src/ir/index.ts +5 -0
- package/src/ir/model.ts +53 -2
- package/src/ir/scalars.ts +126 -0
- package/src/runtime/.runtime-VaUSOu/server/router.ts +17 -0
- package/src/runtime/.runtime-VaUSOu/src/cell.ts +45 -0
- package/src/runtime/.runtime-VaUSOu/src/controller.ts +58 -0
- package/src/runtime/.runtime-VaUSOu/src/lane.ts +6 -0
- package/src/runtime/.runtime-VaUSOu/src/main.ts +11 -0
- package/src/runtime/.runtime-VaUSOu/src/services.ts +8 -0
- package/src/runtime/.runtime-VaUSOu/tsconfig.json +13 -0
- package/src/runtime/.runtime-VaUSOu/tsplc.config.ts +31 -0
- package/src/runtime/.runtime-ybIxYh/server/router.ts +17 -0
- package/src/runtime/.runtime-ybIxYh/src/cell.ts +45 -0
- package/src/runtime/.runtime-ybIxYh/src/controller.ts +58 -0
- package/src/runtime/.runtime-ybIxYh/src/lane.ts +6 -0
- package/src/runtime/.runtime-ybIxYh/src/main.ts +11 -0
- package/src/runtime/.runtime-ybIxYh/src/services.ts +8 -0
- package/src/runtime/.runtime-ybIxYh/tsconfig.json +13 -0
- package/src/runtime/.runtime-ybIxYh/tsplc.config.ts +31 -0
- package/stdlib/collections.ts +514 -0
- package/types/index.d.ts +18 -0
|
@@ -0,0 +1,752 @@
|
|
|
1
|
+
import type { Diagnostic } from "@tsplc/compiler/ir";
|
|
2
|
+
import ts from "typescript";
|
|
3
|
+
import { runtimeSources } from "./module-graph";
|
|
4
|
+
import {
|
|
5
|
+
copied,
|
|
6
|
+
copiedRange,
|
|
7
|
+
type Edit,
|
|
8
|
+
edited,
|
|
9
|
+
from,
|
|
10
|
+
joined,
|
|
11
|
+
type Mapped,
|
|
12
|
+
mapped,
|
|
13
|
+
type Part,
|
|
14
|
+
} from "./positions";
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Structured Text exits a loop with EXIT and leaves a CASE at its end only, and has no labels and no
|
|
18
|
+
* finally. Jumps it can't express become flags: the jump sets its flag, the statements after it run
|
|
19
|
+
* only while the flag is clear, and the statement the jump targets clears it.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
type JumpKind = "break" | "continue" | "return";
|
|
23
|
+
|
|
24
|
+
/** A statement a jump can leave or target. */
|
|
25
|
+
interface Target {
|
|
26
|
+
kind: "loop" | "switch" | "labelled" | "finally";
|
|
27
|
+
labels: readonly string[];
|
|
28
|
+
breakFlag?: string;
|
|
29
|
+
continueFlag?: string;
|
|
30
|
+
/** Of a try with finally: which of its blocks the statements being lowered sit in. */
|
|
31
|
+
region?: "try" | "catch" | "finally";
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** A jump that left its statement with its flag set; undefined `target` is the routine, for a return. */
|
|
35
|
+
interface Pending {
|
|
36
|
+
kind: JumpKind;
|
|
37
|
+
flag: string;
|
|
38
|
+
target: Target | undefined;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
interface Lowered {
|
|
42
|
+
text: Part;
|
|
43
|
+
pending: readonly Pending[];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
interface List {
|
|
47
|
+
parts: readonly Part[];
|
|
48
|
+
pending: readonly Pending[];
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** One statement of a list, lowered when its turn comes, so guards can wrap the statements after it. */
|
|
52
|
+
interface Item {
|
|
53
|
+
origin: ts.Node;
|
|
54
|
+
lower: () => Lowered;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
interface Routine {
|
|
58
|
+
source: ts.SourceFile;
|
|
59
|
+
async: boolean;
|
|
60
|
+
stack: Target[];
|
|
61
|
+
/** The routine's result type as written, or undefined when it returns nothing. */
|
|
62
|
+
resultType: string | undefined;
|
|
63
|
+
result?: { flag: string; value: string | undefined };
|
|
64
|
+
changes: number;
|
|
65
|
+
name: (base: string) => string;
|
|
66
|
+
/** The SDK functions the lowered routine calls, which its module imports. */
|
|
67
|
+
uses: Set<keyof typeof sdkNames>;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const unique = (pending: readonly Pending[]): Pending[] => [
|
|
71
|
+
...new Map(pending.map((item) => [item.flag, item])).values(),
|
|
72
|
+
];
|
|
73
|
+
|
|
74
|
+
const anyOf = (pending: readonly Pending[]): string =>
|
|
75
|
+
unique(pending)
|
|
76
|
+
.map((item) => item.flag)
|
|
77
|
+
.join(" || ");
|
|
78
|
+
|
|
79
|
+
/** A case's or block's statements, looking through the one block a braced case holds. */
|
|
80
|
+
const unbraced = (
|
|
81
|
+
statements: readonly ts.Statement[],
|
|
82
|
+
): readonly ts.Statement[] => {
|
|
83
|
+
const [only, ...others] = statements;
|
|
84
|
+
return only && !others.length && ts.isBlock(only)
|
|
85
|
+
? only.statements
|
|
86
|
+
: statements;
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
const isJump = (statement: ts.Statement | undefined): boolean =>
|
|
90
|
+
statement !== undefined &&
|
|
91
|
+
(ts.isBreakStatement(statement) ||
|
|
92
|
+
ts.isContinueStatement(statement) ||
|
|
93
|
+
ts.isReturnStatement(statement) ||
|
|
94
|
+
ts.isThrowStatement(statement));
|
|
95
|
+
|
|
96
|
+
const containsAwaitOrThrow = (node: ts.Node): boolean =>
|
|
97
|
+
ts.isAwaitExpression(node) ||
|
|
98
|
+
ts.isThrowStatement(node) ||
|
|
99
|
+
(!ts.isFunctionLike(node) &&
|
|
100
|
+
(ts.forEachChild(node, containsAwaitOrThrow) ?? false));
|
|
101
|
+
|
|
102
|
+
/** Whether Structured Text can make the jump as written, from inside `crossing` to `target`. */
|
|
103
|
+
const isNative = (
|
|
104
|
+
kind: JumpKind,
|
|
105
|
+
target: Target | undefined,
|
|
106
|
+
crossing: readonly Target[],
|
|
107
|
+
): boolean => {
|
|
108
|
+
if (
|
|
109
|
+
crossing.some(
|
|
110
|
+
(item) => item.kind === "finally" && item.region !== "finally",
|
|
111
|
+
)
|
|
112
|
+
) {
|
|
113
|
+
return false;
|
|
114
|
+
}
|
|
115
|
+
if (kind === "return" || !target) {
|
|
116
|
+
return true;
|
|
117
|
+
}
|
|
118
|
+
if (target.kind !== "loop") {
|
|
119
|
+
return false;
|
|
120
|
+
}
|
|
121
|
+
return kind === "break"
|
|
122
|
+
? !crossing.some((item) => item.kind === "loop" || item.kind === "switch")
|
|
123
|
+
: !crossing.some((item) => item.kind === "loop");
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
/** The innermost statement a native `break` would leave, past labelled blocks. */
|
|
127
|
+
const innermostExit = (
|
|
128
|
+
crossing: readonly Target[],
|
|
129
|
+
): Target["kind"] | undefined =>
|
|
130
|
+
[...crossing].reverse().find((item) => item.kind !== "labelled")?.kind;
|
|
131
|
+
|
|
132
|
+
const targetIndex = (
|
|
133
|
+
kind: JumpKind,
|
|
134
|
+
label: string | undefined,
|
|
135
|
+
stack: readonly Target[],
|
|
136
|
+
): number | undefined => {
|
|
137
|
+
if (kind === "return") {
|
|
138
|
+
return -1;
|
|
139
|
+
}
|
|
140
|
+
for (let index = stack.length - 1; index >= 0; index--) {
|
|
141
|
+
const item = stack[index];
|
|
142
|
+
if (!item) {
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
if (label !== undefined) {
|
|
146
|
+
if (item.labels.includes(label)) {
|
|
147
|
+
return index;
|
|
148
|
+
}
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
if (item.kind === "loop" || (kind === "break" && item.kind === "switch")) {
|
|
152
|
+
return index;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return undefined;
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
const lowerItems = (items: readonly Item[], loop: Target | undefined): List => {
|
|
159
|
+
const [first, ...others] = items;
|
|
160
|
+
if (!first) {
|
|
161
|
+
return { parts: [], pending: [] };
|
|
162
|
+
}
|
|
163
|
+
const head = first.lower();
|
|
164
|
+
const tail = lowerItems(others, loop);
|
|
165
|
+
if (!head.pending.length) {
|
|
166
|
+
return { parts: [head.text, ...tail.parts], pending: tail.pending };
|
|
167
|
+
}
|
|
168
|
+
// Directly in a loop's body, a jump past the loop leaves it with EXIT; one continuing it skips the rest.
|
|
169
|
+
const continuing = loop
|
|
170
|
+
? head.pending.filter(
|
|
171
|
+
(item) => item.target === loop && item.kind === "continue",
|
|
172
|
+
)
|
|
173
|
+
: head.pending;
|
|
174
|
+
const leaving = loop
|
|
175
|
+
? head.pending.filter(
|
|
176
|
+
(item) => !(item.target === loop && item.kind === "continue"),
|
|
177
|
+
)
|
|
178
|
+
: [];
|
|
179
|
+
const parts: Part[] = [head.text];
|
|
180
|
+
if (leaving.length) {
|
|
181
|
+
parts.push(from(first.origin, `if (${anyOf(leaving)}) { break; }`));
|
|
182
|
+
}
|
|
183
|
+
if (tail.parts.length) {
|
|
184
|
+
parts.push(
|
|
185
|
+
continuing.length
|
|
186
|
+
? from(
|
|
187
|
+
first.origin,
|
|
188
|
+
mapped`if (!(${anyOf(continuing)})) { ${joined(tail.parts, " ")} }`,
|
|
189
|
+
)
|
|
190
|
+
: joined(tail.parts, " "),
|
|
191
|
+
);
|
|
192
|
+
}
|
|
193
|
+
return { parts, pending: unique([...head.pending, ...tail.pending]) };
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
const statementItems = (
|
|
197
|
+
statements: readonly ts.Statement[],
|
|
198
|
+
routine: Routine,
|
|
199
|
+
): Item[] =>
|
|
200
|
+
statements.map((statement) => ({
|
|
201
|
+
origin: statement,
|
|
202
|
+
lower: () => lower(statement, routine),
|
|
203
|
+
}));
|
|
204
|
+
|
|
205
|
+
const lowerList = (
|
|
206
|
+
statements: readonly ts.Statement[],
|
|
207
|
+
loop: Target | undefined,
|
|
208
|
+
routine: Routine,
|
|
209
|
+
): List => lowerItems(statementItems(statements, routine), loop);
|
|
210
|
+
|
|
211
|
+
const settled = (pending: readonly Pending[], target: Target): Pending[] =>
|
|
212
|
+
pending.filter((item) => item.target !== target);
|
|
213
|
+
|
|
214
|
+
/** Declares the flags jumps to `target` set, before it runs, so each run of it starts with them clear. */
|
|
215
|
+
const declared = (target: Target, node: ts.Node, text: Part): Part => {
|
|
216
|
+
const flags = [target.breakFlag, target.continueFlag].filter(
|
|
217
|
+
(flag) => flag !== undefined,
|
|
218
|
+
);
|
|
219
|
+
if (!flags.length) {
|
|
220
|
+
return text;
|
|
221
|
+
}
|
|
222
|
+
return from(
|
|
223
|
+
node,
|
|
224
|
+
mapped`{ ${flags.map((flag) => `let ${flag}: boolean = false;`).join(" ")} ${text} }`,
|
|
225
|
+
);
|
|
226
|
+
};
|
|
227
|
+
|
|
228
|
+
const lower = (node: ts.Statement, routine: Routine): Lowered => {
|
|
229
|
+
const before = routine.changes;
|
|
230
|
+
const lowered = lowerStatement(node, routine);
|
|
231
|
+
if (routine.changes === before && !lowered.pending.length) {
|
|
232
|
+
return { text: copied(node), pending: [] };
|
|
233
|
+
}
|
|
234
|
+
return lowered;
|
|
235
|
+
};
|
|
236
|
+
|
|
237
|
+
const lowerStatement = (node: ts.Statement, routine: Routine): Lowered => {
|
|
238
|
+
if (ts.isLabeledStatement(node)) {
|
|
239
|
+
return labelled(node, routine);
|
|
240
|
+
}
|
|
241
|
+
if (ts.isIterationStatement(node, false)) {
|
|
242
|
+
return loop(node, [], routine);
|
|
243
|
+
}
|
|
244
|
+
if (ts.isSwitchStatement(node)) {
|
|
245
|
+
return switchStatement(node, [], routine);
|
|
246
|
+
}
|
|
247
|
+
if (ts.isBlock(node)) {
|
|
248
|
+
const list = lowerList(node.statements, undefined, routine);
|
|
249
|
+
return {
|
|
250
|
+
text: from(node, mapped`{ ${joined(list.parts, " ")} }`),
|
|
251
|
+
pending: list.pending,
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
if (ts.isIfStatement(node)) {
|
|
255
|
+
return ifStatement(node, routine);
|
|
256
|
+
}
|
|
257
|
+
if (ts.isTryStatement(node)) {
|
|
258
|
+
return node.finallyBlock
|
|
259
|
+
? finallyStatement(node, node.finallyBlock, routine)
|
|
260
|
+
: tryStatement(node, routine);
|
|
261
|
+
}
|
|
262
|
+
if (
|
|
263
|
+
ts.isBreakStatement(node) ||
|
|
264
|
+
ts.isContinueStatement(node) ||
|
|
265
|
+
ts.isReturnStatement(node)
|
|
266
|
+
) {
|
|
267
|
+
return jump(node, routine);
|
|
268
|
+
}
|
|
269
|
+
return { text: copied(node), pending: [] };
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
const labelled = (node: ts.LabeledStatement, routine: Routine): Lowered => {
|
|
273
|
+
routine.changes++;
|
|
274
|
+
const { labels, inner } = unlabelled(node);
|
|
275
|
+
if (ts.isIterationStatement(inner, false)) {
|
|
276
|
+
return loop(inner, labels, routine);
|
|
277
|
+
}
|
|
278
|
+
if (ts.isSwitchStatement(inner)) {
|
|
279
|
+
return switchStatement(inner, labels, routine);
|
|
280
|
+
}
|
|
281
|
+
const target: Target = { kind: "labelled", labels };
|
|
282
|
+
routine.stack.push(target);
|
|
283
|
+
const body = lower(inner, routine);
|
|
284
|
+
routine.stack.pop();
|
|
285
|
+
return {
|
|
286
|
+
text: declared(target, node, body.text),
|
|
287
|
+
pending: settled(body.pending, target),
|
|
288
|
+
};
|
|
289
|
+
};
|
|
290
|
+
|
|
291
|
+
/** The statement under a run of labels, and the labels. */
|
|
292
|
+
const unlabelled = (
|
|
293
|
+
node: ts.LabeledStatement,
|
|
294
|
+
): { labels: string[]; inner: ts.Statement } => {
|
|
295
|
+
if (!ts.isLabeledStatement(node.statement)) {
|
|
296
|
+
return { labels: [node.label.text], inner: node.statement };
|
|
297
|
+
}
|
|
298
|
+
const nested = unlabelled(node.statement);
|
|
299
|
+
return { labels: [node.label.text, ...nested.labels], inner: nested.inner };
|
|
300
|
+
};
|
|
301
|
+
|
|
302
|
+
const loop = (
|
|
303
|
+
node: ts.IterationStatement,
|
|
304
|
+
labels: readonly string[],
|
|
305
|
+
routine: Routine,
|
|
306
|
+
): Lowered => {
|
|
307
|
+
const before = routine.changes;
|
|
308
|
+
const target: Target = { kind: "loop", labels };
|
|
309
|
+
routine.stack.push(target);
|
|
310
|
+
const body = node.statement;
|
|
311
|
+
const list = lowerList(
|
|
312
|
+
ts.isBlock(body) ? body.statements : [body],
|
|
313
|
+
target,
|
|
314
|
+
routine,
|
|
315
|
+
);
|
|
316
|
+
routine.stack.pop();
|
|
317
|
+
if (routine.changes === before && !list.pending.length) {
|
|
318
|
+
return { text: copied(node), pending: [] };
|
|
319
|
+
}
|
|
320
|
+
const { source } = routine;
|
|
321
|
+
const reset = target.continueFlag ? `${target.continueFlag} = false; ` : "";
|
|
322
|
+
const text = mapped`${copiedRange(source, node.getStart(source), body.getStart(source))}${from(body, mapped`{ ${reset}${joined(list.parts, " ")} }`)}${copiedRange(source, body.end, node.end)}`;
|
|
323
|
+
return {
|
|
324
|
+
text: declared(target, node, text),
|
|
325
|
+
pending: settled(list.pending, target),
|
|
326
|
+
};
|
|
327
|
+
};
|
|
328
|
+
|
|
329
|
+
const ifStatement = (node: ts.IfStatement, routine: Routine): Lowered => {
|
|
330
|
+
const before = routine.changes;
|
|
331
|
+
const yes = lower(node.thenStatement, routine);
|
|
332
|
+
const no = node.elseStatement && lower(node.elseStatement, routine);
|
|
333
|
+
if (
|
|
334
|
+
routine.changes === before &&
|
|
335
|
+
!yes.pending.length &&
|
|
336
|
+
!no?.pending.length
|
|
337
|
+
) {
|
|
338
|
+
return { text: copied(node), pending: [] };
|
|
339
|
+
}
|
|
340
|
+
const { source } = routine;
|
|
341
|
+
const head = copiedRange(
|
|
342
|
+
source,
|
|
343
|
+
node.getStart(source),
|
|
344
|
+
node.thenStatement.getStart(source),
|
|
345
|
+
);
|
|
346
|
+
const otherwise =
|
|
347
|
+
node.elseStatement && no
|
|
348
|
+
? mapped`${copiedRange(source, node.thenStatement.end, node.elseStatement.getStart(source))}${no.text}`
|
|
349
|
+
: "";
|
|
350
|
+
return {
|
|
351
|
+
text: mapped`${head}${yes.text}${otherwise}`,
|
|
352
|
+
pending: unique([...yes.pending, ...(no?.pending ?? [])]),
|
|
353
|
+
};
|
|
354
|
+
};
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* A case that doesn't end in a jump runs on into the next, so its body is the chain of bodies up to
|
|
358
|
+
* one that does. Each case ends with the break Structured Text's CASE implies, or its return.
|
|
359
|
+
*/
|
|
360
|
+
const switchStatement = (
|
|
361
|
+
node: ts.SwitchStatement,
|
|
362
|
+
labels: readonly string[],
|
|
363
|
+
routine: Routine,
|
|
364
|
+
): Lowered => {
|
|
365
|
+
const before = routine.changes;
|
|
366
|
+
const target: Target = { kind: "switch", labels };
|
|
367
|
+
routine.stack.push(target);
|
|
368
|
+
const { source } = routine;
|
|
369
|
+
const bodies = node.caseBlock.clauses.map((clause) =>
|
|
370
|
+
unbraced(clause.statements),
|
|
371
|
+
);
|
|
372
|
+
const pending: Pending[] = [];
|
|
373
|
+
const clauses = node.caseBlock.clauses.map((clause, index) => {
|
|
374
|
+
const label = ts.isCaseClause(clause)
|
|
375
|
+
? mapped`case ${copied(clause.expression)}:`
|
|
376
|
+
: "default:";
|
|
377
|
+
if (!bodies[index]?.length) {
|
|
378
|
+
return from(clause, label);
|
|
379
|
+
}
|
|
380
|
+
const chain: (readonly ts.Statement[])[] = [];
|
|
381
|
+
for (const body of bodies.slice(index)) {
|
|
382
|
+
if (!body.length) {
|
|
383
|
+
continue;
|
|
384
|
+
}
|
|
385
|
+
chain.push(body);
|
|
386
|
+
if (isJump(body.at(-1))) {
|
|
387
|
+
break;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
if (chain.length > 1) {
|
|
391
|
+
routine.changes++;
|
|
392
|
+
}
|
|
393
|
+
const last = chain.at(-1) ?? [];
|
|
394
|
+
const end = last.at(-1);
|
|
395
|
+
const ending =
|
|
396
|
+
end && ts.isBreakStatement(end) && !end.label ? last.slice(0, -1) : last;
|
|
397
|
+
const pieces = [...chain.slice(0, -1), ending];
|
|
398
|
+
const items: Item[] =
|
|
399
|
+
pieces.length === 1
|
|
400
|
+
? statementItems(ending, routine)
|
|
401
|
+
: pieces.map((piece) => ({
|
|
402
|
+
origin: piece[0] ?? clause,
|
|
403
|
+
lower: () => {
|
|
404
|
+
const list = lowerList(piece, undefined, routine);
|
|
405
|
+
return {
|
|
406
|
+
text: from(clause, mapped`{ ${joined(list.parts, " ")} }`),
|
|
407
|
+
pending: list.pending,
|
|
408
|
+
};
|
|
409
|
+
},
|
|
410
|
+
}));
|
|
411
|
+
const list = lowerItems(items, undefined);
|
|
412
|
+
pending.push(...list.pending);
|
|
413
|
+
const returns =
|
|
414
|
+
end !== undefined &&
|
|
415
|
+
(ts.isReturnStatement(end) || ts.isThrowStatement(end)) &&
|
|
416
|
+
!list.pending.length;
|
|
417
|
+
const body = joined(list.parts, " ");
|
|
418
|
+
return from(
|
|
419
|
+
clause,
|
|
420
|
+
returns
|
|
421
|
+
? mapped`${label} { ${body} }`
|
|
422
|
+
: mapped`${label} { ${body} } break;`,
|
|
423
|
+
);
|
|
424
|
+
});
|
|
425
|
+
routine.stack.pop();
|
|
426
|
+
if (routine.changes === before && !pending.length) {
|
|
427
|
+
return { text: copied(node), pending: [] };
|
|
428
|
+
}
|
|
429
|
+
routine.changes++;
|
|
430
|
+
const text = mapped`${copiedRange(source, node.getStart(source), node.caseBlock.getStart(source))}{ ${joined(clauses, " ")} }`;
|
|
431
|
+
return {
|
|
432
|
+
text: declared(target, node, text),
|
|
433
|
+
pending: settled(unique(pending), target),
|
|
434
|
+
};
|
|
435
|
+
};
|
|
436
|
+
|
|
437
|
+
const tryStatement = (node: ts.TryStatement, routine: Routine): Lowered => {
|
|
438
|
+
const before = routine.changes;
|
|
439
|
+
const attempt = lower(node.tryBlock, routine);
|
|
440
|
+
const caught = node.catchClause && lower(node.catchClause.block, routine);
|
|
441
|
+
if (
|
|
442
|
+
routine.changes === before &&
|
|
443
|
+
!attempt.pending.length &&
|
|
444
|
+
!caught?.pending.length
|
|
445
|
+
) {
|
|
446
|
+
return { text: copied(node), pending: [] };
|
|
447
|
+
}
|
|
448
|
+
const { source } = routine;
|
|
449
|
+
const recovery =
|
|
450
|
+
node.catchClause && caught
|
|
451
|
+
? mapped`${copiedRange(source, node.tryBlock.end, node.catchClause.block.getStart(source))}${caught.text}`
|
|
452
|
+
: "";
|
|
453
|
+
return {
|
|
454
|
+
text: mapped`${copiedRange(source, node.getStart(source), node.tryBlock.getStart(source))}${attempt.text}${recovery}`,
|
|
455
|
+
pending: unique([...attempt.pending, ...(caught?.pending ?? [])]),
|
|
456
|
+
};
|
|
457
|
+
};
|
|
458
|
+
|
|
459
|
+
/**
|
|
460
|
+
* The finally block runs after the try and catch blocks however they end. A jump out of them is held
|
|
461
|
+
* until it has run; in an async routine a failure is caught, held and raised again after it.
|
|
462
|
+
*/
|
|
463
|
+
const finallyStatement = (
|
|
464
|
+
node: ts.TryStatement,
|
|
465
|
+
finallyBlock: ts.Block,
|
|
466
|
+
routine: Routine,
|
|
467
|
+
): Lowered => {
|
|
468
|
+
routine.changes++;
|
|
469
|
+
const target: Target = { kind: "finally", labels: [], region: "try" };
|
|
470
|
+
routine.stack.push(target);
|
|
471
|
+
const attempt = lowerList(node.tryBlock.statements, undefined, routine);
|
|
472
|
+
target.region = "catch";
|
|
473
|
+
const caught =
|
|
474
|
+
node.catchClause &&
|
|
475
|
+
lowerList(node.catchClause.block.statements, undefined, routine);
|
|
476
|
+
target.region = "finally";
|
|
477
|
+
const final = lowerList(finallyBlock.statements, undefined, routine);
|
|
478
|
+
routine.stack.pop();
|
|
479
|
+
|
|
480
|
+
const held = unique([...attempt.pending, ...(caught?.pending ?? [])]);
|
|
481
|
+
const guarded = routine.async
|
|
482
|
+
? caughtAttempt(node, attempt, caught, routine)
|
|
483
|
+
: // Synchronous scan code can't fail, so its catch block never runs.
|
|
484
|
+
{
|
|
485
|
+
parts: [mapped`{ ${joined(attempt.parts, " ")} }`],
|
|
486
|
+
rethrow: undefined,
|
|
487
|
+
};
|
|
488
|
+
const parts: Part[] = [...guarded.parts];
|
|
489
|
+
parts.push(mapped`{ ${joined(final.parts, " ")} }`);
|
|
490
|
+
|
|
491
|
+
// Held jumps Structured Text can now make go straight on; the rest stay held for the statements around.
|
|
492
|
+
const resumed: string[] = guarded.rethrow ? [guarded.rethrow] : [];
|
|
493
|
+
const still: Pending[] = [];
|
|
494
|
+
for (const item of held) {
|
|
495
|
+
const index = item.target ? routine.stack.indexOf(item.target) : -1;
|
|
496
|
+
const crossing = routine.stack.slice(index + 1);
|
|
497
|
+
if (!isNative(item.kind, item.target, crossing)) {
|
|
498
|
+
still.push(item);
|
|
499
|
+
continue;
|
|
500
|
+
}
|
|
501
|
+
if (item.kind === "return") {
|
|
502
|
+
const value = routine.result?.value;
|
|
503
|
+
resumed.push(`if (${item.flag}) { return${value ? ` ${value}` : ""}; }`);
|
|
504
|
+
continue;
|
|
505
|
+
}
|
|
506
|
+
resumed.push(`if (${item.flag}) { ${item.kind}; }`);
|
|
507
|
+
}
|
|
508
|
+
if (resumed.length) {
|
|
509
|
+
parts.push(
|
|
510
|
+
final.pending.length
|
|
511
|
+
? `if (!(${anyOf(final.pending)})) { ${resumed.join(" ")} }`
|
|
512
|
+
: resumed.join(" "),
|
|
513
|
+
);
|
|
514
|
+
}
|
|
515
|
+
return {
|
|
516
|
+
text: from(node, mapped`{ ${joined(parts, " ")} }`),
|
|
517
|
+
pending: unique([...still, ...final.pending]),
|
|
518
|
+
};
|
|
519
|
+
};
|
|
520
|
+
|
|
521
|
+
/** An async try whose failures, in its try block or its catch block, are held until finally has run. */
|
|
522
|
+
const caughtAttempt = (
|
|
523
|
+
node: ts.TryStatement,
|
|
524
|
+
attempt: List,
|
|
525
|
+
caught: List | undefined,
|
|
526
|
+
routine: Routine,
|
|
527
|
+
): { parts: Part[]; rethrow: string } => {
|
|
528
|
+
const throwing = routine.name("tsplcThrowing");
|
|
529
|
+
const error = routine.name("tsplcError");
|
|
530
|
+
routine.uses.add("errorCode");
|
|
531
|
+
const hold = (caught: string) =>
|
|
532
|
+
`${throwing} = true; ${error} = ${sdkNames.errorCode}(${caught});`;
|
|
533
|
+
const fallback = routine.name("tsplcCaught");
|
|
534
|
+
const clause = node.catchClause;
|
|
535
|
+
const binding = clause?.variableDeclaration
|
|
536
|
+
? copied(clause.variableDeclaration)
|
|
537
|
+
: fallback;
|
|
538
|
+
const recovery = (): Part => {
|
|
539
|
+
if (!clause || !caught) {
|
|
540
|
+
return hold(fallback);
|
|
541
|
+
}
|
|
542
|
+
// A failure in the catch block still runs finally, so it is caught again.
|
|
543
|
+
if (!containsAwaitOrThrow(clause.block)) {
|
|
544
|
+
return joined(caught.parts, " ");
|
|
545
|
+
}
|
|
546
|
+
const again = routine.name("tsplcCaught");
|
|
547
|
+
return mapped`try { ${joined(caught.parts, " ")} } catch (${again}) { ${hold(again)} }`;
|
|
548
|
+
};
|
|
549
|
+
return {
|
|
550
|
+
parts: [
|
|
551
|
+
`let ${throwing}: boolean = false; let ${error}: UDINT = 0;`,
|
|
552
|
+
mapped`try { ${joined(attempt.parts, " ")} } catch (${binding}) { ${recovery()} }`,
|
|
553
|
+
],
|
|
554
|
+
rethrow: `if (${throwing}) { throw ${error}; }`,
|
|
555
|
+
};
|
|
556
|
+
};
|
|
557
|
+
|
|
558
|
+
const jump = (
|
|
559
|
+
node: ts.BreakStatement | ts.ContinueStatement | ts.ReturnStatement,
|
|
560
|
+
routine: Routine,
|
|
561
|
+
): Lowered => {
|
|
562
|
+
const kind: JumpKind = ts.isBreakStatement(node)
|
|
563
|
+
? "break"
|
|
564
|
+
: ts.isContinueStatement(node)
|
|
565
|
+
? "continue"
|
|
566
|
+
: "return";
|
|
567
|
+
const label =
|
|
568
|
+
ts.isBreakStatement(node) || ts.isContinueStatement(node)
|
|
569
|
+
? node.label?.text
|
|
570
|
+
: undefined;
|
|
571
|
+
const index = targetIndex(kind, label, routine.stack);
|
|
572
|
+
if (index === undefined) {
|
|
573
|
+
return { text: copied(node), pending: [] };
|
|
574
|
+
}
|
|
575
|
+
const target = index >= 0 ? routine.stack[index] : undefined;
|
|
576
|
+
const crossing = routine.stack.slice(index + 1);
|
|
577
|
+
if (isNative(kind, target, crossing) && label === undefined) {
|
|
578
|
+
return { text: copied(node), pending: [] };
|
|
579
|
+
}
|
|
580
|
+
if (isNative(kind, target, crossing)) {
|
|
581
|
+
routine.changes++;
|
|
582
|
+
return { text: from(node, `${kind};`), pending: [] };
|
|
583
|
+
}
|
|
584
|
+
routine.changes++;
|
|
585
|
+
const flag = flagFor(kind, target, routine);
|
|
586
|
+
const value =
|
|
587
|
+
ts.isReturnStatement(node) && node.expression && routine.result?.value
|
|
588
|
+
? mapped`${routine.result.value} = ${copied(node.expression)}; `
|
|
589
|
+
: "";
|
|
590
|
+
const exit = innermostExit(crossing) === "loop" ? " break;" : "";
|
|
591
|
+
return {
|
|
592
|
+
text: from(node, mapped`{ ${flag} = true; ${value}${exit} }`),
|
|
593
|
+
pending: [{ kind, flag, target }],
|
|
594
|
+
};
|
|
595
|
+
};
|
|
596
|
+
|
|
597
|
+
const flagFor = (
|
|
598
|
+
kind: JumpKind,
|
|
599
|
+
target: Target | undefined,
|
|
600
|
+
routine: Routine,
|
|
601
|
+
): string => {
|
|
602
|
+
if (!target) {
|
|
603
|
+
routine.result ??= {
|
|
604
|
+
flag: routine.name("tsplcReturning"),
|
|
605
|
+
value: routine.resultType ? routine.name("tsplcResult") : undefined,
|
|
606
|
+
};
|
|
607
|
+
return routine.result.flag;
|
|
608
|
+
}
|
|
609
|
+
if (kind === "continue") {
|
|
610
|
+
target.continueFlag ??= routine.name("tsplcContinue");
|
|
611
|
+
return target.continueFlag;
|
|
612
|
+
}
|
|
613
|
+
target.breakFlag ??= routine.name("tsplcBreak");
|
|
614
|
+
return target.breakFlag;
|
|
615
|
+
};
|
|
616
|
+
|
|
617
|
+
type RoutineNode =
|
|
618
|
+
| ts.FunctionDeclaration
|
|
619
|
+
| ts.MethodDeclaration
|
|
620
|
+
| ts.GetAccessorDeclaration
|
|
621
|
+
| ts.SetAccessorDeclaration
|
|
622
|
+
| ts.ConstructorDeclaration
|
|
623
|
+
| ts.ArrowFunction
|
|
624
|
+
| ts.FunctionExpression;
|
|
625
|
+
|
|
626
|
+
const isRoutine = (node: ts.Node): node is RoutineNode =>
|
|
627
|
+
ts.isFunctionDeclaration(node) ||
|
|
628
|
+
ts.isMethodDeclaration(node) ||
|
|
629
|
+
ts.isGetAccessorDeclaration(node) ||
|
|
630
|
+
ts.isSetAccessorDeclaration(node) ||
|
|
631
|
+
ts.isConstructorDeclaration(node) ||
|
|
632
|
+
ts.isArrowFunction(node) ||
|
|
633
|
+
ts.isFunctionExpression(node);
|
|
634
|
+
|
|
635
|
+
/** The result type a return statement's value is held as, as written, or undefined for a routine returning nothing. */
|
|
636
|
+
const resultType = (
|
|
637
|
+
node: RoutineNode,
|
|
638
|
+
checker: ts.TypeChecker,
|
|
639
|
+
): string | undefined => {
|
|
640
|
+
if (ts.isConstructorDeclaration(node) || ts.isSetAccessorDeclaration(node)) {
|
|
641
|
+
return undefined;
|
|
642
|
+
}
|
|
643
|
+
const annotation = node.type;
|
|
644
|
+
const isAsync = node.modifiers?.some(
|
|
645
|
+
(modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword,
|
|
646
|
+
);
|
|
647
|
+
if (annotation) {
|
|
648
|
+
const inner =
|
|
649
|
+
isAsync &&
|
|
650
|
+
ts.isTypeReferenceNode(annotation) &&
|
|
651
|
+
annotation.typeName.getText() === "Promise"
|
|
652
|
+
? annotation.typeArguments?.[0]
|
|
653
|
+
: annotation;
|
|
654
|
+
if (!inner || inner.kind === ts.SyntaxKind.VoidKeyword) {
|
|
655
|
+
return undefined;
|
|
656
|
+
}
|
|
657
|
+
return inner.getText();
|
|
658
|
+
}
|
|
659
|
+
const signature = checker.getSignatureFromDeclaration(node);
|
|
660
|
+
if (!signature) {
|
|
661
|
+
return undefined;
|
|
662
|
+
}
|
|
663
|
+
const returns = checker.getReturnTypeOfSignature(signature);
|
|
664
|
+
const awaited = isAsync ? checker.getAwaitedType(returns) : returns;
|
|
665
|
+
if (!awaited || awaited.flags & ts.TypeFlags.Void) {
|
|
666
|
+
return undefined;
|
|
667
|
+
}
|
|
668
|
+
return checker.typeToString(awaited);
|
|
669
|
+
};
|
|
670
|
+
|
|
671
|
+
/** The SDK functions lowered code calls, by the names their imports give them. */
|
|
672
|
+
const sdkNames = {
|
|
673
|
+
defaultValue: "tsplcHeldDefault",
|
|
674
|
+
errorCode: "tsplcHeldErrorCode",
|
|
675
|
+
} as const;
|
|
676
|
+
|
|
677
|
+
const sdkModules: Record<keyof typeof sdkNames, string> = {
|
|
678
|
+
defaultValue: "@tsplc/compiler/types",
|
|
679
|
+
errorCode: "@tsplc/compiler/async",
|
|
680
|
+
};
|
|
681
|
+
|
|
682
|
+
/** Lowers the jumps, labels, fallthrough and finally blocks Structured Text can't express in every routine. */
|
|
683
|
+
export const lowerControlFlow = (program: ts.Program) => {
|
|
684
|
+
const checker = program.getTypeChecker();
|
|
685
|
+
const sources = new Map<string, Mapped>();
|
|
686
|
+
const diagnostics: Diagnostic[] = [];
|
|
687
|
+
for (const source of runtimeSources(program)) {
|
|
688
|
+
if (source.isDeclarationFile) {
|
|
689
|
+
continue;
|
|
690
|
+
}
|
|
691
|
+
const edits: Edit[] = [];
|
|
692
|
+
let counter = 0;
|
|
693
|
+
const uses = new Set<keyof typeof sdkNames>();
|
|
694
|
+
const name = (base: string) => `${base}${++counter}`;
|
|
695
|
+
const visit = (node: ts.Node): void => {
|
|
696
|
+
if (!isRoutine(node) || !node.body || !ts.isBlock(node.body)) {
|
|
697
|
+
ts.forEachChild(node, visit);
|
|
698
|
+
return;
|
|
699
|
+
}
|
|
700
|
+
const body = node.body;
|
|
701
|
+
const routine: Routine = {
|
|
702
|
+
source,
|
|
703
|
+
async: Boolean(
|
|
704
|
+
node.modifiers?.some(
|
|
705
|
+
(modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword,
|
|
706
|
+
),
|
|
707
|
+
),
|
|
708
|
+
stack: [],
|
|
709
|
+
resultType: resultType(node, checker),
|
|
710
|
+
changes: 0,
|
|
711
|
+
name,
|
|
712
|
+
uses,
|
|
713
|
+
};
|
|
714
|
+
const list = lowerList(body.statements, undefined, routine);
|
|
715
|
+
if (!routine.changes) {
|
|
716
|
+
ts.forEachChild(node, visit);
|
|
717
|
+
return;
|
|
718
|
+
}
|
|
719
|
+
const declarations: string[] = [];
|
|
720
|
+
if (routine.result) {
|
|
721
|
+
declarations.push(`let ${routine.result.flag}: boolean = false;`);
|
|
722
|
+
if (routine.result.value && routine.resultType) {
|
|
723
|
+
uses.add("defaultValue");
|
|
724
|
+
declarations.push(
|
|
725
|
+
`let ${routine.result.value}: ${routine.resultType} = ${sdkNames.defaultValue}<${routine.resultType}>();`,
|
|
726
|
+
);
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
edits.push({
|
|
730
|
+
start: body.getStart(source),
|
|
731
|
+
end: body.end,
|
|
732
|
+
text: from(
|
|
733
|
+
body,
|
|
734
|
+
mapped`{ ${declarations.join(" ")} ${joined(list.parts, "\n")} }`,
|
|
735
|
+
),
|
|
736
|
+
});
|
|
737
|
+
};
|
|
738
|
+
visit(source);
|
|
739
|
+
if (!edits.length) {
|
|
740
|
+
continue;
|
|
741
|
+
}
|
|
742
|
+
for (const used of uses) {
|
|
743
|
+
edits.push({
|
|
744
|
+
start: 0,
|
|
745
|
+
end: 0,
|
|
746
|
+
text: `import { ${used} as ${sdkNames[used]} } from "${sdkModules[used]}";\n`,
|
|
747
|
+
});
|
|
748
|
+
}
|
|
749
|
+
sources.set(source.fileName, edited(source, edits));
|
|
750
|
+
}
|
|
751
|
+
return { sources, diagnostics };
|
|
752
|
+
};
|