@tsplc/compiler 0.2.17 → 0.2.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/cli.js +920 -943
- package/dist/cli.js.map +13 -10
- package/dist/codesys.js +3893 -3352
- package/dist/codesys.js.map +29 -20
- package/dist/elaborate-capture.js +33 -17
- package/dist/elaborate-capture.js.map +3 -3
- package/dist/index.js +8787 -6855
- package/dist/index.js.map +40 -20
- package/dist/ir.js +1575 -1072
- package/dist/ir.js.map +21 -17
- package/dist/math.js.map +2 -2
- package/dist/project.js +154 -60
- package/dist/project.js.map +5 -5
- package/dist/telemetry.js +27 -9
- package/dist/telemetry.js.map +5 -5
- package/package.json +112 -112
- package/src/codesys/config.ts +50 -0
- package/src/codesys/debug.ts +670 -0
- package/src/codesys/emit.ts +142 -0
- package/src/codesys/engineering.ts +109 -0
- package/src/codesys/expressions.ts +92 -0
- package/src/codesys/global-lists.ts +250 -0
- package/src/codesys/global-names.ts +68 -0
- package/src/codesys/http.ts +890 -0
- package/src/codesys/index.ts +30 -0
- package/src/codesys/instrumentation.ts +430 -0
- package/src/codesys/io-paths.ts +140 -0
- package/src/codesys/manifest.ts +643 -0
- package/src/codesys/names.ts +81 -0
- package/src/codesys/numeric.ts +409 -0
- package/src/codesys/operands.ts +62 -0
- package/src/codesys/plan.ts +605 -0
- package/src/codesys/programs.ts +53 -0
- package/src/codesys/publication.ts +171 -0
- package/src/codesys/routines.ts +603 -0
- package/src/codesys/sources.ts +71 -0
- package/src/codesys/st-files.ts +115 -0
- package/src/codesys/storage.ts +97 -0
- package/src/codesys/symbols.ts +220 -0
- package/src/codesys/task-access.ts +320 -0
- package/src/codesys/telemetry.ts +732 -0
- package/src/codesys/types.ts +250 -0
- package/src/codesys/vendor.ts +150 -0
- package/src/frontend/analyzer.ts +794 -0
- package/src/frontend/async.ts +317 -1137
- package/src/frontend/blocks.ts +537 -403
- package/src/frontend/configuration.ts +176 -144
- package/src/frontend/const-functions.ts +183 -148
- package/src/frontend/cooperative.ts +73 -43
- package/src/frontend/coroutines.ts +1032 -0
- package/src/frontend/elaborate/calls.ts +535 -0
- package/src/frontend/elaborate/capture.ts +157 -101
- package/src/frontend/elaborate/dialect.ts +257 -0
- package/src/frontend/elaborate/expressions.ts +992 -0
- package/src/frontend/elaborate/frame.ts +53 -0
- package/src/frontend/elaborate/graph.ts +116 -71
- package/src/frontend/elaborate/imports.ts +70 -0
- package/src/frontend/elaborate/index.ts +435 -331
- package/src/frontend/elaborate/initializers.ts +198 -0
- package/src/frontend/elaborate/layouts.ts +591 -384
- package/src/frontend/elaborate/model.ts +264 -169
- package/src/frontend/elaborate/specialize.ts +343 -2586
- package/src/frontend/elaborate/statements.ts +606 -0
- package/src/frontend/elaborate/storage.ts +546 -0
- package/src/frontend/elaborate/values.ts +58 -0
- package/src/frontend/elaborate/writes.ts +100 -0
- package/src/frontend/exposure.ts +172 -140
- package/src/frontend/expressions.ts +1383 -0
- package/src/frontend/intrinsics.ts +337 -0
- package/src/frontend/module-graph.ts +89 -59
- package/src/frontend/positions.ts +271 -200
- package/src/frontend/promise-chains.ts +897 -0
- package/src/frontend/promises.ts +390 -747
- package/src/frontend/routines.ts +181 -0
- package/src/frontend/sdk.ts +82 -0
- package/src/frontend/services.ts +506 -372
- package/src/frontend/statements.ts +855 -0
- package/src/frontend/tasks.ts +471 -0
- package/src/frontend/telemetry.ts +174 -0
- package/src/frontend/types.ts +845 -551
- package/src/frontend/typescript.ts +323 -2543
- package/src/index.ts +5 -5
- package/src/ir/aggregates.ts +275 -0
- package/src/ir/allocation.ts +84 -0
- package/src/ir/core-model.ts +146 -0
- package/src/ir/declarations.ts +295 -0
- package/src/ir/diagnostics.ts +61 -0
- package/src/ir/domains.ts +152 -0
- package/src/ir/fold.ts +342 -0
- package/src/ir/index.ts +90 -0
- package/{ir/errors.ts → src/ir/job-errors.ts} +12 -10
- package/src/ir/layouts.ts +181 -0
- package/src/ir/link.ts +354 -0
- package/src/ir/model.ts +386 -0
- package/{ir → src/ir}/normalization-error.ts +4 -4
- package/src/ir/normalize.ts +70 -0
- package/src/ir/numeric.ts +171 -0
- package/src/ir/ranges.ts +256 -0
- package/src/ir/routine.ts +1163 -0
- package/src/ir/scalars.ts +321 -0
- package/src/ir/types.ts +127 -0
- package/src/project/artifacts.ts +342 -0
- package/src/project/cli.ts +177 -0
- package/src/project/debugger.ts +82 -0
- package/src/project/index.ts +6 -0
- package/src/project/plant.ts +467 -0
- package/src/project/project-commands.ts +372 -0
- package/src/project/project.ts +457 -0
- package/src/project/release.ts +153 -0
- package/src/project/server.ts +150 -0
- package/src/project/terminal.ts +32 -0
- package/stdlib/math.ts +14 -10
- package/stdlib/telemetry.ts +71 -47
- package/types/async.d.ts +46 -40
- package/types/data-types.d.ts +26 -26
- package/types/globals.d.ts +41 -38
- package/types/index.d.ts +96 -51
- package/types/plc.d.ts +3 -4
- package/types/telemetry.d.ts +14 -14
- package/backends/codesys/config.ts +0 -54
- package/backends/codesys/debug.ts +0 -509
- package/backends/codesys/emit.ts +0 -1738
- package/backends/codesys/engineering.ts +0 -88
- package/backends/codesys/global-names.ts +0 -49
- package/backends/codesys/http.ts +0 -675
- package/backends/codesys/index.ts +0 -13
- package/backends/codesys/io-paths.ts +0 -105
- package/backends/codesys/manifest.ts +0 -312
- package/backends/codesys/names.ts +0 -76
- package/backends/codesys/numeric.ts +0 -356
- package/backends/codesys/plan.ts +0 -457
- package/backends/codesys/publication.ts +0 -59
- package/backends/codesys/storage.ts +0 -70
- package/backends/codesys/task-access.ts +0 -293
- package/backends/codesys/telemetry.ts +0 -593
- package/backends/codesys/types.ts +0 -179
- package/backends/codesys/vendor.ts +0 -108
- package/ir/aggregates.ts +0 -333
- package/ir/allocation.ts +0 -74
- package/ir/core-model.ts +0 -129
- package/ir/core.ts +0 -64
- package/ir/declarations.ts +0 -208
- package/ir/diagnostics.ts +0 -43
- package/ir/domains.ts +0 -96
- package/ir/index.ts +0 -8
- package/ir/link.ts +0 -185
- package/ir/model.ts +0 -346
- package/ir/routine.ts +0 -859
- package/ir/scalars.ts +0 -675
- package/ir/types.ts +0 -76
- package/project/artifacts.ts +0 -277
- package/project/cli.ts +0 -395
- package/project/index.ts +0 -1
- package/project/plant.ts +0 -509
- package/project/project.ts +0 -358
- package/project/server.ts +0 -113
|
@@ -0,0 +1,471 @@
|
|
|
1
|
+
import ts from "typescript";
|
|
2
|
+
import { resolve } from "node:path";
|
|
3
|
+
import { durationLiteral, nanosecondsPerMillisecond } from "@tsplc/compiler/ir";
|
|
4
|
+
import {
|
|
5
|
+
cooperativeSite,
|
|
6
|
+
copyValue,
|
|
7
|
+
taskSite,
|
|
8
|
+
type Site,
|
|
9
|
+
} from "./cooperative.ts";
|
|
10
|
+
import { aliasPrefix } from "./coroutines.ts";
|
|
11
|
+
import { importSpecifier } from "./module-graph.ts";
|
|
12
|
+
import { from } from "./positions.ts";
|
|
13
|
+
import type { AsyncContext, Routine, SourceRewrite } from "./async.ts";
|
|
14
|
+
|
|
15
|
+
/** A `<tasks>.define(...)` initializer, the declaration holding it, and that declaration's block. */
|
|
16
|
+
interface TaskDefinition {
|
|
17
|
+
declaration: ts.VariableDeclaration | ts.PropertyDeclaration;
|
|
18
|
+
init: ts.CallExpression;
|
|
19
|
+
owner: ts.ClassLikeDeclaration | undefined;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Lowers `tasks.define`, `cooperativeTasks.define` and `backgroundTasks.define` in one
|
|
24
|
+
* source: each becomes a generated site or mailbox block, with the entry points that run it.
|
|
25
|
+
*/
|
|
26
|
+
export function lowerTaskDefinitions(
|
|
27
|
+
context: AsyncContext,
|
|
28
|
+
file: SourceRewrite,
|
|
29
|
+
): void {
|
|
30
|
+
for (const declaration of declarations(file.source)) {
|
|
31
|
+
const init = declaration.initializer;
|
|
32
|
+
if (
|
|
33
|
+
!init ||
|
|
34
|
+
!ts.isCallExpression(init) ||
|
|
35
|
+
!ts.isPropertyAccessExpression(init.expression) ||
|
|
36
|
+
(!context.namesSdk(init.expression.expression, "backgroundTasks") &&
|
|
37
|
+
!context.namesSdk(init.expression.expression, "cooperativeTasks") &&
|
|
38
|
+
!context.namesSdk(init.expression.expression, "tasks")) ||
|
|
39
|
+
init.expression.name.text !== "define"
|
|
40
|
+
) {
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
const definition = {
|
|
44
|
+
declaration,
|
|
45
|
+
init,
|
|
46
|
+
owner: ts.isPropertyDeclaration(declaration)
|
|
47
|
+
? declaration.parent
|
|
48
|
+
: undefined,
|
|
49
|
+
};
|
|
50
|
+
if (context.namesSdk(init.expression.expression, "tasks")) {
|
|
51
|
+
taskDefinition(context, file, definition);
|
|
52
|
+
} else if (
|
|
53
|
+
context.namesSdk(init.expression.expression, "cooperativeTasks")
|
|
54
|
+
) {
|
|
55
|
+
cooperativeDefinition(context, file, definition);
|
|
56
|
+
} else {
|
|
57
|
+
backgroundDefinition(context, file, definition);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Module variables and block fields, where task definitions live. */
|
|
63
|
+
const declarations = (source: ts.SourceFile) =>
|
|
64
|
+
source.statements.flatMap<ts.VariableDeclaration | ts.PropertyDeclaration>(
|
|
65
|
+
(statement) => {
|
|
66
|
+
if (ts.isVariableStatement(statement)) {
|
|
67
|
+
return [...statement.declarationList.declarations];
|
|
68
|
+
}
|
|
69
|
+
if (ts.isClassDeclaration(statement)) {
|
|
70
|
+
return statement.members.filter(ts.isPropertyDeclaration);
|
|
71
|
+
}
|
|
72
|
+
return [];
|
|
73
|
+
},
|
|
74
|
+
);
|
|
75
|
+
|
|
76
|
+
/** `tasks.define(work)`: a task the owner starts, polls and reads, with no callback. */
|
|
77
|
+
function taskDefinition(
|
|
78
|
+
context: AsyncContext,
|
|
79
|
+
file: SourceRewrite,
|
|
80
|
+
definition: TaskDefinition,
|
|
81
|
+
): void {
|
|
82
|
+
const { declaration, init, owner } = definition;
|
|
83
|
+
const [work, ...rest] = init.arguments;
|
|
84
|
+
const symbol = context.symbol(work ?? init);
|
|
85
|
+
const fn = symbol && context.functions.get(symbol);
|
|
86
|
+
if (!ts.isIdentifier(declaration.name) || !work || rest.length || !fn?.type) {
|
|
87
|
+
context.fail(
|
|
88
|
+
init,
|
|
89
|
+
"tasks.define requires one named async function with a return type.",
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
const { params, valueType, valueAggregate } = workTypes(
|
|
93
|
+
context,
|
|
94
|
+
file,
|
|
95
|
+
fn,
|
|
96
|
+
declaration,
|
|
97
|
+
);
|
|
98
|
+
const worker = `tsplcTaskWorker${context.sequence()}`;
|
|
99
|
+
const receiver = `this.${worker}`;
|
|
100
|
+
const site = taskSite(
|
|
101
|
+
declaration.name.text,
|
|
102
|
+
params,
|
|
103
|
+
{
|
|
104
|
+
start: `${receiver}.start`,
|
|
105
|
+
advance: `${receiver}.update`,
|
|
106
|
+
snapshot: `${receiver}.snapshot`,
|
|
107
|
+
reset: `${receiver}.reset`,
|
|
108
|
+
declaration: `private ${worker}=new ${work.getText(file.source)}();`,
|
|
109
|
+
},
|
|
110
|
+
Boolean(owner),
|
|
111
|
+
{ type: valueType, aggregate: valueAggregate },
|
|
112
|
+
);
|
|
113
|
+
placeSite(context, file, definition, declaration.name.text, site, {
|
|
114
|
+
siteClass: "TsplcTaskSite",
|
|
115
|
+
unnamedOwner: "Task owners require a named block.",
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** `cooperativeTasks.define(work)`: a continuation slot the compiler polls for its owner. */
|
|
120
|
+
function cooperativeDefinition(
|
|
121
|
+
context: AsyncContext,
|
|
122
|
+
file: SourceRewrite,
|
|
123
|
+
definition: TaskDefinition,
|
|
124
|
+
): void {
|
|
125
|
+
const { declaration, init, owner } = definition;
|
|
126
|
+
const [work, ...rest] = init.arguments;
|
|
127
|
+
if (!ts.isIdentifier(declaration.name) || !work || rest.length) {
|
|
128
|
+
context.fail(init, "Invalid compiler-owned continuation slot.");
|
|
129
|
+
}
|
|
130
|
+
const symbol = context.symbol(
|
|
131
|
+
ts.isPropertyAccessExpression(work) ? work.name : work,
|
|
132
|
+
);
|
|
133
|
+
const routine = symbol && context.functions.get(symbol);
|
|
134
|
+
if (!routine) {
|
|
135
|
+
context.fail(work, "A continuation requires a named async routine.");
|
|
136
|
+
}
|
|
137
|
+
const params = routine.parameters.map((parameter, index) => ({
|
|
138
|
+
name: `argument${index}`,
|
|
139
|
+
type: parameter.type!.getText(routine.getSourceFile()),
|
|
140
|
+
aggregate: Boolean(
|
|
141
|
+
context.checker.getTypeAtLocation(parameter).flags & ts.TypeFlags.Object,
|
|
142
|
+
),
|
|
143
|
+
}));
|
|
144
|
+
// An async method runs as members of the owner itself; a helper runs in its own block.
|
|
145
|
+
const method = context.methods.get(symbol);
|
|
146
|
+
const worker = `tsplcCooperativeWorker${context.sequence()}`;
|
|
147
|
+
const receiver = method ? "this" : `this.${worker}`;
|
|
148
|
+
const site = cooperativeSite(
|
|
149
|
+
declaration.name.text,
|
|
150
|
+
params,
|
|
151
|
+
{
|
|
152
|
+
start: `${receiver}.${method?.start ?? "start"}`,
|
|
153
|
+
advance: `${receiver}.${method?.advance ?? "update"}`,
|
|
154
|
+
snapshot: `${receiver}.${method?.snapshot ?? "snapshot"}`,
|
|
155
|
+
reset: `${receiver}.${method?.reset ?? "reset"}`,
|
|
156
|
+
declaration: method
|
|
157
|
+
? ""
|
|
158
|
+
: `private ${worker}=new ${work.getText(file.source)}();`,
|
|
159
|
+
},
|
|
160
|
+
Boolean(owner),
|
|
161
|
+
);
|
|
162
|
+
placeSite(context, file, definition, declaration.name.text, site, {
|
|
163
|
+
siteClass: "TsplcCooperativeSite",
|
|
164
|
+
unnamedOwner: "Continuation owners require a named block.",
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* A site defined in a block replaces its field, is polled through the block's instances, and
|
|
170
|
+
* takes calls to its members through the field. A module-level site gets its own block and a
|
|
171
|
+
* continuation entry that polls it.
|
|
172
|
+
*/
|
|
173
|
+
function placeSite(
|
|
174
|
+
context: AsyncContext,
|
|
175
|
+
{ source, replacements, extra }: SourceRewrite,
|
|
176
|
+
{ declaration, init, owner }: TaskDefinition,
|
|
177
|
+
name: string,
|
|
178
|
+
site: Site,
|
|
179
|
+
{ siteClass, unnamedOwner }: { siteClass: string; unnamedOwner: string },
|
|
180
|
+
): void {
|
|
181
|
+
if (owner) {
|
|
182
|
+
if (!owner.name) {
|
|
183
|
+
context.fail(owner, unnamedOwner);
|
|
184
|
+
}
|
|
185
|
+
replacements.push({
|
|
186
|
+
start: declaration.getStart(source),
|
|
187
|
+
end: declaration.end,
|
|
188
|
+
text: site.body,
|
|
189
|
+
});
|
|
190
|
+
const block = context.symbol(owner.name)!;
|
|
191
|
+
context.ownedContinuations.set(block, [
|
|
192
|
+
...(context.ownedContinuations.get(block) ?? []),
|
|
193
|
+
site.poll,
|
|
194
|
+
]);
|
|
195
|
+
const field = context.symbol(declaration.name);
|
|
196
|
+
const visit = (node: ts.Node): void => {
|
|
197
|
+
if (
|
|
198
|
+
ts.isCallExpression(node) &&
|
|
199
|
+
ts.isPropertyAccessExpression(node.expression) &&
|
|
200
|
+
ts.isPropertyAccessExpression(node.expression.expression) &&
|
|
201
|
+
node.expression.expression.expression.kind ===
|
|
202
|
+
ts.SyntaxKind.ThisKeyword &&
|
|
203
|
+
context.symbol(node.expression.expression.name) === field
|
|
204
|
+
) {
|
|
205
|
+
const renamed = site.renames.get(node.expression.name.text);
|
|
206
|
+
if (renamed) {
|
|
207
|
+
replacements.push({
|
|
208
|
+
start: node.expression.getStart(source),
|
|
209
|
+
end: node.expression.end,
|
|
210
|
+
text: `this.${renamed}`,
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
ts.forEachChild(node, visit);
|
|
215
|
+
};
|
|
216
|
+
visit(owner);
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
const block = `${siteClass}${context.sequence()}`;
|
|
220
|
+
const entry = `tsplcContinuation${context.sequence()}`;
|
|
221
|
+
extra.push(
|
|
222
|
+
from(
|
|
223
|
+
declaration,
|
|
224
|
+
`class ${block} extends FunctionBlock<{}>{${site.body}protected execute(input:{}):void{}}
|
|
225
|
+
export function ${entry}():void{${name}.poll();}`,
|
|
226
|
+
),
|
|
227
|
+
);
|
|
228
|
+
replacements.push({
|
|
229
|
+
start: init.getStart(source),
|
|
230
|
+
end: init.end,
|
|
231
|
+
text: `new ${block}()`,
|
|
232
|
+
});
|
|
233
|
+
context.result.programs[entry] = {
|
|
234
|
+
module: resolve(source.fileName),
|
|
235
|
+
export: entry,
|
|
236
|
+
};
|
|
237
|
+
context.result.continuations.set(entry, {
|
|
238
|
+
instance: name,
|
|
239
|
+
file: context.positions.node(declaration).file,
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** `backgroundTasks.define(work, { interval, priority })`: a mailbox a scheduled task serves. */
|
|
244
|
+
function backgroundDefinition(
|
|
245
|
+
context: AsyncContext,
|
|
246
|
+
file: SourceRewrite,
|
|
247
|
+
definition: TaskDefinition,
|
|
248
|
+
): void {
|
|
249
|
+
const { declaration, init, owner } = definition;
|
|
250
|
+
const { source, replacements, extra } = file;
|
|
251
|
+
const [work, options, ...rest] = init.arguments;
|
|
252
|
+
if (
|
|
253
|
+
!ts.isIdentifier(declaration.name) ||
|
|
254
|
+
!work ||
|
|
255
|
+
!options ||
|
|
256
|
+
rest.length ||
|
|
257
|
+
!ts.isObjectLiteralExpression(options)
|
|
258
|
+
) {
|
|
259
|
+
context.fail(
|
|
260
|
+
declaration,
|
|
261
|
+
"Define background tasks at module scope or as function-block fields with a named async function and scheduling options.",
|
|
262
|
+
);
|
|
263
|
+
}
|
|
264
|
+
const symbol = context.symbol(work);
|
|
265
|
+
const fn = symbol && context.functions.get(symbol);
|
|
266
|
+
if (!fn?.type || !ts.isTypeReferenceNode(fn.type)) {
|
|
267
|
+
context.fail(
|
|
268
|
+
init,
|
|
269
|
+
"backgroundTasks.define requires a named async function.",
|
|
270
|
+
);
|
|
271
|
+
}
|
|
272
|
+
const { params, valueType, valueAggregate } = workTypes(
|
|
273
|
+
context,
|
|
274
|
+
file,
|
|
275
|
+
fn,
|
|
276
|
+
declaration,
|
|
277
|
+
);
|
|
278
|
+
const mailbox = `TsplcMailbox${context.sequence()}`;
|
|
279
|
+
const worker = `tsplcWorker${context.sequence()}`;
|
|
280
|
+
const entry = `tsplcBackground${context.sequence()}`;
|
|
281
|
+
const requestType = `{ready:BOOL;${params.map((p) => `${p.field}:${p.type}`).join(";")}}`;
|
|
282
|
+
const snapshotType = `{valid:BOOL;busy:BOOL;done:BOOL;cancelRequested:BOOL;error:UDINT;result:${valueType}}`;
|
|
283
|
+
const emptySnapshot = `{valid:true,busy:this.pending || this.active,done:this.completed,cancelRequested:this.cancelRequested,error:this.failure,result:${copyValue("this.value", valueAggregate)}}`;
|
|
284
|
+
extra.push(
|
|
285
|
+
from(
|
|
286
|
+
declaration,
|
|
287
|
+
`class ${mailbox} extends FunctionBlock<{}> {
|
|
288
|
+
private pending:BOOL=false;private active:BOOL=false;private completed:BOOL=false;private cancelRequested:BOOL=false;private failure:UDINT=0;private value:${valueType}=defaultValue<${valueType}>();
|
|
289
|
+
${params.map((p) => `private ${p.field}:${p.type}=defaultValue<${p.type}>();`).join("\n")}
|
|
290
|
+
start(${params.map((p) => `${p.name}:${p.type}`).join(",")}):BOOL {if(this.pending || this.active || this.completed)return false;${params.map((p) => `this.${p.field}=${copyValue(p.name, p.aggregate)};`).join("")}this.pending=true;return true;}
|
|
291
|
+
take():${requestType} {const ready:BOOL=this.pending; if(ready){this.pending=false;this.active=true;}return {ready,${params.map((p) => `${p.field}:${copyValue(`this.${p.field}`, p.aggregate)}`).join(",")}};}
|
|
292
|
+
publish(value:${valueType},error:UDINT):BOOL {if(!this.active)return false;if(this.cancelRequested){this.value=defaultValue<${valueType}>();this.failure=1;}else{this.value=${copyValue("value", valueAggregate)};this.failure=error;}this.active=false;this.completed=true;this.cancelRequested=false;return true;}
|
|
293
|
+
snapshot():${snapshotType} {return ${emptySnapshot};}
|
|
294
|
+
cancel():BOOL {if(this.pending){this.pending=false;this.completed=true;this.failure=1;return true;}if(this.active){this.cancelRequested=true;return true;}return false;}
|
|
295
|
+
reset():BOOL {if(this.pending || this.active)return false;this.completed=false;this.failure=0;this.cancelRequested=false;this.value=defaultValue<${valueType}>();return true;}
|
|
296
|
+
protected execute(input:{}):void {}
|
|
297
|
+
}
|
|
298
|
+
`,
|
|
299
|
+
),
|
|
300
|
+
);
|
|
301
|
+
const receiver = owner
|
|
302
|
+
? `this.${declaration.name.text}`
|
|
303
|
+
: declaration.name.text;
|
|
304
|
+
const workerReceiver = owner ? `this.${worker}` : worker;
|
|
305
|
+
const run = `const request=${receiver}.take();if(request.ready){const accepted:BOOL=${workerReceiver}.start(${params.map((p) => `request.${p.field}`).join(",")});}const control=${receiver}.snapshot();if(!control.valid)return;${workerReceiver}.update({cancel:control.cancelRequested});const state=${workerReceiver}.snapshot();if(state.done){const published:BOOL=${receiver}.publish(state.result,state.error);if(published)${workerReceiver}.reset();}`;
|
|
306
|
+
if (owner) {
|
|
307
|
+
if (!owner.name) {
|
|
308
|
+
context.fail(owner, "Background job owners need a named function block.");
|
|
309
|
+
}
|
|
310
|
+
replacements.push({
|
|
311
|
+
start: owner.end - 1,
|
|
312
|
+
end: owner.end - 1,
|
|
313
|
+
text: from(
|
|
314
|
+
declaration,
|
|
315
|
+
`private ${worker}=new ${work.getText(source)}();public ${entry}():void{${run}}`,
|
|
316
|
+
),
|
|
317
|
+
});
|
|
318
|
+
context.result.blocks.set(`${source.fileName}:${owner.name.text}`, {
|
|
319
|
+
kind: "backgroundHost",
|
|
320
|
+
});
|
|
321
|
+
} else {
|
|
322
|
+
extra.push(
|
|
323
|
+
from(
|
|
324
|
+
declaration,
|
|
325
|
+
`const ${worker}=new ${work.getText(source)}();export function ${entry}():void{${run}}`,
|
|
326
|
+
),
|
|
327
|
+
);
|
|
328
|
+
}
|
|
329
|
+
context.result.blocks.set(`${source.fileName}:${mailbox}`, {
|
|
330
|
+
kind: "mailbox",
|
|
331
|
+
});
|
|
332
|
+
const schedule = {
|
|
333
|
+
...scheduleTiming(context, source, init, options),
|
|
334
|
+
mailbox: declaration.name.text,
|
|
335
|
+
worker,
|
|
336
|
+
};
|
|
337
|
+
if (owner) {
|
|
338
|
+
const block = context.symbol(owner.name!)!;
|
|
339
|
+
context.ownedJobs.set(block, [
|
|
340
|
+
...(context.ownedJobs.get(block) ?? []),
|
|
341
|
+
{ method: entry, schedule },
|
|
342
|
+
]);
|
|
343
|
+
} else {
|
|
344
|
+
context.result.programs[entry] = {
|
|
345
|
+
module: resolve(source.fileName),
|
|
346
|
+
export: entry,
|
|
347
|
+
};
|
|
348
|
+
context.result.schedules.set(entry, schedule);
|
|
349
|
+
}
|
|
350
|
+
replacements.push({
|
|
351
|
+
start: init.getStart(source),
|
|
352
|
+
end: init.end,
|
|
353
|
+
text: `new ${mailbox}()`,
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** The literal `interval: ms(n)` or `seconds(n)` and `priority` a background task runs at. */
|
|
358
|
+
function scheduleTiming(
|
|
359
|
+
context: AsyncContext,
|
|
360
|
+
source: ts.SourceFile,
|
|
361
|
+
init: ts.CallExpression,
|
|
362
|
+
options: ts.ObjectLiteralExpression,
|
|
363
|
+
): { intervalNanoseconds: string; priority: number } {
|
|
364
|
+
const properties = new Map(
|
|
365
|
+
options.properties
|
|
366
|
+
.filter(ts.isPropertyAssignment)
|
|
367
|
+
.map((property) => [property.name.getText(source), property.initializer]),
|
|
368
|
+
);
|
|
369
|
+
const interval = properties.get("interval");
|
|
370
|
+
const priority = properties.get("priority");
|
|
371
|
+
const [amount, ...rest] =
|
|
372
|
+
interval && ts.isCallExpression(interval) ? interval.arguments : [];
|
|
373
|
+
if (
|
|
374
|
+
!interval ||
|
|
375
|
+
!ts.isCallExpression(interval) ||
|
|
376
|
+
!amount ||
|
|
377
|
+
rest.length ||
|
|
378
|
+
!ts.isNumericLiteral(amount) ||
|
|
379
|
+
!priority ||
|
|
380
|
+
!ts.isNumericLiteral(priority) ||
|
|
381
|
+
!["ms", "seconds"].some((name) =>
|
|
382
|
+
context.namesSdk(interval.expression, name),
|
|
383
|
+
)
|
|
384
|
+
) {
|
|
385
|
+
context.fail(
|
|
386
|
+
init,
|
|
387
|
+
"Background schedules require a literal ms/seconds interval and priority.",
|
|
388
|
+
);
|
|
389
|
+
}
|
|
390
|
+
const milliseconds =
|
|
391
|
+
Number(amount.text) *
|
|
392
|
+
(context.namesSdk(interval.expression, "seconds") ? 1000 : 1);
|
|
393
|
+
const taskPriority = Number(priority.text);
|
|
394
|
+
// A whole number of milliseconds, held to the TIME range.
|
|
395
|
+
const period =
|
|
396
|
+
Number.isSafeInteger(milliseconds) && milliseconds > 0
|
|
397
|
+
? durationLiteral(String(milliseconds), nanosecondsPerMillisecond)
|
|
398
|
+
: undefined;
|
|
399
|
+
if (
|
|
400
|
+
period?.kind !== "duration" ||
|
|
401
|
+
!Number.isInteger(taskPriority) ||
|
|
402
|
+
taskPriority < 1 ||
|
|
403
|
+
taskPriority > 31
|
|
404
|
+
) {
|
|
405
|
+
context.fail(
|
|
406
|
+
init,
|
|
407
|
+
"Background interval must be positive and priority must be an integer in 1..31.",
|
|
408
|
+
);
|
|
409
|
+
}
|
|
410
|
+
return {
|
|
411
|
+
intervalNanoseconds: period.nanoseconds,
|
|
412
|
+
priority: taskPriority,
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/**
|
|
417
|
+
* The argument and result types a definition's worker routine has, as its defining module
|
|
418
|
+
* can name them.
|
|
419
|
+
*/
|
|
420
|
+
function workTypes(
|
|
421
|
+
context: AsyncContext,
|
|
422
|
+
{ source, extra }: SourceRewrite,
|
|
423
|
+
fn: Routine,
|
|
424
|
+
declaration: ts.VariableDeclaration | ts.PropertyDeclaration,
|
|
425
|
+
) {
|
|
426
|
+
const { checker } = context;
|
|
427
|
+
const reference = fn.type as ts.TypeReferenceNode;
|
|
428
|
+
const returnType =
|
|
429
|
+
reference.typeArguments![0]!.kind === ts.SyntaxKind.VoidKeyword
|
|
430
|
+
? "BOOL"
|
|
431
|
+
: reference.typeArguments![0]!.getText(fn.getSourceFile());
|
|
432
|
+
const promised = checker.getAwaitedType(
|
|
433
|
+
checker.getReturnTypeOfSignature(checker.getSignatureFromDeclaration(fn)!),
|
|
434
|
+
)!;
|
|
435
|
+
const valueAggregate = Boolean(promised.flags & ts.TypeFlags.Object);
|
|
436
|
+
const parameter = (
|
|
437
|
+
node: ts.ParameterDeclaration,
|
|
438
|
+
index: number,
|
|
439
|
+
type: string,
|
|
440
|
+
) => ({
|
|
441
|
+
field: `argument${index}`,
|
|
442
|
+
name: `argument${index}`,
|
|
443
|
+
aggregate: Boolean(
|
|
444
|
+
checker.getTypeAtLocation(node).flags & ts.TypeFlags.Object,
|
|
445
|
+
),
|
|
446
|
+
type,
|
|
447
|
+
});
|
|
448
|
+
if (fn.getSourceFile() === source) {
|
|
449
|
+
// The annotations keep the PLC widths the TypeScript checker erases.
|
|
450
|
+
return {
|
|
451
|
+
params: fn.parameters.map((node, index) =>
|
|
452
|
+
parameter(node, index, node.type!.getText(source)),
|
|
453
|
+
),
|
|
454
|
+
valueType: returnType,
|
|
455
|
+
valueAggregate,
|
|
456
|
+
};
|
|
457
|
+
}
|
|
458
|
+
// Another module's types are named through the aliases its coroutine exports.
|
|
459
|
+
const prefix = aliasPrefix(fn);
|
|
460
|
+
const params = fn.parameters.map((node, index) =>
|
|
461
|
+
parameter(node, index, `${prefix}Argument${index}`),
|
|
462
|
+
);
|
|
463
|
+
const valueType = `${prefix}Result`;
|
|
464
|
+
extra.push(
|
|
465
|
+
from(
|
|
466
|
+
declaration,
|
|
467
|
+
`import type {${valueType},${params.map((p) => p.type).join(",")}} from ${importSpecifier(source.fileName, fn.getSourceFile().fileName)};`,
|
|
468
|
+
),
|
|
469
|
+
);
|
|
470
|
+
return { params, valueType, valueAggregate };
|
|
471
|
+
}
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import ts from "typescript";
|
|
2
|
+
import type { Statement } from "@tsplc/compiler/ir";
|
|
3
|
+
import type { ExpressionLowering } from "./expressions.ts";
|
|
4
|
+
import { namedProperty, type TelemetryMethod } from "./types.ts";
|
|
5
|
+
|
|
6
|
+
type Telemetry = Extract<Statement, { kind: "telemetry" }>;
|
|
7
|
+
|
|
8
|
+
/** A `@tsplc/compiler/telemetry` call, which the backend encodes as one record (docs/language/telemetry.md). */
|
|
9
|
+
export function telemetryStatement(
|
|
10
|
+
lowering: ExpressionLowering,
|
|
11
|
+
node: ts.CallExpression,
|
|
12
|
+
): Statement | undefined {
|
|
13
|
+
const method = lowering.resolver.telemetryMethod(node);
|
|
14
|
+
if (!method) {
|
|
15
|
+
return undefined;
|
|
16
|
+
}
|
|
17
|
+
if (method === "text") {
|
|
18
|
+
lowering.fail(
|
|
19
|
+
node,
|
|
20
|
+
"PLC2001",
|
|
21
|
+
"telemetry.text is a property value of a telemetry call.",
|
|
22
|
+
);
|
|
23
|
+
}
|
|
24
|
+
const [first, properties, ...rest] = node.arguments;
|
|
25
|
+
if (!first || rest.length || node.typeArguments?.length) {
|
|
26
|
+
lowering.fail(
|
|
27
|
+
node,
|
|
28
|
+
"PLC2001",
|
|
29
|
+
`telemetry.${method} takes one value and optional properties.`,
|
|
30
|
+
);
|
|
31
|
+
}
|
|
32
|
+
return {
|
|
33
|
+
span: lowering.positions.node(node),
|
|
34
|
+
kind: "telemetry",
|
|
35
|
+
record: telemetryRecord(lowering, method, first),
|
|
36
|
+
properties: properties ? telemetryProperties(lowering, properties) : [],
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function telemetryRecord(
|
|
41
|
+
lowering: ExpressionLowering,
|
|
42
|
+
method: Exclude<TelemetryMethod, "text">,
|
|
43
|
+
first: ts.Expression,
|
|
44
|
+
): Telemetry["record"] {
|
|
45
|
+
switch (method) {
|
|
46
|
+
case "captureException":
|
|
47
|
+
return { kind: "exception", code: lowering.expression(first, "UDINT") };
|
|
48
|
+
case "capture":
|
|
49
|
+
return {
|
|
50
|
+
kind: "event",
|
|
51
|
+
event: literalText(lowering, method, first, "event name"),
|
|
52
|
+
};
|
|
53
|
+
default:
|
|
54
|
+
return {
|
|
55
|
+
kind: "log",
|
|
56
|
+
level: method,
|
|
57
|
+
message: literalText(lowering, method, first, "message"),
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** An event name or log message is fixed text; changing values go in the properties. */
|
|
63
|
+
function literalText(
|
|
64
|
+
lowering: ExpressionLowering,
|
|
65
|
+
method: TelemetryMethod,
|
|
66
|
+
node: ts.Expression,
|
|
67
|
+
label: string,
|
|
68
|
+
): string {
|
|
69
|
+
if (!ts.isStringLiteral(node) && !ts.isNoSubstitutionTemplateLiteral(node)) {
|
|
70
|
+
lowering.fail(
|
|
71
|
+
node,
|
|
72
|
+
"PLC2001",
|
|
73
|
+
`telemetry.${method} needs its ${label} as a string literal; put changing values in its properties.`,
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
return node.text;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function telemetryProperties(
|
|
80
|
+
lowering: ExpressionLowering,
|
|
81
|
+
node: ts.Expression,
|
|
82
|
+
): Telemetry["properties"] {
|
|
83
|
+
if (!ts.isObjectLiteralExpression(node)) {
|
|
84
|
+
lowering.fail(
|
|
85
|
+
node,
|
|
86
|
+
"PLC2001",
|
|
87
|
+
"Telemetry properties are an object literal.",
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
if (node.properties.length > 8) {
|
|
91
|
+
lowering.fail(
|
|
92
|
+
node,
|
|
93
|
+
"PLC2001",
|
|
94
|
+
"A telemetry call has at most 8 properties.",
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
return node.properties.map((property) => {
|
|
98
|
+
const named = namedProperty(property);
|
|
99
|
+
if (!named) {
|
|
100
|
+
lowering.fail(
|
|
101
|
+
property,
|
|
102
|
+
"PLC2001",
|
|
103
|
+
"Name each telemetry property with an identifier.",
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
const { name, value } = named;
|
|
107
|
+
if (
|
|
108
|
+
ts.isCallExpression(value) &&
|
|
109
|
+
lowering.resolver.telemetryMethod(value) === "text"
|
|
110
|
+
) {
|
|
111
|
+
return { name, ...textProperty(lowering, value) };
|
|
112
|
+
}
|
|
113
|
+
const expression = lowering.expression(value);
|
|
114
|
+
const type = lowering.resolver.types.get(expression.type);
|
|
115
|
+
if (
|
|
116
|
+
!type ||
|
|
117
|
+
!["bool", "integer", "bits", "float", "enum", "string"].includes(
|
|
118
|
+
type.kind,
|
|
119
|
+
) ||
|
|
120
|
+
(type.kind === "string" && type.encoding !== "utf8")
|
|
121
|
+
) {
|
|
122
|
+
lowering.fail(
|
|
123
|
+
value,
|
|
124
|
+
"PLC2001",
|
|
125
|
+
`Telemetry property ${name} is ${expression.type}; send BOOL, integers, REAL, LREAL, enums, STRINGs or telemetry.text(bytes, length).`,
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
return { name, value: expression };
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** `telemetry.text(bytes, length)`: the first `length` bytes of a BYTE array, sent as text. */
|
|
133
|
+
function textProperty(
|
|
134
|
+
lowering: ExpressionLowering,
|
|
135
|
+
node: ts.CallExpression,
|
|
136
|
+
): Omit<Telemetry["properties"][number], "name"> {
|
|
137
|
+
const [bytes, length, ...rest] = node.arguments;
|
|
138
|
+
if (!bytes || !length || rest.length) {
|
|
139
|
+
lowering.fail(
|
|
140
|
+
node,
|
|
141
|
+
"PLC2001",
|
|
142
|
+
"telemetry.text takes a byte array and a length.",
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
const place = lowering.place(bytes);
|
|
146
|
+
const { type } = lowering.placeType(place);
|
|
147
|
+
const array =
|
|
148
|
+
type === undefined ? undefined : lowering.resolver.types.get(type);
|
|
149
|
+
const element =
|
|
150
|
+
array?.kind === "array"
|
|
151
|
+
? lowering.resolver.types.get(array.element)
|
|
152
|
+
: undefined;
|
|
153
|
+
if (
|
|
154
|
+
!type ||
|
|
155
|
+
(element?.kind !== "bits" && element?.kind !== "integer") ||
|
|
156
|
+
element.bits !== 8
|
|
157
|
+
) {
|
|
158
|
+
lowering.fail(bytes, "PLC2001", "telemetry.text reads an array of BYTE.");
|
|
159
|
+
}
|
|
160
|
+
const counted = lowering.expression(length);
|
|
161
|
+
const countKind = lowering.resolver.types.get(counted.type)?.kind;
|
|
162
|
+
if (countKind !== "integer" && countKind !== "bits") {
|
|
163
|
+
lowering.fail(length, "PLC2001", "telemetry.text needs an integer length.");
|
|
164
|
+
}
|
|
165
|
+
return {
|
|
166
|
+
value: {
|
|
167
|
+
kind: "borrow",
|
|
168
|
+
place,
|
|
169
|
+
type,
|
|
170
|
+
span: lowering.positions.node(bytes),
|
|
171
|
+
},
|
|
172
|
+
length: counted,
|
|
173
|
+
};
|
|
174
|
+
}
|