@tsplc/compiler 0.5.8 → 0.5.9
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 +8 -2
- package/dist/bun-runtime.js.map +3 -3
- package/dist/codesys.js +1567 -1507
- package/dist/codesys.js.map +13 -13
- package/dist/index.js +818 -681
- package/dist/index.js.map +17 -16
- package/dist/ir.js +13 -42
- package/dist/ir.js.map +6 -5
- package/dist/telemetry.js +8 -2
- package/dist/telemetry.js.map +3 -3
- package/package.json +9 -9
- package/src/codesys/emit.ts +2 -1
- package/src/codesys/engineering.ts +27 -12
- package/src/codesys/plan.ts +9 -22
- package/src/codesys/programs.ts +61 -1
- package/src/codesys/types.ts +34 -12
- package/src/frontend/async.ts +14 -8
- package/src/frontend/coroutines.ts +55 -16
- package/src/frontend/elaborate/expressions.ts +10 -2
- package/src/frontend/elaborate/filtered-arrays.ts +5 -5
- package/src/frontend/elaborate/index.ts +26 -3
- package/src/frontend/elaborate/model.ts +48 -1
- package/src/frontend/elaborate/references.ts +6 -6
- package/src/frontend/elaborate/specialize.ts +18 -4
- package/src/frontend/elaborate/storage.ts +3 -2
- package/src/frontend/generated-names.ts +95 -0
- package/src/frontend/promise-chains.ts +22 -8
- package/src/frontend/promises.ts +8 -10
- package/src/frontend/tasks.ts +8 -8
- package/src/frontend/typescript.ts +2 -2
- package/src/ir/identity.ts +9 -0
- package/src/ir/index.ts +8 -2
- package/src/ir/job-errors.ts +14 -0
- package/src/ir/share.ts +0 -52
|
@@ -429,10 +429,10 @@ export class FilteredArrays {
|
|
|
429
429
|
frame.emitter.open(mapped`if (${joined(guards, " && ")}) {`);
|
|
430
430
|
frame.emitter.append(arm.lines);
|
|
431
431
|
if (isTrue(arm.passes)) {
|
|
432
|
-
frame.emitter.line(`${result} = ${arm.node.
|
|
432
|
+
frame.emitter.line(`${result} = ${arm.node.reference};`);
|
|
433
433
|
} else if (arm.passes.kind !== "const") {
|
|
434
434
|
frame.emitter.line(
|
|
435
|
-
mapped`if (${this.dialect.condition(arm.passes, at)}) { ${result} = ${arm.node.
|
|
435
|
+
mapped`if (${this.dialect.condition(arm.passes, at)}) { ${result} = ${arm.node.reference}; }`,
|
|
436
436
|
);
|
|
437
437
|
}
|
|
438
438
|
frame.emitter.close();
|
|
@@ -483,7 +483,7 @@ export class FilteredArrays {
|
|
|
483
483
|
mapped`if (${this.dialect.condition(entry.present, at)}) {`,
|
|
484
484
|
);
|
|
485
485
|
}
|
|
486
|
-
const take = `${best} = ${entry.node.
|
|
486
|
+
const take = `${best} = ${entry.node.reference};`;
|
|
487
487
|
const rivals = union(before.map((rival) => rival.node))
|
|
488
488
|
.filter((rival) => rival !== entry.node)
|
|
489
489
|
.map((rival) => {
|
|
@@ -511,7 +511,7 @@ export class FilteredArrays {
|
|
|
511
511
|
...rivals
|
|
512
512
|
.filter(({ wins, lines }) => !isFalse(wins) || lines.length > 0)
|
|
513
513
|
.map(({ rival, wins, lines }) => ({
|
|
514
|
-
test: `${best} === ${rival.
|
|
514
|
+
test: `${best} === ${rival.reference}`,
|
|
515
515
|
body: () => {
|
|
516
516
|
frame.emitter.append(lines);
|
|
517
517
|
if (isTrue(wins)) {
|
|
@@ -583,7 +583,7 @@ export class FilteredArrays {
|
|
|
583
583
|
test: fromEnd
|
|
584
584
|
? mapped`${held} === ${position} || ${held} === ${position - nodes.length}`
|
|
585
585
|
: mapped`${held} === ${position}`,
|
|
586
|
-
body: () => frame.emitter.line(`${result} = ${item.
|
|
586
|
+
body: () => frame.emitter.line(`${result} = ${item.reference};`),
|
|
587
587
|
})),
|
|
588
588
|
);
|
|
589
589
|
return settled({
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { dirname, join, resolve } from "node:path";
|
|
1
|
+
import { dirname, join, relative, resolve } from "node:path";
|
|
2
2
|
import {
|
|
3
3
|
type Constant,
|
|
4
4
|
type Diagnostic,
|
|
5
5
|
error,
|
|
6
|
+
identityDigest,
|
|
6
7
|
type PlcModule,
|
|
7
8
|
type SourceSpan,
|
|
8
9
|
type TypeId,
|
|
@@ -241,7 +242,6 @@ export const lowerElaboration = (
|
|
|
241
242
|
/\\/g,
|
|
242
243
|
"/",
|
|
243
244
|
);
|
|
244
|
-
const rootModule = (item: Root) => `${directory}/${item.name}.ts`;
|
|
245
245
|
// Failures statements recorded before one escaped: often its cause, as a skipped declaration's name is then unknown.
|
|
246
246
|
let recorded = (): readonly SpecializeError[] => [];
|
|
247
247
|
|
|
@@ -250,7 +250,8 @@ export const lowerElaboration = (
|
|
|
250
250
|
const graph = captureGraph(entryFile, runtime, checker);
|
|
251
251
|
// Generic classes specialize per instance, through a checker that knows each one's type arguments.
|
|
252
252
|
const generics = new GenericTypes(checker);
|
|
253
|
-
const model = new Model(graph, generics.checker, program, entryFile);
|
|
253
|
+
const model = new Model(graph, generics.checker, program, entryFile, root);
|
|
254
|
+
const rootModule = rootModules(model.roots, directory, root);
|
|
254
255
|
const specializer = new Specializer(
|
|
255
256
|
model,
|
|
256
257
|
generics,
|
|
@@ -553,3 +554,25 @@ const findEntry = (
|
|
|
553
554
|
}
|
|
554
555
|
throw new Error(`${source.fileName} exports no function ${name}.`);
|
|
555
556
|
};
|
|
557
|
+
|
|
558
|
+
/**
|
|
559
|
+
* Each root's storage module. Roots in different modules can share a name, up to case, and would
|
|
560
|
+
* then share one module and its list; each of them is qualified by its own module instead.
|
|
561
|
+
*/
|
|
562
|
+
const rootModules = (
|
|
563
|
+
roots: readonly Root[],
|
|
564
|
+
directory: string,
|
|
565
|
+
projectRoot: string,
|
|
566
|
+
): ((item: Root) => string) => {
|
|
567
|
+
const counts = new Map<string, number>();
|
|
568
|
+
for (const item of roots) {
|
|
569
|
+
const key = item.name.toLowerCase();
|
|
570
|
+
counts.set(key, (counts.get(key) ?? 0) + 1);
|
|
571
|
+
}
|
|
572
|
+
return (item) => {
|
|
573
|
+
const shared = (counts.get(item.name.toLowerCase()) ?? 0) > 1;
|
|
574
|
+
const module = relative(projectRoot, item.file).replace(/\\/g, "/");
|
|
575
|
+
const name = shared ? `${item.name}_${identityDigest(module)}` : item.name;
|
|
576
|
+
return `${directory}/${name}.ts`;
|
|
577
|
+
};
|
|
578
|
+
};
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { relative } from "node:path";
|
|
2
|
+
import { identityDigest } from "@tsplc/compiler/ir";
|
|
1
3
|
import ts from "typescript";
|
|
2
4
|
import type {
|
|
3
5
|
CapturedGraph,
|
|
@@ -73,6 +75,11 @@ export interface Root {
|
|
|
73
75
|
|
|
74
76
|
export interface ModelNode {
|
|
75
77
|
id: number;
|
|
78
|
+
/**
|
|
79
|
+
* The id a reference to the object holds at runtime: a digest of where setup put it, so an
|
|
80
|
+
* object added elsewhere changes no stored reference across an online change.
|
|
81
|
+
*/
|
|
82
|
+
reference: number;
|
|
76
83
|
captured: CapturedNode;
|
|
77
84
|
/** The declared type where the object is stored; undefined for functions and services. */
|
|
78
85
|
type?: ts.Type;
|
|
@@ -84,14 +91,20 @@ export interface ModelNode {
|
|
|
84
91
|
export class Model {
|
|
85
92
|
readonly nodes: ModelNode[];
|
|
86
93
|
readonly roots: Root[] = [];
|
|
94
|
+
private readonly projectRoot: string;
|
|
87
95
|
|
|
88
96
|
constructor(
|
|
89
97
|
readonly graph: CapturedGraph,
|
|
90
98
|
readonly checker: ts.TypeChecker,
|
|
91
99
|
readonly program: ts.Program,
|
|
92
100
|
entry: string,
|
|
101
|
+
projectRoot: string,
|
|
93
102
|
) {
|
|
94
|
-
this.nodes = graph.nodes.map((captured, id) => ({
|
|
103
|
+
this.nodes = graph.nodes.map((captured, id) => ({
|
|
104
|
+
id,
|
|
105
|
+
reference: id,
|
|
106
|
+
captured,
|
|
107
|
+
}));
|
|
95
108
|
// Dependencies own what they build before the entry module's instances refer to it.
|
|
96
109
|
const ordered = [
|
|
97
110
|
...graph.bindings.filter((binding) => binding.file !== entry),
|
|
@@ -115,6 +128,40 @@ export class Model {
|
|
|
115
128
|
checker.getTypeAtLocation(declaration.name),
|
|
116
129
|
);
|
|
117
130
|
}
|
|
131
|
+
this.projectRoot = projectRoot;
|
|
132
|
+
this.assignReferences();
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Where setup put an object, as generated names and reference ids are made from: its root's
|
|
137
|
+
* module and its path from there. Undefined for an object no root owns.
|
|
138
|
+
*/
|
|
139
|
+
identity(node: ModelNode): string | undefined {
|
|
140
|
+
return (
|
|
141
|
+
node.owner &&
|
|
142
|
+
`${relative(this.projectRoot, node.owner.root.file).replace(/\\/g, "/")}:${tsPath(node.owner)}`
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Gives each object setup put somewhere its reference id, from its identity. */
|
|
147
|
+
private assignReferences(): void {
|
|
148
|
+
const taken = new Map<number, ModelNode>();
|
|
149
|
+
for (const node of this.nodes) {
|
|
150
|
+
const identity = this.identity(node);
|
|
151
|
+
if (!identity || !node.owner) {
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
const reference =
|
|
155
|
+
Number.parseInt(identityDigest(identity), 16) & 0x7fffffff;
|
|
156
|
+
const other = taken.get(reference);
|
|
157
|
+
if (other?.owner) {
|
|
158
|
+
throw new Error(
|
|
159
|
+
`${tsPath(other.owner)} and ${tsPath(node.owner)} would hold the same reference id; rename one of them.`,
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
taken.set(reference, node);
|
|
163
|
+
node.reference = reference;
|
|
164
|
+
}
|
|
118
165
|
}
|
|
119
166
|
|
|
120
167
|
/** The object a captured value refers to; undefined for a primitive. */
|
|
@@ -55,7 +55,7 @@ export const referenceIndex = (value: Value): string | Mapped | undefined => {
|
|
|
55
55
|
return value.index;
|
|
56
56
|
}
|
|
57
57
|
if (value.kind === "static" && referable(value.node)) {
|
|
58
|
-
return String(value.node.
|
|
58
|
+
return String(value.node.reference);
|
|
59
59
|
}
|
|
60
60
|
if (value.kind === "const" && value.value === undefined) {
|
|
61
61
|
return "-1";
|
|
@@ -75,9 +75,9 @@ const optionsOf = (value: Value): readonly ModelNode[] => {
|
|
|
75
75
|
const absentOf = (value: Value): boolean =>
|
|
76
76
|
value.kind === "choice" ? value.optional : value.kind === "const";
|
|
77
77
|
|
|
78
|
-
/** Objects without repeats, in the order
|
|
78
|
+
/** Objects without repeats, in the order of their reference ids, so the code over them is the same every build. */
|
|
79
79
|
export const union = (nodes: readonly ModelNode[]): ModelNode[] =>
|
|
80
|
-
[...new Set(nodes)].sort((left, right) => left.
|
|
80
|
+
[...new Set(nodes)].sort((left, right) => left.reference - right.reference);
|
|
81
81
|
|
|
82
82
|
const maybeAbsent = (type: ts.Type): boolean => parts(type).some(isAbsent);
|
|
83
83
|
|
|
@@ -220,7 +220,7 @@ export class References {
|
|
|
220
220
|
return mapped`(${choice.index} === ${other.index})`;
|
|
221
221
|
case "static":
|
|
222
222
|
return choice.options.includes(other.node)
|
|
223
|
-
? mapped`(${choice.index} === ${other.node.
|
|
223
|
+
? mapped`(${choice.index} === ${other.node.reference})`
|
|
224
224
|
: false;
|
|
225
225
|
case "const":
|
|
226
226
|
return other.value === undefined && choice.optional
|
|
@@ -399,7 +399,7 @@ export class References {
|
|
|
399
399
|
arms
|
|
400
400
|
.filter((arm) => arm.lines.length > 0)
|
|
401
401
|
.map((arm) => ({
|
|
402
|
-
test: mapped`${choice.index} === ${arm.option.
|
|
402
|
+
test: mapped`${choice.index} === ${arm.option.reference}`,
|
|
403
403
|
body: () => frame.emitter.append(arm.lines),
|
|
404
404
|
})),
|
|
405
405
|
);
|
|
@@ -479,7 +479,7 @@ export class References {
|
|
|
479
479
|
return constant(undefined);
|
|
480
480
|
}
|
|
481
481
|
const test = (option: ModelNode): Mapped =>
|
|
482
|
-
mapped`${choice.index} === ${option.
|
|
482
|
+
mapped`${choice.index} === ${option.reference}`;
|
|
483
483
|
const known = first.value;
|
|
484
484
|
if (
|
|
485
485
|
known.kind === "const" &&
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
// biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
|
|
2
|
+
import { identityDigest } from "@tsplc/compiler/ir";
|
|
2
3
|
import ts from "typescript";
|
|
3
4
|
import { from, joined, type Mapped, mapped } from "../positions";
|
|
4
5
|
import { DialectText } from "./dialect";
|
|
@@ -277,7 +278,7 @@ export class Specializer implements RoutineTable {
|
|
|
277
278
|
referents: this.resultReferents(known),
|
|
278
279
|
};
|
|
279
280
|
}
|
|
280
|
-
const name = this.routineName(declaration, self);
|
|
281
|
+
const name = this.routineName(declaration, self, keys);
|
|
281
282
|
this.specialized.set(key, name);
|
|
282
283
|
if (ts.isArrowFunction(declaration) && !ts.isBlock(declaration.body)) {
|
|
283
284
|
frame.emitter.origin = declaration.body;
|
|
@@ -369,9 +370,15 @@ export class Specializer implements RoutineTable {
|
|
|
369
370
|
);
|
|
370
371
|
}
|
|
371
372
|
|
|
373
|
+
/**
|
|
374
|
+
* A specialized routine's name: its class and method, and for an instance or a known argument a
|
|
375
|
+
* digest of which. Numbering specializations in the order they were made renamed them when an
|
|
376
|
+
* instance was added before, which renamed the routines a job calls, and so its code.
|
|
377
|
+
*/
|
|
372
378
|
private routineName(
|
|
373
379
|
declaration: FunctionLike,
|
|
374
380
|
self: ModelNode | undefined,
|
|
381
|
+
keys: readonly string[],
|
|
375
382
|
): string {
|
|
376
383
|
const own =
|
|
377
384
|
declaration.name && ts.isIdentifier(declaration.name)
|
|
@@ -386,9 +393,16 @@ export class Specializer implements RoutineTable {
|
|
|
386
393
|
: undefined;
|
|
387
394
|
const owner =
|
|
388
395
|
self?.captured.kind === "instance" ? self.captured.name : undefined;
|
|
389
|
-
const
|
|
396
|
+
const named = [owner, own ?? variable ?? "callback"]
|
|
390
397
|
.filter(Boolean)
|
|
391
398
|
.join("_");
|
|
399
|
+
const instance = self && this.model.identity(self);
|
|
400
|
+
const specialized = Boolean(instance) || keys.length > 0;
|
|
401
|
+
// A callback's key holds its source position; a name mustn't move with an edit above it.
|
|
402
|
+
const stable = keys.map((key) => key.replace(/fn:[^,|\]}]*/g, "fn"));
|
|
403
|
+
const base = specialized
|
|
404
|
+
? `${named}_${identityDigest([instance ?? "", ...stable].join("\0"))}`
|
|
405
|
+
: named;
|
|
392
406
|
const name = unusedName(base, (candidate) =>
|
|
393
407
|
this.routineNames.has(candidate),
|
|
394
408
|
);
|
|
@@ -750,7 +764,7 @@ const declarationKey = (declaration: ts.Node): string =>
|
|
|
750
764
|
const valueKey = (value: Value): string => {
|
|
751
765
|
switch (value.kind) {
|
|
752
766
|
case "static":
|
|
753
|
-
return `#${value.node.
|
|
767
|
+
return `#${value.node.reference}`;
|
|
754
768
|
case "const":
|
|
755
769
|
return `=${String(value.value)}`;
|
|
756
770
|
case "function":
|
|
@@ -762,7 +776,7 @@ const valueKey = (value: Value): string => {
|
|
|
762
776
|
case "code":
|
|
763
777
|
return "code";
|
|
764
778
|
case "choice":
|
|
765
|
-
return `ref(${value.options.map((option) => option.
|
|
779
|
+
return `ref(${value.options.map((option) => option.reference).join(",")})${value.optional ? "?" : ""}`;
|
|
766
780
|
case "masked":
|
|
767
781
|
return `some[${value.entries.map((entry) => `${valueKey(entry.item)}:${valueKey(entry.present)}`).join(",")}]${value.order ? `by ${valueKey(value.order)}` : ""}`;
|
|
768
782
|
case "counted":
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
// biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
|
|
2
|
+
import { basename } from "node:path";
|
|
2
3
|
import ts from "typescript";
|
|
3
4
|
import type { CapturedPrimitive, CapturedValue } from "./capture-protocol";
|
|
4
5
|
import type { EntryImports } from "./imports";
|
|
@@ -134,7 +135,7 @@ export class Storage {
|
|
|
134
135
|
return {
|
|
135
136
|
references: this.model.nodes.flatMap((node) => {
|
|
136
137
|
const path = referable(node) ? this.storagePlace(node) : undefined;
|
|
137
|
-
return path === undefined ? [] : [{ id: node.
|
|
138
|
+
return path === undefined ? [] : [{ id: node.reference, path }];
|
|
138
139
|
}),
|
|
139
140
|
referenceFields: this.references.flatMap(({ holder, name }) => {
|
|
140
141
|
const path = this.storagePlace(holder);
|
|
@@ -244,7 +245,7 @@ export class Storage {
|
|
|
244
245
|
}
|
|
245
246
|
|
|
246
247
|
private namespace(root: Root): string {
|
|
247
|
-
const pascal = pascalCase(root.
|
|
248
|
+
const pascal = pascalCase(basename(this.rootModule(root), ".ts"));
|
|
248
249
|
const name = this.typeNames.has(pascal) ? `${pascal}Root` : pascal;
|
|
249
250
|
this.imports.namespaces.set(name, this.rootModule(root));
|
|
250
251
|
return name;
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { relative } from "node:path";
|
|
2
|
+
import { identityDigest } from "@tsplc/compiler/ir";
|
|
3
|
+
import ts from "typescript";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Names for what lowering generates, each a fixed function of the source node it stands for: its
|
|
7
|
+
* module, the declarations around it, and its ordinal among the nodes with the same key in the
|
|
8
|
+
* innermost one. An edit elsewhere then never renames it, so an online change finds its state
|
|
9
|
+
* where it left it; counting generated objects across the program renamed them all.
|
|
10
|
+
*/
|
|
11
|
+
export class GeneratedNames {
|
|
12
|
+
constructor(private readonly root: string) {}
|
|
13
|
+
|
|
14
|
+
/** `base` followed by the digest of `node`'s identity. */
|
|
15
|
+
name(base: string, node: ts.Node): string {
|
|
16
|
+
return `${base}_${identityDigest(this.identity(node))}`;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
identity(node: ts.Node): string {
|
|
20
|
+
const source = node.getSourceFile();
|
|
21
|
+
const module = relative(this.root, source.fileName).replace(/\\/g, "/");
|
|
22
|
+
const scopes = enclosingDeclarations(node);
|
|
23
|
+
const scope = scopes.at(-1)?.node ?? source;
|
|
24
|
+
const key = nodeKey(node, source);
|
|
25
|
+
const ordinal = sameKey(scope, key, source).indexOf(node);
|
|
26
|
+
return [
|
|
27
|
+
module,
|
|
28
|
+
...scopes.map((declaration) => declaration.name),
|
|
29
|
+
`${key}#${ordinal}`,
|
|
30
|
+
].join("\0");
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** A call is told apart by its callee, a declaration by its name, anything else by its syntax. */
|
|
35
|
+
const nodeKey = (node: ts.Node, source: ts.SourceFile): string => {
|
|
36
|
+
if (ts.isCallExpression(node)) {
|
|
37
|
+
return `call ${node.expression.getText(source)}`;
|
|
38
|
+
}
|
|
39
|
+
const name = declarationName(node);
|
|
40
|
+
return name === undefined
|
|
41
|
+
? ts.SyntaxKind[node.kind]
|
|
42
|
+
: `${ts.SyntaxKind[node.kind]} ${name}`;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
/** The nodes under `scope` with `key`, in source order. */
|
|
46
|
+
const sameKey = (
|
|
47
|
+
scope: ts.Node,
|
|
48
|
+
key: string,
|
|
49
|
+
source: ts.SourceFile,
|
|
50
|
+
): ts.Node[] => {
|
|
51
|
+
const found: ts.Node[] = [];
|
|
52
|
+
const visit = (node: ts.Node) => {
|
|
53
|
+
if (nodeKey(node, source) === key) {
|
|
54
|
+
found.push(node);
|
|
55
|
+
}
|
|
56
|
+
ts.forEachChild(node, visit);
|
|
57
|
+
};
|
|
58
|
+
ts.forEachChild(scope, visit);
|
|
59
|
+
return found;
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
const declarationName = (node: ts.Node): string | undefined => {
|
|
63
|
+
if (
|
|
64
|
+
(ts.isClassDeclaration(node) ||
|
|
65
|
+
ts.isFunctionDeclaration(node) ||
|
|
66
|
+
ts.isMethodDeclaration(node) ||
|
|
67
|
+
ts.isPropertyDeclaration(node) ||
|
|
68
|
+
ts.isGetAccessorDeclaration(node) ||
|
|
69
|
+
ts.isSetAccessorDeclaration(node) ||
|
|
70
|
+
ts.isVariableDeclaration(node) ||
|
|
71
|
+
ts.isInterfaceDeclaration(node) ||
|
|
72
|
+
ts.isTypeAliasDeclaration(node)) &&
|
|
73
|
+
node.name &&
|
|
74
|
+
(ts.isIdentifier(node.name) || ts.isStringLiteral(node.name))
|
|
75
|
+
) {
|
|
76
|
+
return node.name.text;
|
|
77
|
+
}
|
|
78
|
+
if (ts.isConstructorDeclaration(node)) {
|
|
79
|
+
return "constructor";
|
|
80
|
+
}
|
|
81
|
+
return undefined;
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
/** The named declarations around `node`, outermost first. */
|
|
85
|
+
const enclosingDeclarations = (
|
|
86
|
+
node: ts.Node,
|
|
87
|
+
): { name: string; node: ts.Node }[] => {
|
|
88
|
+
const parent = node.parent;
|
|
89
|
+
if (!parent || ts.isSourceFile(parent)) {
|
|
90
|
+
return [];
|
|
91
|
+
}
|
|
92
|
+
const name = declarationName(parent);
|
|
93
|
+
const outer = enclosingDeclarations(parent);
|
|
94
|
+
return name === undefined ? outer : [...outer, { name, node: parent }];
|
|
95
|
+
};
|
|
@@ -508,7 +508,7 @@ class PromiseChain {
|
|
|
508
508
|
const links = this.chain.links;
|
|
509
509
|
let lowered = {
|
|
510
510
|
call: this.addHelper(
|
|
511
|
-
|
|
511
|
+
context.names.name("tsplcPromiseOperation", this.chain.root),
|
|
512
512
|
helperFinish(this.rootInvocation, this.rootType),
|
|
513
513
|
this.rootType,
|
|
514
514
|
),
|
|
@@ -522,13 +522,14 @@ class PromiseChain {
|
|
|
522
522
|
for (const [index, link] of links.entries()) {
|
|
523
523
|
lowered = this.link(link, lowered, {
|
|
524
524
|
terminal: detached && index === links.length - 1,
|
|
525
|
+
index,
|
|
525
526
|
});
|
|
526
527
|
}
|
|
527
528
|
const values = this.params.map((value) => value.expression).join(",");
|
|
528
529
|
if (!detached) {
|
|
529
530
|
return lowered.call.replace(`(${this.args})`, `(${values})`);
|
|
530
531
|
}
|
|
531
|
-
const site =
|
|
532
|
+
const site = context.names.name("tsplcPromiseSite", this.chain.root);
|
|
532
533
|
const callable = lowered.call.slice(0, lowered.call.indexOf("("));
|
|
533
534
|
const scope = classOwner ?? source;
|
|
534
535
|
context.append(
|
|
@@ -547,16 +548,22 @@ class PromiseChain {
|
|
|
547
548
|
private link(
|
|
548
549
|
link: ChainLink,
|
|
549
550
|
previous: Callback,
|
|
550
|
-
{ terminal }: { terminal: boolean },
|
|
551
|
+
{ terminal, index }: { terminal: boolean; index: number },
|
|
551
552
|
): Callback {
|
|
552
553
|
const fulfilled =
|
|
553
554
|
link.kind === "then"
|
|
554
|
-
? this.callback(
|
|
555
|
+
? this.callback(
|
|
556
|
+
link.handlers[0],
|
|
557
|
+
previous.type,
|
|
558
|
+
"promiseResult",
|
|
559
|
+
`${index}Fulfilled`,
|
|
560
|
+
)
|
|
555
561
|
: undefined;
|
|
556
562
|
const rejected = this.callback(
|
|
557
563
|
link.handlers[link.kind === "catch" ? 0 : 1],
|
|
558
564
|
"UDINT",
|
|
559
565
|
"tsplcErrorCode(promiseError)",
|
|
566
|
+
`${index}Rejected`,
|
|
560
567
|
);
|
|
561
568
|
if (!fulfilled && !rejected) {
|
|
562
569
|
return previous;
|
|
@@ -570,7 +577,7 @@ class PromiseChain {
|
|
|
570
577
|
}
|
|
571
578
|
return {
|
|
572
579
|
call: this.addHelper(
|
|
573
|
-
`tsplcPromiseChain${this.
|
|
580
|
+
this.context.names.name(`tsplcPromiseChain${index}`, this.chain.root),
|
|
574
581
|
linkBody(previous, { fulfilled, rejected, terminal }),
|
|
575
582
|
output,
|
|
576
583
|
),
|
|
@@ -582,10 +589,12 @@ class PromiseChain {
|
|
|
582
589
|
}
|
|
583
590
|
|
|
584
591
|
/** How the chain calls a callback, declaring a helper for it when it needs one. */
|
|
592
|
+
/** `slot` tells the callbacks of one chain apart: its link and whether it fulfils or rejects. */
|
|
585
593
|
private callback(
|
|
586
594
|
expression: ts.Expression | undefined,
|
|
587
595
|
inputType: string,
|
|
588
596
|
input: string,
|
|
597
|
+
slot: string,
|
|
589
598
|
): Callback | undefined {
|
|
590
599
|
if (
|
|
591
600
|
!expression ||
|
|
@@ -615,6 +624,7 @@ class PromiseChain {
|
|
|
615
624
|
inputType,
|
|
616
625
|
input,
|
|
617
626
|
aggregate,
|
|
627
|
+
slot,
|
|
618
628
|
});
|
|
619
629
|
}
|
|
620
630
|
const names = new Map(this.captureNames);
|
|
@@ -629,7 +639,10 @@ class PromiseChain {
|
|
|
629
639
|
parameter,
|
|
630
640
|
inputType,
|
|
631
641
|
});
|
|
632
|
-
const name =
|
|
642
|
+
const name = context.names.name(
|
|
643
|
+
`tsplcPromiseHandler${slot}`,
|
|
644
|
+
this.chain.root,
|
|
645
|
+
);
|
|
633
646
|
const body = this.replaceNames(declaration.body, names);
|
|
634
647
|
const takesInput = Boolean(parameter && inputType !== "void");
|
|
635
648
|
const handlerParams = [
|
|
@@ -677,7 +690,8 @@ class PromiseChain {
|
|
|
677
690
|
inputType,
|
|
678
691
|
input,
|
|
679
692
|
aggregate,
|
|
680
|
-
|
|
693
|
+
slot,
|
|
694
|
+
}: { inputType: string; input: string; aggregate: boolean; slot: string },
|
|
681
695
|
): Callback {
|
|
682
696
|
const { context, source } = this;
|
|
683
697
|
const result = declaration.type;
|
|
@@ -704,7 +718,7 @@ class PromiseChain {
|
|
|
704
718
|
}
|
|
705
719
|
return {
|
|
706
720
|
call: this.addHelper(
|
|
707
|
-
`tsplcPromiseNamed${
|
|
721
|
+
context.names.name(`tsplcPromiseNamed${slot}`, this.chain.root),
|
|
708
722
|
callbackType === "void"
|
|
709
723
|
? `${name}(${takesInput ? "promiseInput" : ""});return;`
|
|
710
724
|
: `return ${name}(${takesInput ? "promiseInput" : ""});`,
|
package/src/frontend/promises.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
|
|
2
2
|
import { type Diagnostic, error } from "@tsplc/compiler/ir";
|
|
3
3
|
import ts from "typescript";
|
|
4
|
+
import { GeneratedNames } from "./generated-names";
|
|
4
5
|
import { importSpecifier, runtimeSources } from "./module-graph";
|
|
5
6
|
import {
|
|
6
7
|
type Edit,
|
|
@@ -34,8 +35,8 @@ export interface PromiseContext {
|
|
|
34
35
|
/** Whether a node names the SDK declaration `name`. */
|
|
35
36
|
namesSdk(node: ts.Node, name: string): boolean;
|
|
36
37
|
fail(node: ts.Node, message: string): never;
|
|
37
|
-
/**
|
|
38
|
-
|
|
38
|
+
/** Names for generated declarations, from the source node each stands for. */
|
|
39
|
+
readonly names: GeneratedNames;
|
|
39
40
|
/** Adds generated code to the end of a module, or to a class, mapped to the node it was made for. */
|
|
40
41
|
append(
|
|
41
42
|
scope: ts.SourceFile | ts.ClassDeclaration,
|
|
@@ -58,6 +59,7 @@ export const lowerPromises = (
|
|
|
58
59
|
program: ts.Program,
|
|
59
60
|
sdk: string,
|
|
60
61
|
positions: Positions,
|
|
62
|
+
root: string,
|
|
61
63
|
): PromiseLowering => {
|
|
62
64
|
const files = runtimeSources(program).filter(
|
|
63
65
|
(source) => !source.isDeclarationFile,
|
|
@@ -67,6 +69,7 @@ export const lowerPromises = (
|
|
|
67
69
|
sdk,
|
|
68
70
|
positions,
|
|
69
71
|
files,
|
|
72
|
+
new GeneratedNames(root),
|
|
70
73
|
);
|
|
71
74
|
const diagnostics: Diagnostic[] = [];
|
|
72
75
|
const runtimeBlocks = new Map<string, { kind: "mailbox" }>();
|
|
@@ -216,7 +219,7 @@ function cancelScope(
|
|
|
216
219
|
),
|
|
217
220
|
);
|
|
218
221
|
}
|
|
219
|
-
const name =
|
|
222
|
+
const name = rewrite.names.name("tsplcCancelScope", node);
|
|
220
223
|
const member = ts.isClassDeclaration(scope);
|
|
221
224
|
const body = (rewrite.sites.get(scope) ?? [])
|
|
222
225
|
.map((site) => `${member ? "this." : ""}${site}.cancel();`)
|
|
@@ -243,13 +246,12 @@ class PromiseRewrite implements PromiseContext {
|
|
|
243
246
|
private readonly aliases = new Map<ts.Node, string>();
|
|
244
247
|
private readonly typeImports = new Map<ts.SourceFile, Set<string>>();
|
|
245
248
|
private readonly imported = new Set<ts.SourceFile>();
|
|
246
|
-
private nextName = 0;
|
|
247
|
-
|
|
248
249
|
constructor(
|
|
249
250
|
readonly checker: ts.TypeChecker,
|
|
250
251
|
private readonly sdk: string,
|
|
251
252
|
private readonly positions: Positions,
|
|
252
253
|
files: readonly ts.SourceFile[],
|
|
254
|
+
readonly names: GeneratedNames,
|
|
253
255
|
) {
|
|
254
256
|
for (const source of files) {
|
|
255
257
|
for (const statement of source.statements) {
|
|
@@ -285,10 +287,6 @@ class PromiseRewrite implements PromiseContext {
|
|
|
285
287
|
throw new SemanticError(this.diagnostic(node, message));
|
|
286
288
|
}
|
|
287
289
|
|
|
288
|
-
sequence(): number {
|
|
289
|
-
return this.nextName++;
|
|
290
|
-
}
|
|
291
|
-
|
|
292
290
|
append(
|
|
293
291
|
scope: ts.SourceFile | ts.ClassDeclaration,
|
|
294
292
|
origin: ts.Node,
|
|
@@ -344,7 +342,7 @@ class PromiseRewrite implements PromiseContext {
|
|
|
344
342
|
|
|
345
343
|
/** Exports a type from the module that declares it, so other modules can name it. */
|
|
346
344
|
private declareAlias(node: ts.TypeNode): string {
|
|
347
|
-
const alias =
|
|
345
|
+
const alias = this.names.name("TsplcPromiseType", node);
|
|
348
346
|
this.aliases.set(node, alias);
|
|
349
347
|
this.append(
|
|
350
348
|
node.getSourceFile(),
|
package/src/frontend/tasks.ts
CHANGED
|
@@ -95,7 +95,7 @@ function taskDefinition(
|
|
|
95
95
|
fn,
|
|
96
96
|
declaration,
|
|
97
97
|
);
|
|
98
|
-
const worker =
|
|
98
|
+
const worker = context.names.name("tsplcTaskWorker", declaration);
|
|
99
99
|
const receiver = `this.${worker}`;
|
|
100
100
|
const site = taskSite(
|
|
101
101
|
declaration.name.text,
|
|
@@ -143,7 +143,7 @@ function cooperativeDefinition(
|
|
|
143
143
|
}));
|
|
144
144
|
// An async method runs as members of the owner itself; a helper runs in its own block.
|
|
145
145
|
const method = context.methods.get(symbol);
|
|
146
|
-
const worker =
|
|
146
|
+
const worker = context.names.name("tsplcCooperativeWorker", declaration);
|
|
147
147
|
const receiver = method ? "this" : `this.${worker}`;
|
|
148
148
|
const site = cooperativeSite(
|
|
149
149
|
declaration.name.text,
|
|
@@ -216,8 +216,8 @@ function placeSite(
|
|
|
216
216
|
visit(owner);
|
|
217
217
|
return;
|
|
218
218
|
}
|
|
219
|
-
const block =
|
|
220
|
-
const entry =
|
|
219
|
+
const block = context.names.name(siteClass, declaration);
|
|
220
|
+
const entry = context.names.name("tsplcContinuation", declaration);
|
|
221
221
|
extra.push(
|
|
222
222
|
from(
|
|
223
223
|
declaration,
|
|
@@ -275,9 +275,9 @@ function backgroundDefinition(
|
|
|
275
275
|
fn,
|
|
276
276
|
declaration,
|
|
277
277
|
);
|
|
278
|
-
const mailbox =
|
|
279
|
-
const worker =
|
|
280
|
-
const entry =
|
|
278
|
+
const mailbox = context.names.name("TsplcMailbox", declaration);
|
|
279
|
+
const worker = context.names.name("tsplcWorker", declaration);
|
|
280
|
+
const entry = context.names.name("tsplcBackground", declaration);
|
|
281
281
|
const requestType = `{ready:BOOL;${params.map((p) => `${p.field}:${p.type}`).join(";")}}`;
|
|
282
282
|
const snapshotType = `{valid:BOOL;busy:BOOL;done:BOOL;cancelRequested:BOOL;error:UDINT;result:${valueType}}`;
|
|
283
283
|
const emptySnapshot = `{valid:true,busy:this.pending || this.active,done:this.completed,cancelRequested:this.cancelRequested,error:this.failure,result:${copyValue("this.value", valueAggregate)}}`;
|
|
@@ -456,7 +456,7 @@ function workTypes(
|
|
|
456
456
|
};
|
|
457
457
|
}
|
|
458
458
|
// Another module's types are named through the aliases its coroutine exports.
|
|
459
|
-
const prefix = aliasPrefix(fn);
|
|
459
|
+
const prefix = aliasPrefix(context.names, fn);
|
|
460
460
|
const params = fn.parameters.map((node, index) =>
|
|
461
461
|
parameter(node, index, `${prefix}Argument${index}`),
|
|
462
462
|
);
|
|
@@ -236,11 +236,11 @@ export function analyze(options: FrontendOptions): FrontendResult {
|
|
|
236
236
|
if (!apply(lowerConstFunctions(program, positions))) {
|
|
237
237
|
return { diagnostics };
|
|
238
238
|
}
|
|
239
|
-
const promises = lowerPromises(program, sdk, positions);
|
|
239
|
+
const promises = lowerPromises(program, sdk, positions, dirname(filename));
|
|
240
240
|
if (!apply(promises)) {
|
|
241
241
|
return { diagnostics };
|
|
242
242
|
}
|
|
243
|
-
const lowering = lowerAsync(program, sdk, positions);
|
|
243
|
+
const lowering = lowerAsync(program, sdk, positions, dirname(filename));
|
|
244
244
|
for (const [key, value] of promises.runtimeBlocks) {
|
|
245
245
|
lowering.blocks.set(key, value);
|
|
246
246
|
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Generated names are a fixed function of the identity of what they stand for, so the same source
|
|
5
|
+
* names the same things whatever else changes: an online change then finds every piece of state
|
|
6
|
+
* where it left it. A digest keeps the name short and its identity out of the PLC's namespace.
|
|
7
|
+
*/
|
|
8
|
+
export const identityDigest = (identity: string): string =>
|
|
9
|
+
createHash("sha256").update(identity).digest("hex").slice(0, 8);
|