@tsplc/compiler 0.3.0 → 0.4.0
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/codesys.js +48 -26
- package/dist/codesys.js.map +5 -5
- package/dist/elaborate-capture.js +22 -3
- package/dist/elaborate-capture.js.map +4 -4
- package/dist/index.js +489 -355
- package/dist/index.js.map +9 -8
- package/dist/retain.js +8 -0
- package/dist/retain.js.map +10 -0
- package/package.json +14 -9
- package/src/codesys/global-lists.ts +18 -16
- package/src/codesys/global-names.ts +3 -3
- package/src/codesys/storage.ts +44 -9
- package/src/frontend/elaborate/capture-protocol.ts +5 -0
- package/src/frontend/elaborate/capture.ts +22 -1
- package/src/frontend/elaborate/expressions.ts +4 -2
- package/src/frontend/elaborate/index.ts +29 -4
- package/src/frontend/elaborate/retention.ts +206 -0
- package/src/frontend/elaborate/storage.ts +1 -1
- package/stdlib/retain.ts +2 -0
- package/types/retain.d.ts +6 -0
package/dist/retain.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../stdlib/retain.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"/** `retain` as a program running under Bun sees it: retention is the PLC's, so the value passes through. */\nexport const retain = <T>(value: T): T => value;\n"
|
|
6
|
+
],
|
|
7
|
+
"mappings": ";AACO,IAAM,SAAS,CAAI,UAAgB;",
|
|
8
|
+
"debugId": "A03AEA5B694A74C464756E2164756E21",
|
|
9
|
+
"names": []
|
|
10
|
+
}
|
package/package.json
CHANGED
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
"url": "git+https://github.com/rip-technologies/tsplc.git",
|
|
18
18
|
"directory": "packages/compiler"
|
|
19
19
|
},
|
|
20
|
-
"version": "0.
|
|
20
|
+
"version": "0.4.0",
|
|
21
21
|
"type": "module",
|
|
22
22
|
"exports": {
|
|
23
23
|
".": {
|
|
@@ -50,6 +50,11 @@
|
|
|
50
50
|
"bun": "./stdlib/telemetry.ts",
|
|
51
51
|
"default": "./dist/telemetry.js"
|
|
52
52
|
},
|
|
53
|
+
"./retain": {
|
|
54
|
+
"types": "./types/retain.d.ts",
|
|
55
|
+
"bun": "./stdlib/retain.ts",
|
|
56
|
+
"default": "./dist/retain.js"
|
|
57
|
+
},
|
|
53
58
|
"./math": {
|
|
54
59
|
"types": "./stdlib/math.ts",
|
|
55
60
|
"bun": "./stdlib/math.ts",
|
|
@@ -96,17 +101,17 @@
|
|
|
96
101
|
"bun": ">=1.4.3"
|
|
97
102
|
},
|
|
98
103
|
"dependencies": {
|
|
99
|
-
"@tsplc/agent": "0.
|
|
100
|
-
"@tsplc/build": "0.
|
|
101
|
-
"@tsplc/config": "0.
|
|
102
|
-
"@tsplc/debug": "0.
|
|
103
|
-
"@tsplc/opcua": "0.
|
|
104
|
-
"@tsplc/typegen": "0.
|
|
104
|
+
"@tsplc/agent": "0.4.0",
|
|
105
|
+
"@tsplc/build": "0.4.0",
|
|
106
|
+
"@tsplc/config": "0.4.0",
|
|
107
|
+
"@tsplc/debug": "0.4.0",
|
|
108
|
+
"@tsplc/opcua": "0.4.0",
|
|
109
|
+
"@tsplc/typegen": "0.4.0",
|
|
105
110
|
"typescript": "6.0.3",
|
|
106
111
|
"zod": "4.3.6",
|
|
107
112
|
"@types/bun": "1.4.2",
|
|
108
|
-
"@tsplc/server": "0.
|
|
109
|
-
"@tsplc/iec": "0.
|
|
113
|
+
"@tsplc/server": "0.4.0",
|
|
114
|
+
"@tsplc/iec": "0.4.0"
|
|
110
115
|
},
|
|
111
116
|
"bin": {
|
|
112
117
|
"tsplc": "./dist/cli.js"
|
|
@@ -72,25 +72,27 @@ export function emitGlobalLists(
|
|
|
72
72
|
const lines = [
|
|
73
73
|
...(publish ? ["{attribute 'linkalways'}"] : []),
|
|
74
74
|
"{attribute 'qualified_only'}",
|
|
75
|
-
globalSections[group.storage],
|
|
76
75
|
];
|
|
77
|
-
for (const
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
76
|
+
for (const section of group.sections) {
|
|
77
|
+
lines.push(globalSections[section.storage]);
|
|
78
|
+
for (const item of section.variables) {
|
|
79
|
+
const field = required(fields.get(item.id));
|
|
80
|
+
references.set(item.id, `${name}.${field}`);
|
|
81
|
+
if (published.has(item.id)) {
|
|
82
|
+
lines.push(
|
|
83
|
+
` {attribute 'symbol' := '${item.exposure ? "read" : "readwrite"}'}`,
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
mappings.push({
|
|
87
|
+
path: `${name}.st`,
|
|
88
|
+
line: lines.length + 1,
|
|
89
|
+
span: item.span,
|
|
90
|
+
});
|
|
91
|
+
const initial = globalInitializer(symbols, section.storage, item);
|
|
92
|
+
lines.push(` ${field} : ${targetTypes.name(item.type)}${initial};`);
|
|
84
93
|
}
|
|
85
|
-
|
|
86
|
-
path: `${name}.st`,
|
|
87
|
-
line: lines.length + 1,
|
|
88
|
-
span: item.span,
|
|
89
|
-
});
|
|
90
|
-
const initial = globalInitializer(symbols, group.storage, item);
|
|
91
|
-
lines.push(` ${field} : ${targetTypes.name(item.type)}${initial};`);
|
|
94
|
+
lines.push("END_VAR");
|
|
92
95
|
}
|
|
93
|
-
lines.push("END_VAR");
|
|
94
96
|
objects.push({
|
|
95
97
|
id: group.id,
|
|
96
98
|
kind: "globalList",
|
|
@@ -33,17 +33,17 @@ export const planGlobalNames = (
|
|
|
33
33
|
const splitByStorage = globalLists.some(
|
|
34
34
|
(other) =>
|
|
35
35
|
other.module === group.module &&
|
|
36
|
-
other.
|
|
36
|
+
other.kind !== group.kind &&
|
|
37
37
|
hasExports(other),
|
|
38
38
|
);
|
|
39
39
|
// Exported lists are the program's public interface. Private storage stays generated.
|
|
40
40
|
const name = hasExports(group)
|
|
41
41
|
? names.allocate(
|
|
42
42
|
pascalCase(
|
|
43
|
-
splitByStorage ? `${group.module}-${group.
|
|
43
|
+
splitByStorage ? `${group.module}-${group.kind}` : group.module,
|
|
44
44
|
),
|
|
45
45
|
)
|
|
46
|
-
: names.allocateObject("GVL", `${group.module}_${group.
|
|
46
|
+
: names.allocateObject("GVL", `${group.module}_${group.kind}`);
|
|
47
47
|
const fields = new Names();
|
|
48
48
|
for (const name of blockNames.values()) {
|
|
49
49
|
fields.reserve(name);
|
package/src/codesys/storage.ts
CHANGED
|
@@ -8,10 +8,21 @@ import {
|
|
|
8
8
|
/** Which global list of its module a variable goes in. */
|
|
9
9
|
export type GlobalStorage = "constants" | "retained" | "state";
|
|
10
10
|
|
|
11
|
+
/** A section of a global list: the variables one `VAR_GLOBAL` qualifier declares. */
|
|
12
|
+
interface GlobalSection {
|
|
13
|
+
storage: GlobalStorage;
|
|
14
|
+
variables: Variable[];
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* A module's constants, or its mutable storage. Retained and ordinary state share one list in
|
|
19
|
+
* separate sections, so retaining a variable never changes the path it is published at.
|
|
20
|
+
*/
|
|
11
21
|
interface GlobalList {
|
|
12
22
|
id: string;
|
|
13
23
|
module: string;
|
|
14
|
-
|
|
24
|
+
kind: Exclude<GlobalStorage, "retained">;
|
|
25
|
+
sections: GlobalSection[];
|
|
15
26
|
variables: Variable[];
|
|
16
27
|
}
|
|
17
28
|
|
|
@@ -26,6 +37,12 @@ export const moduleFile = (variable: Variable): string =>
|
|
|
26
37
|
export const moduleName = (variable: Variable): string =>
|
|
27
38
|
basename(moduleFile(variable)).replace(/\.[^.]+$/, "");
|
|
28
39
|
|
|
40
|
+
const sectionOrder: readonly GlobalStorage[] = [
|
|
41
|
+
"constants",
|
|
42
|
+
"state",
|
|
43
|
+
"retained",
|
|
44
|
+
];
|
|
45
|
+
|
|
29
46
|
const globalStorage = (
|
|
30
47
|
variable: Variable,
|
|
31
48
|
retainedVariables: ReadonlySet<string>,
|
|
@@ -75,23 +92,41 @@ export function storageLayout(core: VerifiedCoreModule) {
|
|
|
75
92
|
.map((variable) => variable.id),
|
|
76
93
|
);
|
|
77
94
|
|
|
78
|
-
const groups = new Map<string, GlobalList
|
|
95
|
+
const groups = new Map<string, Omit<GlobalList, "variables">>();
|
|
79
96
|
for (const variable of core.variables) {
|
|
80
97
|
if (variable.storage === "input" || variable.storage === "output") {
|
|
81
98
|
continue;
|
|
82
99
|
}
|
|
83
100
|
const storage = globalStorage(variable, retainedVariables);
|
|
84
|
-
const
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
101
|
+
const kind = storage === "constants" ? "constants" : "state";
|
|
102
|
+
const id = `${moduleFile(variable)}:${kind}`;
|
|
103
|
+
const group = groups.get(id) ?? {
|
|
104
|
+
id,
|
|
105
|
+
module: moduleName(variable),
|
|
106
|
+
kind,
|
|
107
|
+
sections: [],
|
|
108
|
+
};
|
|
109
|
+
groups.set(id, group);
|
|
110
|
+
const section = group.sections.find((item) => item.storage === storage);
|
|
111
|
+
if (section) {
|
|
112
|
+
section.variables.push(variable);
|
|
113
|
+
} else {
|
|
114
|
+
group.sections.push({ storage, variables: [variable] });
|
|
89
115
|
}
|
|
90
|
-
group.variables.push(variable);
|
|
91
116
|
}
|
|
92
117
|
return {
|
|
93
118
|
retainedBlocks,
|
|
94
119
|
retainedVariables,
|
|
95
|
-
globalLists: [...groups.values()]
|
|
120
|
+
globalLists: [...groups.values()].map((group): GlobalList => {
|
|
121
|
+
// Ordinary state comes first, so retaining a variable leaves the others' lines in place.
|
|
122
|
+
const sections = sectionOrder.flatMap((storage) =>
|
|
123
|
+
group.sections.filter((section) => section.storage === storage),
|
|
124
|
+
);
|
|
125
|
+
return {
|
|
126
|
+
...group,
|
|
127
|
+
sections,
|
|
128
|
+
variables: sections.flatMap((section) => section.variables),
|
|
129
|
+
};
|
|
130
|
+
}),
|
|
96
131
|
};
|
|
97
132
|
}
|
|
@@ -72,6 +72,8 @@ export const capturedGraphSchema = z
|
|
|
72
72
|
value: capturedValueSchema,
|
|
73
73
|
}),
|
|
74
74
|
),
|
|
75
|
+
/** The objects setup passed to `retain`. */
|
|
76
|
+
retained: z.array(z.number().int().nonnegative()),
|
|
75
77
|
})
|
|
76
78
|
.superRefine((graph, context) => {
|
|
77
79
|
const references = [
|
|
@@ -86,6 +88,9 @@ export const capturedGraphSchema = z
|
|
|
86
88
|
return [];
|
|
87
89
|
}),
|
|
88
90
|
];
|
|
91
|
+
for (const id of graph.retained) {
|
|
92
|
+
references.push({ kind: "node", id });
|
|
93
|
+
}
|
|
89
94
|
for (const value of references) {
|
|
90
95
|
if (value.kind === "node" && value.id >= graph.nodes.length) {
|
|
91
96
|
context.addIssue({
|
|
@@ -75,6 +75,12 @@ plugin({
|
|
|
75
75
|
export const onTelemetry = () => () => {};`,
|
|
76
76
|
loader: "js",
|
|
77
77
|
}));
|
|
78
|
+
// Retention belongs to storage, so setup notes each object it retains for the compiler.
|
|
79
|
+
build.module("@tsplc/compiler/retain", () => ({
|
|
80
|
+
contents:
|
|
81
|
+
"export const retain = (value) => globalThis.__tsplcRetain(value);",
|
|
82
|
+
loader: "js",
|
|
83
|
+
}));
|
|
78
84
|
build.module("@tsplc/compiler/async", () => ({
|
|
79
85
|
contents: `export const createServiceClient = () => globalThis.__tsplcService([]);
|
|
80
86
|
const unsupported = (name) => () => { throw new Error(name + " cannot run during PLC setup."); };
|
|
@@ -84,6 +90,16 @@ plugin({
|
|
|
84
90
|
},
|
|
85
91
|
});
|
|
86
92
|
(globalThis as { __tsplcService?: unknown }).__tsplcService = service;
|
|
93
|
+
/** Objects setup passed to `retain`. A retained primitive has no identity; the compiler finds those in the source. */
|
|
94
|
+
const retainedObjects = new Set<object>();
|
|
95
|
+
(globalThis as { __tsplcRetain?: unknown }).__tsplcRetain = (
|
|
96
|
+
value: unknown,
|
|
97
|
+
) => {
|
|
98
|
+
if (typeof value === "object" && value !== null) {
|
|
99
|
+
retainedObjects.add(value);
|
|
100
|
+
}
|
|
101
|
+
return value;
|
|
102
|
+
};
|
|
87
103
|
|
|
88
104
|
/** The bindings each runtime module exports for capture, as `bindings` above adds them. */
|
|
89
105
|
interface Registry {
|
|
@@ -188,7 +204,7 @@ const capture = (value: unknown, where: string): CapturedValue => {
|
|
|
188
204
|
return { kind: "node", id };
|
|
189
205
|
};
|
|
190
206
|
|
|
191
|
-
const graph: CapturedGraph = { nodes, bindings: [] };
|
|
207
|
+
const graph: CapturedGraph = { nodes, bindings: [], retained: [] };
|
|
192
208
|
for (const [file, registry] of modules) {
|
|
193
209
|
for (const [name, read] of Object.entries(registry.values)) {
|
|
194
210
|
let value: unknown;
|
|
@@ -206,4 +222,9 @@ for (const [file, registry] of modules) {
|
|
|
206
222
|
graph.bindings.push({ file, name, value: capture(value, name) });
|
|
207
223
|
}
|
|
208
224
|
}
|
|
225
|
+
// A retained object no binding reaches is stored nowhere, so it has no id.
|
|
226
|
+
graph.retained = [...retainedObjects].flatMap((value) => {
|
|
227
|
+
const id = ids.get(value);
|
|
228
|
+
return id === undefined ? [] : [id];
|
|
229
|
+
});
|
|
209
230
|
writeFileSync(process.argv[3]!, JSON.stringify(graph));
|
|
@@ -485,7 +485,7 @@ export class ExpressionSpecializer {
|
|
|
485
485
|
: this.table(node, at);
|
|
486
486
|
return {
|
|
487
487
|
kind: "code",
|
|
488
|
-
text: mapped`${text}[${this.dialect.code(index,
|
|
488
|
+
text: mapped`${text}[${this.dialect.code(index, node.type && recordTypes(node.type)?.key)}]`,
|
|
489
489
|
declared,
|
|
490
490
|
place: true,
|
|
491
491
|
};
|
|
@@ -495,9 +495,11 @@ export class ExpressionSpecializer {
|
|
|
495
495
|
object.declared &&
|
|
496
496
|
(this.model.elementType(object.declared) ??
|
|
497
497
|
recordTypes(object.declared)?.value);
|
|
498
|
+
// A key setup fixed reads as a number; an enum-keyed record takes its enum's member.
|
|
499
|
+
const key = object.declared && recordTypes(object.declared)?.key;
|
|
498
500
|
return {
|
|
499
501
|
kind: "code",
|
|
500
|
-
text: mapped`${object.text}[${this.dialect.code(index,
|
|
502
|
+
text: mapped`${object.text}[${this.dialect.code(index, key)}]`,
|
|
501
503
|
declared,
|
|
502
504
|
place: object.place,
|
|
503
505
|
iec: object.elementIec,
|
|
@@ -22,6 +22,7 @@ import type { CapturedValue } from "./capture-protocol.ts";
|
|
|
22
22
|
import { captureGraph } from "./graph.ts";
|
|
23
23
|
import { importPath } from "./imports.ts";
|
|
24
24
|
import { Model, type Root } from "./model.ts";
|
|
25
|
+
import { Retention, retainedDeclarations } from "./retention.ts";
|
|
25
26
|
import { closingBrace, Specializer } from "./specialize.ts";
|
|
26
27
|
import { setterName } from "./storage.ts";
|
|
27
28
|
import { SpecializeError } from "./values.ts";
|
|
@@ -230,6 +231,7 @@ export const lowerElaboration = (
|
|
|
230
231
|
const rootModule = (item: Root) => `${directory}/${item.name}.ts`;
|
|
231
232
|
|
|
232
233
|
try {
|
|
234
|
+
const declarations = retainedDeclarations(runtime, checker, sdk);
|
|
233
235
|
const graph = captureGraph(entryFile, runtime);
|
|
234
236
|
const model = new Model(graph, checker, program, entryFile);
|
|
235
237
|
const specializer = new Specializer(
|
|
@@ -251,9 +253,14 @@ export const lowerElaboration = (
|
|
|
251
253
|
}
|
|
252
254
|
|
|
253
255
|
// Writing the globals declares the types they use, so they come before the types module.
|
|
256
|
+
const retention = new Retention(model, specializer.storage, declarations);
|
|
254
257
|
const globals = new Map<Root, Mapped[]>();
|
|
255
258
|
for (const item of specializer.storage.roots) {
|
|
256
|
-
globals.set(item, storageGlobals(specializer, item));
|
|
259
|
+
globals.set(item, storageGlobals(specializer, retention, item));
|
|
260
|
+
}
|
|
261
|
+
const [unretained] = retention.unclaimed();
|
|
262
|
+
if (unretained) {
|
|
263
|
+
throw unretained;
|
|
257
264
|
}
|
|
258
265
|
const typesFile = `${directory}/types.ts`;
|
|
259
266
|
const typeImports = (file: string) => [
|
|
@@ -349,9 +356,14 @@ export const lowerElaboration = (
|
|
|
349
356
|
* The globals of a root's storage module: one per stored field of a record or instance, or the
|
|
350
357
|
* root itself. Other modules can't assign an imported binding, so each global comes with a setter.
|
|
351
358
|
*/
|
|
352
|
-
const storageGlobals = (
|
|
359
|
+
const storageGlobals = (
|
|
360
|
+
specializer: Specializer,
|
|
361
|
+
retention: Retention,
|
|
362
|
+
item: Root,
|
|
363
|
+
): Mapped[] => {
|
|
353
364
|
const { model, checker, layouts, storage, initializers } = specializer;
|
|
354
365
|
const lines: Mapped[] = [];
|
|
366
|
+
const retained: string[] = [];
|
|
355
367
|
const global = (
|
|
356
368
|
name: string,
|
|
357
369
|
layout: string,
|
|
@@ -359,8 +371,13 @@ const storageGlobals = (specializer: Specializer, item: Root): Mapped[] => {
|
|
|
359
371
|
declaration: ts.Node | undefined,
|
|
360
372
|
) => {
|
|
361
373
|
const origin = declaration ?? item.declaration;
|
|
374
|
+
const kept = retention.global(item, storage.flattened(item) ? name : null);
|
|
375
|
+
if (kept) {
|
|
376
|
+
retained.push(name);
|
|
377
|
+
}
|
|
378
|
+
const value = kept ? `retain(${initial})` : initial;
|
|
362
379
|
lines.push(
|
|
363
|
-
from(origin, `export let ${name}: ${layout} = ${
|
|
380
|
+
from(origin, `export let ${name}: ${layout} = ${value};`),
|
|
364
381
|
from(
|
|
365
382
|
origin,
|
|
366
383
|
`export function ${setterName(name)}(value: ${layout}): void { ${name} = value; }`,
|
|
@@ -422,7 +439,15 @@ const storageGlobals = (specializer: Specializer, item: Root): Mapped[] => {
|
|
|
422
439
|
);
|
|
423
440
|
}
|
|
424
441
|
}
|
|
425
|
-
return
|
|
442
|
+
return retained.length
|
|
443
|
+
? [
|
|
444
|
+
from(
|
|
445
|
+
item.declaration,
|
|
446
|
+
'import { retain } from "@tsplc/compiler/types";',
|
|
447
|
+
),
|
|
448
|
+
...lines,
|
|
449
|
+
]
|
|
450
|
+
: lines;
|
|
426
451
|
};
|
|
427
452
|
|
|
428
453
|
/** A plain module reduced to the types other modules may import from it. */
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import ts from "typescript";
|
|
2
|
+
import { namesSdk } from "../sdk.ts";
|
|
3
|
+
import type { CapturedValue } from "./capture-protocol.ts";
|
|
4
|
+
import {
|
|
5
|
+
children,
|
|
6
|
+
type Model,
|
|
7
|
+
type ModelNode,
|
|
8
|
+
type Owner,
|
|
9
|
+
type Root,
|
|
10
|
+
tsPath,
|
|
11
|
+
} from "./model.ts";
|
|
12
|
+
import type { Storage } from "./storage.ts";
|
|
13
|
+
import { SpecializeError } from "./values.ts";
|
|
14
|
+
|
|
15
|
+
/** A declaration whose initializer retains a primitive: a module binding or a class field. */
|
|
16
|
+
type RetainedDeclaration = ts.VariableDeclaration | ts.PropertyDeclaration;
|
|
17
|
+
|
|
18
|
+
/** Whether a value of `type` has no identity setup can mark, so retaining it needs its declaration. */
|
|
19
|
+
const primitive = (type: ts.Type): boolean => {
|
|
20
|
+
if (type.isUnion()) {
|
|
21
|
+
return type.types.every(primitive);
|
|
22
|
+
}
|
|
23
|
+
if (type.isIntersection()) {
|
|
24
|
+
return type.types.some(primitive);
|
|
25
|
+
}
|
|
26
|
+
return !(type.flags & (ts.TypeFlags.Object | ts.TypeFlags.NonPrimitive));
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
/** The declaration a `retain` call initializes, when it retains a primitive there. */
|
|
30
|
+
const retainedDeclaration = (
|
|
31
|
+
call: ts.CallExpression,
|
|
32
|
+
): RetainedDeclaration | undefined => {
|
|
33
|
+
const parent = call.parent;
|
|
34
|
+
if (ts.isPropertyDeclaration(parent) && parent.initializer === call) {
|
|
35
|
+
return parent;
|
|
36
|
+
}
|
|
37
|
+
if (
|
|
38
|
+
ts.isVariableDeclaration(parent) &&
|
|
39
|
+
parent.initializer === call &&
|
|
40
|
+
ts.isVariableDeclarationList(parent.parent) &&
|
|
41
|
+
ts.isVariableStatement(parent.parent.parent) &&
|
|
42
|
+
ts.isSourceFile(parent.parent.parent.parent)
|
|
43
|
+
) {
|
|
44
|
+
return parent;
|
|
45
|
+
}
|
|
46
|
+
return undefined;
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The declarations that retain a primitive. Setup marks the objects it retains as it runs, but a
|
|
51
|
+
* primitive has no identity, so its declaration is found here, in the source. Checked before setup
|
|
52
|
+
* runs, so a `retain` setup can't evaluate is reported where it is written.
|
|
53
|
+
*/
|
|
54
|
+
export const retainedDeclarations = (
|
|
55
|
+
sources: readonly ts.SourceFile[],
|
|
56
|
+
checker: ts.TypeChecker,
|
|
57
|
+
sdk: string,
|
|
58
|
+
): ReadonlySet<ts.Node> => {
|
|
59
|
+
const found = new Set<ts.Node>();
|
|
60
|
+
const visit = (node: ts.Node): void => {
|
|
61
|
+
if (
|
|
62
|
+
ts.isCallExpression(node) &&
|
|
63
|
+
namesSdk(checker, sdk, node.expression, "retain")
|
|
64
|
+
) {
|
|
65
|
+
const symbol = checker.getSymbolAtLocation(node.expression);
|
|
66
|
+
if (!symbol || !(symbol.flags & ts.SymbolFlags.Alias)) {
|
|
67
|
+
throw new SpecializeError(
|
|
68
|
+
node,
|
|
69
|
+
'Setup runs under Bun, where the global retain has no value: import { retain } from "@tsplc/compiler/retain".',
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
const [argument] = node.arguments;
|
|
73
|
+
if (argument && primitive(checker.getTypeAtLocation(argument))) {
|
|
74
|
+
const declaration = retainedDeclaration(node);
|
|
75
|
+
if (!declaration) {
|
|
76
|
+
throw new SpecializeError(
|
|
77
|
+
node,
|
|
78
|
+
"A primitive is retained only as a module let's or a class field's initializer; retain the record that holds it.",
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
found.add(declaration);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
ts.forEachChild(node, visit);
|
|
85
|
+
};
|
|
86
|
+
for (const source of sources) {
|
|
87
|
+
visit(source);
|
|
88
|
+
}
|
|
89
|
+
return found;
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Which storage globals are `RETAIN`. CODESYS retains whole variables, so a global is retained when
|
|
94
|
+
* it holds anything setup retained: an object it passed to `retain`, or a field or binding whose
|
|
95
|
+
* declaration retains a primitive. Every retained thing must end up in a retained global.
|
|
96
|
+
*/
|
|
97
|
+
export class Retention {
|
|
98
|
+
private readonly objects: ReadonlySet<number>;
|
|
99
|
+
private readonly claimed = new Set<number | ts.Node>();
|
|
100
|
+
|
|
101
|
+
constructor(
|
|
102
|
+
private readonly model: Model,
|
|
103
|
+
private readonly storage: Storage,
|
|
104
|
+
private readonly declarations: ReadonlySet<ts.Node>,
|
|
105
|
+
) {
|
|
106
|
+
this.objects = new Set(model.graph.retained);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Whether the global holding a root, or one field of a flattened root, is retained. */
|
|
110
|
+
global(root: Root, field: string | null): boolean {
|
|
111
|
+
const node = this.model.node(root.value);
|
|
112
|
+
if (field === null || !node) {
|
|
113
|
+
return this.claim(
|
|
114
|
+
this.declarations.has(root.declaration) ? root.declaration : null,
|
|
115
|
+
this.holds(root.value, { root, steps: [] }),
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
const member =
|
|
119
|
+
node.captured.kind === "instance"
|
|
120
|
+
? this.model.member(this.model.classOf(node), field)
|
|
121
|
+
: undefined;
|
|
122
|
+
const value: CapturedValue = (node.captured.kind === "instance" ||
|
|
123
|
+
node.captured.kind === "object"
|
|
124
|
+
? node.captured.fields[field]
|
|
125
|
+
: undefined) ?? { kind: "undefined" };
|
|
126
|
+
const held = this.holds(value, {
|
|
127
|
+
root,
|
|
128
|
+
steps: [{ kind: "field", name: field }],
|
|
129
|
+
});
|
|
130
|
+
const declared = member && this.declarations.has(member) ? member : null;
|
|
131
|
+
const whole = this.objects.has(node.id) ? node.id : null;
|
|
132
|
+
return [this.claim(declared, held), this.claim(whole, held)].some(Boolean);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Each retained thing no retained global holds, as the error that reports it. */
|
|
136
|
+
unclaimed(): Error[] {
|
|
137
|
+
const objects = [...this.objects]
|
|
138
|
+
.filter((id) => !this.claimed.has(id))
|
|
139
|
+
.map((id) => {
|
|
140
|
+
const owner = this.model.nodes[id]?.owner;
|
|
141
|
+
return new Error(
|
|
142
|
+
`${owner ? tsPath(owner) : "A retained object"}: retain retains nothing the PLC stores; retain state scan code writes, or exported data.`,
|
|
143
|
+
);
|
|
144
|
+
});
|
|
145
|
+
const declarations = [...this.declarations]
|
|
146
|
+
.filter((declaration) => !this.claimed.has(declaration))
|
|
147
|
+
.map(
|
|
148
|
+
(declaration) =>
|
|
149
|
+
new SpecializeError(
|
|
150
|
+
declaration,
|
|
151
|
+
"retain retains nothing the PLC stores; retain state scan code writes, or exported data.",
|
|
152
|
+
),
|
|
153
|
+
);
|
|
154
|
+
return [...objects, ...declarations];
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Claims a mark for the global being decided, and says whether that global is retained. */
|
|
158
|
+
private claim(mark: number | ts.Node | null, held: boolean): boolean {
|
|
159
|
+
if (mark === null) {
|
|
160
|
+
return held;
|
|
161
|
+
}
|
|
162
|
+
this.claimed.add(mark);
|
|
163
|
+
return true;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Whether what a global stores at `at` holds something retained, claiming each mark it finds.
|
|
168
|
+
* An object stored elsewhere is that place's to retain.
|
|
169
|
+
*/
|
|
170
|
+
private holds(value: CapturedValue, at: Owner): boolean {
|
|
171
|
+
const node = this.model.node(value);
|
|
172
|
+
if (!node?.owner || node.owner.root !== at.root) {
|
|
173
|
+
return false;
|
|
174
|
+
}
|
|
175
|
+
if (tsPath(node.owner) !== tsPath(at)) {
|
|
176
|
+
return false;
|
|
177
|
+
}
|
|
178
|
+
const marks = [
|
|
179
|
+
...(this.objects.has(node.id) && this.storage.hasState(node)
|
|
180
|
+
? [node.id]
|
|
181
|
+
: []),
|
|
182
|
+
...this.retainedMembers(node),
|
|
183
|
+
];
|
|
184
|
+
for (const mark of marks) {
|
|
185
|
+
this.claimed.add(mark);
|
|
186
|
+
}
|
|
187
|
+
const inner = children(node.captured).map(([step, held]) =>
|
|
188
|
+
this.holds(held, { root: at.root, steps: [...at.steps, step] }),
|
|
189
|
+
);
|
|
190
|
+
return marks.length > 0 || inner.some(Boolean);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** The fields of an instance the PLC stores whose declarations retain a primitive. */
|
|
194
|
+
private retainedMembers(node: ModelNode): ts.Node[] {
|
|
195
|
+
if (node.captured.kind !== "instance") {
|
|
196
|
+
return [];
|
|
197
|
+
}
|
|
198
|
+
return this.model
|
|
199
|
+
.fields(this.model.classOf(node))
|
|
200
|
+
.filter(
|
|
201
|
+
(member) =>
|
|
202
|
+
this.declarations.has(member) &&
|
|
203
|
+
this.storage.stored(node, member.name.getText()),
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
@@ -169,7 +169,7 @@ export class Storage {
|
|
|
169
169
|
}
|
|
170
170
|
|
|
171
171
|
/** Whether anything inside a node is state the PLC stores. */
|
|
172
|
-
|
|
172
|
+
hasState(node: ModelNode): boolean {
|
|
173
173
|
const captured = node.captured;
|
|
174
174
|
if (node.owner?.root.exported) {
|
|
175
175
|
return true;
|
package/stdlib/retain.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Keeps state through a warm restart: `retain(initializer)` returns its argument, and the PLC
|
|
3
|
+
* declares the storage that holds it `RETAIN`. A plain TypeScript program imports it from here,
|
|
4
|
+
* because its setup and unit tests run under Bun (docs/language/plain-typescript.md).
|
|
5
|
+
*/
|
|
6
|
+
export { retain } from "./index";
|