@tsplc/compiler 0.2.14 → 0.2.16
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/backends/codesys/debug.ts +509 -0
- package/backends/codesys/emit.ts +701 -9
- package/backends/codesys/http.ts +110 -34
- package/backends/codesys/index.ts +2 -1
- package/backends/codesys/io-paths.ts +3 -1
- package/backends/codesys/manifest.ts +312 -0
- package/backends/codesys/plan.ts +39 -9
- package/backends/codesys/publication.ts +2 -2
- package/backends/codesys/storage.ts +10 -3
- package/backends/codesys/task-access.ts +51 -1
- package/backends/codesys/telemetry.ts +593 -0
- package/backends/codesys/types.ts +2 -1
- package/dist/cli.js +190 -33
- package/dist/cli.js.map +6 -6
- package/dist/codesys.js +2148 -432
- package/dist/codesys.js.map +14 -11
- package/dist/elaborate-capture.js +7 -1
- package/dist/elaborate-capture.js.map +3 -3
- package/dist/index.js +877 -459
- package/dist/index.js.map +16 -15
- package/dist/ir.js +87 -23
- package/dist/ir.js.map +10 -9
- package/dist/project.js +42 -9
- package/dist/project.js.map +3 -3
- package/dist/telemetry.js +83 -0
- package/dist/telemetry.js.map +12 -0
- package/ir/core-model.ts +13 -0
- package/ir/core.ts +1 -0
- package/ir/errors.ts +20 -0
- package/ir/index.ts +1 -0
- package/ir/link.ts +17 -8
- package/ir/model.ts +39 -0
- package/ir/routine.ts +62 -29
- package/ir/types.ts +7 -1
- package/package.json +12 -6
- package/project/cli.ts +96 -6
- package/project/plant.ts +58 -9
- package/project/project.ts +56 -10
- package/src/frontend/async.ts +284 -195
- package/src/frontend/configuration.ts +7 -21
- package/src/frontend/const-functions.ts +44 -38
- package/src/frontend/elaborate/capture.ts +7 -0
- package/src/frontend/elaborate/index.ts +135 -61
- package/src/frontend/elaborate/layouts.ts +8 -0
- package/src/frontend/elaborate/model.ts +13 -0
- package/src/frontend/elaborate/specialize.ts +302 -111
- package/src/frontend/exposure.ts +28 -26
- package/src/frontend/positions.ts +272 -0
- package/src/frontend/promises.ts +52 -47
- package/src/frontend/services.ts +16 -26
- package/src/frontend/types.ts +14 -0
- package/src/frontend/typescript.ts +185 -65
- package/stdlib/telemetry.ts +72 -0
- package/types/telemetry.d.ts +44 -0
package/dist/index.js
CHANGED
|
@@ -53,7 +53,7 @@ var runtimeSources = (program) => {
|
|
|
53
53
|
import ts15 from "typescript";
|
|
54
54
|
import { createRequire } from "node:module";
|
|
55
55
|
import { mkdirSync, realpathSync, writeFileSync as writeFileSync2 } from "node:fs";
|
|
56
|
-
import { dirname as dirname8, join as join4, relative as relative6, resolve as
|
|
56
|
+
import { dirname as dirname8, join as join4, relative as relative6, resolve as resolve5 } from "node:path";
|
|
57
57
|
import {
|
|
58
58
|
instancedBlock as instancedBlock3,
|
|
59
59
|
error as error8,
|
|
@@ -81,7 +81,222 @@ import ts2 from "typescript";
|
|
|
81
81
|
import { createHash } from "node:crypto";
|
|
82
82
|
import { dirname } from "node:path";
|
|
83
83
|
import { error } from "@tsplc/compiler/ir";
|
|
84
|
-
|
|
84
|
+
|
|
85
|
+
// packages/compiler/src/frontend/positions.ts
|
|
86
|
+
class Mapped {
|
|
87
|
+
text;
|
|
88
|
+
segments;
|
|
89
|
+
constructor(text, segments = []) {
|
|
90
|
+
this.text = text;
|
|
91
|
+
this.segments = segments;
|
|
92
|
+
}
|
|
93
|
+
toString() {
|
|
94
|
+
return this.text;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
var append = (segments, text, offset) => {
|
|
98
|
+
if (text instanceof Mapped)
|
|
99
|
+
for (const segment of text.segments)
|
|
100
|
+
segments.push({ ...segment, start: segment.start + offset, end: segment.end + offset });
|
|
101
|
+
};
|
|
102
|
+
var mapped = (strings, ...parts) => {
|
|
103
|
+
let text = strings[0];
|
|
104
|
+
const segments = [];
|
|
105
|
+
parts.forEach((part, index) => {
|
|
106
|
+
append(segments, part, text.length);
|
|
107
|
+
text += `${part}${strings[index + 1]}`;
|
|
108
|
+
});
|
|
109
|
+
return new Mapped(text, segments);
|
|
110
|
+
};
|
|
111
|
+
var joined = (parts, separator) => {
|
|
112
|
+
let text = "";
|
|
113
|
+
const segments = [];
|
|
114
|
+
parts.forEach((part, index) => {
|
|
115
|
+
if (index)
|
|
116
|
+
text += separator;
|
|
117
|
+
append(segments, part, text.length);
|
|
118
|
+
text += String(part);
|
|
119
|
+
});
|
|
120
|
+
return new Mapped(text, segments);
|
|
121
|
+
};
|
|
122
|
+
var fill = (text, file, from, to) => {
|
|
123
|
+
const value = text instanceof Mapped ? text : new Mapped(String(text));
|
|
124
|
+
const segments = [];
|
|
125
|
+
let cursor = 0;
|
|
126
|
+
const gap = (end) => {
|
|
127
|
+
if (end > cursor)
|
|
128
|
+
segments.push({ start: cursor, end, file, from, to, copied: false });
|
|
129
|
+
};
|
|
130
|
+
for (const segment of value.segments) {
|
|
131
|
+
gap(segment.start);
|
|
132
|
+
segments.push(segment);
|
|
133
|
+
cursor = segment.end;
|
|
134
|
+
}
|
|
135
|
+
gap(value.text.length);
|
|
136
|
+
return new Mapped(value.text, segments);
|
|
137
|
+
};
|
|
138
|
+
var from = (node, text) => {
|
|
139
|
+
const source = node.getSourceFile();
|
|
140
|
+
return fill(text, source.fileName, node.getStart(source), node.end);
|
|
141
|
+
};
|
|
142
|
+
var copied = (node) => {
|
|
143
|
+
const source = node.getSourceFile();
|
|
144
|
+
const start = node.getStart(source);
|
|
145
|
+
return new Mapped(source.text.slice(start, node.end), [
|
|
146
|
+
{
|
|
147
|
+
start: 0,
|
|
148
|
+
end: node.end - start,
|
|
149
|
+
file: source.fileName,
|
|
150
|
+
from: start,
|
|
151
|
+
to: node.end,
|
|
152
|
+
copied: true
|
|
153
|
+
}
|
|
154
|
+
]);
|
|
155
|
+
};
|
|
156
|
+
var slice = (text, start, end) => {
|
|
157
|
+
const segments = [];
|
|
158
|
+
for (const segment of text.segments) {
|
|
159
|
+
if (segment.end <= start || segment.start >= end)
|
|
160
|
+
continue;
|
|
161
|
+
const first = Math.max(segment.start, start), last = Math.min(segment.end, end);
|
|
162
|
+
segments.push({
|
|
163
|
+
...segment,
|
|
164
|
+
start: first - start,
|
|
165
|
+
end: last - start,
|
|
166
|
+
...segment.copied && {
|
|
167
|
+
from: segment.from + first - segment.start,
|
|
168
|
+
to: segment.from + last - segment.start
|
|
169
|
+
}
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
return new Mapped(text.text.slice(start, end), segments);
|
|
173
|
+
};
|
|
174
|
+
var edited = (base, edits) => {
|
|
175
|
+
const text = base instanceof Mapped ? base : new Mapped(base.text, [
|
|
176
|
+
{
|
|
177
|
+
start: 0,
|
|
178
|
+
end: base.text.length,
|
|
179
|
+
file: base.fileName,
|
|
180
|
+
from: 0,
|
|
181
|
+
to: base.text.length,
|
|
182
|
+
copied: true
|
|
183
|
+
}
|
|
184
|
+
]);
|
|
185
|
+
const ordered = edits.map((edit, index) => ({ edit, index })).sort((left, right) => left.edit.start - right.edit.start || right.index - left.index);
|
|
186
|
+
const parts = [];
|
|
187
|
+
let cursor = 0;
|
|
188
|
+
for (const { edit } of ordered) {
|
|
189
|
+
if (edit.start > cursor)
|
|
190
|
+
parts.push(slice(text, cursor, edit.start));
|
|
191
|
+
const origin = resolve(text.segments, edit.start, edit.end);
|
|
192
|
+
parts.push(origin ? fill(edit.text, origin.file, origin.from, origin.to) : mapped`${edit.text}`);
|
|
193
|
+
cursor = Math.max(cursor, edit.end);
|
|
194
|
+
}
|
|
195
|
+
parts.push(slice(text, cursor, text.text.length));
|
|
196
|
+
return joined(parts, "");
|
|
197
|
+
};
|
|
198
|
+
var search = (segments, offset) => {
|
|
199
|
+
let low = 0, high = segments.length;
|
|
200
|
+
while (low < high) {
|
|
201
|
+
const middle = low + high >> 1;
|
|
202
|
+
if (segments[middle].end > offset)
|
|
203
|
+
high = middle;
|
|
204
|
+
else
|
|
205
|
+
low = middle + 1;
|
|
206
|
+
}
|
|
207
|
+
return low;
|
|
208
|
+
};
|
|
209
|
+
var resolve = (segments, start, end) => {
|
|
210
|
+
const first = search(segments, start);
|
|
211
|
+
const head = segments[first];
|
|
212
|
+
if (!head || head.start >= Math.max(end, start + 1))
|
|
213
|
+
return;
|
|
214
|
+
let last = end > start ? search(segments, end - 1) : first;
|
|
215
|
+
if (!segments[last] || segments[last].start >= end)
|
|
216
|
+
last--;
|
|
217
|
+
const tail = last > first ? segments[last] : head;
|
|
218
|
+
const from = head.copied ? head.from + Math.max(0, start - head.start) : head.from;
|
|
219
|
+
const until = (segment) => segment.copied ? segment.from + Math.min(end, segment.end) - segment.start : segment.to;
|
|
220
|
+
const to = until(tail);
|
|
221
|
+
if (tail.file === head.file && to >= from)
|
|
222
|
+
return { file: head.file, from, to };
|
|
223
|
+
return { file: head.file, from, to: Math.max(from, until(head)) };
|
|
224
|
+
};
|
|
225
|
+
var sourceSpan = (source, start, end) => {
|
|
226
|
+
const position = source.getLineAndCharacterOfPosition(start);
|
|
227
|
+
return {
|
|
228
|
+
file: source.fileName,
|
|
229
|
+
start,
|
|
230
|
+
end,
|
|
231
|
+
line: position.line + 1,
|
|
232
|
+
column: position.character + 1
|
|
233
|
+
};
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
class Positions {
|
|
237
|
+
maps = new Map;
|
|
238
|
+
originals = new Map;
|
|
239
|
+
record(sources, program) {
|
|
240
|
+
const composed = new Map;
|
|
241
|
+
for (const [file, text] of sources) {
|
|
242
|
+
const segments = [];
|
|
243
|
+
for (const segment of text.segments) {
|
|
244
|
+
const previous = this.maps.get(segment.file);
|
|
245
|
+
if (!previous) {
|
|
246
|
+
if (!this.originals.has(segment.file))
|
|
247
|
+
this.originals.set(segment.file, program.getSourceFile(segment.file));
|
|
248
|
+
segments.push(segment);
|
|
249
|
+
} else if (segment.copied) {
|
|
250
|
+
for (let index = search(previous, segment.from);index < previous.length; index++) {
|
|
251
|
+
const inner = previous[index];
|
|
252
|
+
if (inner.start >= segment.to)
|
|
253
|
+
break;
|
|
254
|
+
const first = Math.max(inner.start, segment.from), last = Math.min(inner.end, segment.to);
|
|
255
|
+
segments.push({
|
|
256
|
+
start: segment.start + first - segment.from,
|
|
257
|
+
end: segment.start + last - segment.from,
|
|
258
|
+
file: inner.file,
|
|
259
|
+
from: inner.copied ? inner.from + first - inner.start : inner.from,
|
|
260
|
+
to: inner.copied ? inner.from + last - inner.start : inner.to,
|
|
261
|
+
copied: inner.copied
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
} else {
|
|
265
|
+
const origin = resolve(previous, segment.from, segment.to);
|
|
266
|
+
if (origin)
|
|
267
|
+
segments.push({ ...segment, ...origin });
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
composed.set(file, segments);
|
|
271
|
+
}
|
|
272
|
+
for (const [file, segments] of composed)
|
|
273
|
+
this.maps.set(file, segments);
|
|
274
|
+
}
|
|
275
|
+
origin(source, start, end) {
|
|
276
|
+
const segments = this.maps.get(source.fileName);
|
|
277
|
+
const origin = segments && resolve(segments, start, end);
|
|
278
|
+
if (!origin)
|
|
279
|
+
return { source, from: start, to: end };
|
|
280
|
+
return { source: this.originals.get(origin.file), from: origin.from, to: origin.to };
|
|
281
|
+
}
|
|
282
|
+
span = (source, start, end) => {
|
|
283
|
+
const origin = this.origin(source, start, end);
|
|
284
|
+
return sourceSpan(origin.source, origin.from, origin.to);
|
|
285
|
+
};
|
|
286
|
+
node = (node) => {
|
|
287
|
+
const source = node.getSourceFile();
|
|
288
|
+
return this.span(source, node.getStart(source), node.end);
|
|
289
|
+
};
|
|
290
|
+
excerpt(node, limit = 120) {
|
|
291
|
+
const source = node.getSourceFile();
|
|
292
|
+
const origin = this.origin(source, node.getStart(source), node.end);
|
|
293
|
+
const text = origin.source.text.slice(origin.from, origin.to).replace(/\s+/g, " ").trim();
|
|
294
|
+
return text.length > limit ? `${text.slice(0, limit - 1)}…` : text;
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// packages/compiler/src/frontend/exposure.ts
|
|
299
|
+
var lowerExposure = (program, sdk, positions) => {
|
|
85
300
|
const checker = program.getTypeChecker();
|
|
86
301
|
const sources = new Map;
|
|
87
302
|
const diagnostics = [];
|
|
@@ -103,16 +318,7 @@ var lowerExposure = (program, sdk) => {
|
|
|
103
318
|
ts2.forEachChild(node, visit);
|
|
104
319
|
return;
|
|
105
320
|
}
|
|
106
|
-
const fail = (message) =>
|
|
107
|
-
const start = node.getStart(source), position = source.getLineAndCharacterOfPosition(start);
|
|
108
|
-
diagnostics.push(error("PLC1014", message, {
|
|
109
|
-
file: source.fileName,
|
|
110
|
-
start,
|
|
111
|
-
end: node.end,
|
|
112
|
-
line: position.line + 1,
|
|
113
|
-
column: position.character + 1
|
|
114
|
-
}));
|
|
115
|
-
};
|
|
321
|
+
const fail = (message) => diagnostics.push(error("PLC1014", message, positions.node(node)));
|
|
116
322
|
const [label, values] = node.arguments;
|
|
117
323
|
if (!label || !ts2.isStringLiteral(label) || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(label.text) || label.text === "__proto__" || !values || !ts2.isObjectLiteralExpression(values) || !ts2.isExpressionStatement(node.parent)) {
|
|
118
324
|
fail("expose requires a literal machine name and a flat telemetry object in a synchronous cyclic routine.");
|
|
@@ -151,7 +357,7 @@ var lowerExposure = (program, sdk) => {
|
|
|
151
357
|
fail(`Telemetry ${property.name.text} needs a concrete BOOL, integer up to 32 bits or bounded STRING annotation.`);
|
|
152
358
|
return;
|
|
153
359
|
}
|
|
154
|
-
fields.push({ name: property.name.text, type: annotation, value: value
|
|
360
|
+
fields.push({ name: property.name.text, type: annotation, value: copied(value) });
|
|
155
361
|
}
|
|
156
362
|
if (!fields.length) {
|
|
157
363
|
fail("Expose at least one telemetry field.");
|
|
@@ -164,24 +370,19 @@ var lowerExposure = (program, sdk) => {
|
|
|
164
370
|
name: label.text,
|
|
165
371
|
fields: fields.map(({ name, type }) => ({ name, type }))
|
|
166
372
|
})).digest("hex");
|
|
167
|
-
extra.push(`export interface ${record}{contractVersion:STRING<64>;${fields.map((field) => `${field.name}:${field.type}`).join(";")}}
|
|
168
|
-
export let ${name}:${record}=defaultValue<${record}>();`);
|
|
373
|
+
extra.push(from(node, `export interface ${record}{contractVersion:STRING<64>;${fields.map((field) => `${field.name}:${field.type}`).join(";")}}
|
|
374
|
+
export let ${name}:${record}=defaultValue<${record}>();`));
|
|
169
375
|
variables.set(`${source.fileName}:${name}`, { name: label.text, version });
|
|
170
376
|
edits.push({
|
|
171
377
|
start: node.getStart(source),
|
|
172
378
|
end: node.end,
|
|
173
|
-
text: `{${name}.contractVersion=${JSON.stringify(version)};${fields.map((field) => `${name}.${field.name}=${field.value};`)
|
|
379
|
+
text: mapped`{${name}.contractVersion=${JSON.stringify(version)};${joined(fields.map((field) => mapped`${name}.${field.name}=${field.value};`), "")}}`
|
|
174
380
|
});
|
|
175
381
|
};
|
|
176
382
|
visit(source);
|
|
177
|
-
if (
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
for (const edit of edits.sort((a, b) => b.start - a.start))
|
|
181
|
-
text = text.slice(0, edit.start) + edit.text + text.slice(edit.end);
|
|
182
|
-
sources.set(source.fileName, text + `
|
|
183
|
-
` + extra.join(`
|
|
184
|
-
`));
|
|
383
|
+
if (edits.length)
|
|
384
|
+
sources.set(source.fileName, mapped`${edited(source, edits)}\n${joined(extra, `
|
|
385
|
+
`)}`);
|
|
185
386
|
}
|
|
186
387
|
return { sources, diagnostics, variables };
|
|
187
388
|
};
|
|
@@ -280,7 +481,7 @@ var procedureAt = (checker, router, path) => {
|
|
|
280
481
|
return { kind: kind.value, input, output };
|
|
281
482
|
};
|
|
282
483
|
var pascal = (path) => path.split(".").map((part) => part[0].toUpperCase() + part.slice(1)).join("");
|
|
283
|
-
var lowerServices = (program, sdk, options) => {
|
|
484
|
+
var lowerServices = (program, sdk, positions, options) => {
|
|
284
485
|
const sources = new Map;
|
|
285
486
|
const diagnostics = [];
|
|
286
487
|
const records = new Map;
|
|
@@ -292,16 +493,7 @@ var lowerServices = (program, sdk, options) => {
|
|
|
292
493
|
value = checker.getAliasedSymbol(value);
|
|
293
494
|
return value;
|
|
294
495
|
};
|
|
295
|
-
const fail = (node, code, message) =>
|
|
296
|
-
const source = node.getSourceFile(), start = node.getStart(source), position = source.getLineAndCharacterOfPosition(start);
|
|
297
|
-
diagnostics.push(error2(code, message, {
|
|
298
|
-
file: source.fileName,
|
|
299
|
-
start,
|
|
300
|
-
end: node.end,
|
|
301
|
-
line: position.line + 1,
|
|
302
|
-
column: position.character + 1
|
|
303
|
-
}));
|
|
304
|
-
};
|
|
496
|
+
const fail = (node, code, message) => diagnostics.push(error2(code, message, positions.node(node)));
|
|
305
497
|
const record = (layout, name) => {
|
|
306
498
|
const key = recordKey(layout);
|
|
307
499
|
const existing = records.get(key);
|
|
@@ -311,7 +503,7 @@ var lowerServices = (program, sdk, options) => {
|
|
|
311
503
|
return name;
|
|
312
504
|
};
|
|
313
505
|
const clients = new Map;
|
|
314
|
-
let
|
|
506
|
+
let module;
|
|
315
507
|
const sourceFiles = runtimeSources(program).filter((source) => !source.isDeclarationFile);
|
|
316
508
|
for (const source of sourceFiles)
|
|
317
509
|
for (const statement of source.statements) {
|
|
@@ -331,7 +523,7 @@ var lowerServices = (program, sdk, options) => {
|
|
|
331
523
|
fail(call, "PLC1013", "HTTP service transport requires server.baseUrlEnv.");
|
|
332
524
|
else {
|
|
333
525
|
clients.set(client, checker.getTypeFromTypeNode(router));
|
|
334
|
-
|
|
526
|
+
module ??= { file: join(dirname2(source.fileName), ".tsplc-services.ts"), client: call };
|
|
335
527
|
}
|
|
336
528
|
}
|
|
337
529
|
}
|
|
@@ -414,23 +606,19 @@ var lowerServices = (program, sdk, options) => {
|
|
|
414
606
|
visit(source);
|
|
415
607
|
if (!edits.length)
|
|
416
608
|
continue;
|
|
417
|
-
let text = source
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
const path = relative(dirname2(source.fileName), file).replaceAll("\\", "/");
|
|
422
|
-
text += `
|
|
423
|
-
import {${[...imports].map(([name, local]) => `${name} as ${local}`).join(",")}} from ${JSON.stringify(path.startsWith("../") ? path : `./${path}`)};
|
|
424
|
-
`;
|
|
609
|
+
let text = edited(source, edits);
|
|
610
|
+
if (imports.size && module) {
|
|
611
|
+
const path = relative(dirname2(source.fileName), module.file).replaceAll("\\", "/");
|
|
612
|
+
text = mapped`${text}\nimport {${[...imports].map(([name, local]) => `${name} as ${local}`).join(",")}} from ${JSON.stringify(path.startsWith("../") ? path : `./${path}`)};\n`;
|
|
425
613
|
}
|
|
426
614
|
sources.set(source.fileName, text);
|
|
427
615
|
}
|
|
428
|
-
if (
|
|
429
|
-
sources.set(file, serviceModule(records, calls, options));
|
|
616
|
+
if (module && options)
|
|
617
|
+
sources.set(module.file, from(module.client, serviceModule(records, calls, options)));
|
|
430
618
|
return {
|
|
431
619
|
sources,
|
|
432
620
|
diagnostics,
|
|
433
|
-
file,
|
|
621
|
+
file: module?.file,
|
|
434
622
|
records: new Map([...records].map(([key, { name }]) => [key, name]))
|
|
435
623
|
};
|
|
436
624
|
};
|
|
@@ -498,7 +686,7 @@ var serviceRecords = (program, lowering) => {
|
|
|
498
686
|
import ts4 from "typescript";
|
|
499
687
|
import { dirname as dirname3, relative as relative2 } from "node:path";
|
|
500
688
|
import { error as error3 } from "@tsplc/compiler/ir";
|
|
501
|
-
var lowerPromises = (program, sdk) => {
|
|
689
|
+
var lowerPromises = (program, sdk, positions) => {
|
|
502
690
|
const checker = program.getTypeChecker();
|
|
503
691
|
const sources = new Map, diagnostics = [];
|
|
504
692
|
const runtimeBlocks = new Map;
|
|
@@ -516,20 +704,16 @@ var lowerPromises = (program, sdk) => {
|
|
|
516
704
|
const value = symbol(node);
|
|
517
705
|
return value?.name === name && value.declarations?.some((declaration) => declaration.getSourceFile().fileName.startsWith(dirname3(sdk) + "/"));
|
|
518
706
|
};
|
|
519
|
-
const diagnosticFor = (node, message) =>
|
|
520
|
-
const source = node.getSourceFile(), start = node.getStart(source), position = source.getLineAndCharacterOfPosition(start);
|
|
521
|
-
return error3("PLC1012", message, {
|
|
522
|
-
file: source.fileName,
|
|
523
|
-
start,
|
|
524
|
-
end: node.end,
|
|
525
|
-
line: position.line + 1,
|
|
526
|
-
column: position.character + 1
|
|
527
|
-
});
|
|
528
|
-
};
|
|
707
|
+
const diagnosticFor = (node, message) => error3("PLC1012", message, positions.node(node));
|
|
529
708
|
const fail = (node, message) => {
|
|
530
709
|
throw { promiseDiagnostic: diagnosticFor(node, message) };
|
|
531
710
|
};
|
|
532
|
-
const append = (
|
|
711
|
+
const append = (scope, origin, text) => {
|
|
712
|
+
if (ts4.isClassDeclaration(scope))
|
|
713
|
+
methods.set(scope, [...methods.get(scope) ?? [], from(origin, text)]);
|
|
714
|
+
else
|
|
715
|
+
additions.set(scope, [...additions.get(scope) ?? [], from(origin, text)]);
|
|
716
|
+
};
|
|
533
717
|
const edit = (node, text) => {
|
|
534
718
|
const source = node.getSourceFile();
|
|
535
719
|
edits.set(source, [
|
|
@@ -592,7 +776,7 @@ var lowerPromises = (program, sdk) => {
|
|
|
592
776
|
if (!alias) {
|
|
593
777
|
alias = `TsplcPromiseType${sequence++}`;
|
|
594
778
|
aliases.set(node, alias);
|
|
595
|
-
append(node.getSourceFile(), `export type ${alias}=${node.getText(node.getSourceFile())};`);
|
|
779
|
+
append(node.getSourceFile(), node, `export type ${alias}=${node.getText(node.getSourceFile())};`);
|
|
596
780
|
}
|
|
597
781
|
const path = relative2(dirname3(source.fileName), node.getSourceFile().fileName).replaceAll("\\", "/");
|
|
598
782
|
const importedAliases = typeImports.get(source) ?? new Set;
|
|
@@ -600,7 +784,7 @@ var lowerPromises = (program, sdk) => {
|
|
|
600
784
|
return alias;
|
|
601
785
|
importedAliases.add(alias);
|
|
602
786
|
typeImports.set(source, importedAliases);
|
|
603
|
-
append(source, `import type {${alias}} from ${JSON.stringify(path.startsWith(".") ? path : `./${path}`)};`);
|
|
787
|
+
append(source, node, `import type {${alias}} from ${JSON.stringify(path.startsWith(".") ? path : `./${path}`)};`);
|
|
604
788
|
return alias;
|
|
605
789
|
};
|
|
606
790
|
const expressionType = (node, source) => {
|
|
@@ -669,18 +853,18 @@ var lowerPromises = (program, sdk) => {
|
|
|
669
853
|
}
|
|
670
854
|
return node.getChildren().some((child) => ts4.isTypeNode(child) && hasBorrow(child, seen));
|
|
671
855
|
};
|
|
672
|
-
let
|
|
856
|
+
let diagnosticOwner;
|
|
673
857
|
const diag = () => {
|
|
674
|
-
if (!
|
|
858
|
+
if (!diagnosticOwner)
|
|
675
859
|
throw new Error("Missing async diagnostics owner");
|
|
676
860
|
return "tsplcPromiseDiagnostics";
|
|
677
861
|
};
|
|
678
862
|
const imported = new Set;
|
|
679
|
-
const ensureImports = (source) => {
|
|
863
|
+
const ensureImports = (source, origin) => {
|
|
680
864
|
if (imported.has(source))
|
|
681
865
|
return;
|
|
682
866
|
imported.add(source);
|
|
683
|
-
append(source, `import {cooperativeTasks as tsplcCooperative,errorCode as tsplcErrorCode} from "@tsplc/compiler/async";import {wrapAdd as tsplcAsyncWrapAdd} from "@tsplc/compiler/types";`);
|
|
867
|
+
append(source, origin, `import {cooperativeTasks as tsplcCooperative,errorCode as tsplcErrorCode} from "@tsplc/compiler/async";import {wrapAdd as tsplcAsyncWrapAdd} from "@tsplc/compiler/types";`);
|
|
684
868
|
};
|
|
685
869
|
const scopes = new Map;
|
|
686
870
|
const make = (expression, owner, detached) => {
|
|
@@ -689,8 +873,8 @@ var lowerPromises = (program, sdk) => {
|
|
|
689
873
|
fail(expression, "Expected a statically resolved async call.");
|
|
690
874
|
const source = expression.getSourceFile();
|
|
691
875
|
const classOwner = ts4.isMethodDeclaration(owner) && ts4.isClassDeclaration(owner.parent) ? owner.parent : undefined;
|
|
692
|
-
ensureImports(source);
|
|
693
|
-
|
|
876
|
+
ensureImports(source, expression);
|
|
877
|
+
diagnosticOwner ??= expression;
|
|
694
878
|
const captures = new Map;
|
|
695
879
|
const collectCaptures = (handler) => {
|
|
696
880
|
const visit = (node) => {
|
|
@@ -792,10 +976,7 @@ var lowerPromises = (program, sdk) => {
|
|
|
792
976
|
const signature = params.map((value) => `${value.name}:${value.type}`).join(","), args = params.map((value) => value.name).join(",");
|
|
793
977
|
const addHelper = (name, body, type, extra) => {
|
|
794
978
|
const text = `${classOwner ? "private " : "export "}async ${classOwner ? "" : "function "}${name}(${[signature, extra ? `promiseInput:${extra.type}` : ""].filter(Boolean).join(",")}):Promise<${type}>{${body}}`;
|
|
795
|
-
|
|
796
|
-
methods.set(classOwner, [...methods.get(classOwner) ?? [], text]);
|
|
797
|
-
else
|
|
798
|
-
append(source, text);
|
|
979
|
+
append(classOwner ?? source, expression, text);
|
|
799
980
|
return `${classOwner ? "this." : ""}${name}(${[args, extra?.argument ?? ""].filter(Boolean).join(",")})`;
|
|
800
981
|
};
|
|
801
982
|
const finish = (call, type, discard = false) => type === "void" || discard ? `await ${call};return;` : `return await ${call};`;
|
|
@@ -869,10 +1050,7 @@ var lowerPromises = (program, sdk) => {
|
|
|
869
1050
|
...params.map((value) => `${value.name}:${value.type}`)
|
|
870
1051
|
].join(",");
|
|
871
1052
|
const text = `${classOwner ? "private " : "export "}async ${classOwner ? "" : "function "}${name}(${handlerParams}):Promise<${type}>{${code}}`;
|
|
872
|
-
|
|
873
|
-
methods.set(classOwner, [...methods.get(classOwner) ?? [], text]);
|
|
874
|
-
else
|
|
875
|
-
append(source, text);
|
|
1053
|
+
append(classOwner ?? source, declaration, text);
|
|
876
1054
|
return {
|
|
877
1055
|
call: `${classOwner ? "this." : ""}${name}(${[...parameter && inputType !== "void" ? [input] : [], ...params.map((value) => value.name)].join(",")})`,
|
|
878
1056
|
type,
|
|
@@ -908,10 +1086,7 @@ var lowerPromises = (program, sdk) => {
|
|
|
908
1086
|
const site = `tsplcPromiseSite${sequence++}`;
|
|
909
1087
|
const callable = prefix.slice(0, prefix.indexOf("("));
|
|
910
1088
|
const declaration = `${classOwner ? "private " : "const "}${site}=tsplcCooperative.define(${callable});`;
|
|
911
|
-
|
|
912
|
-
methods.set(classOwner, [...methods.get(classOwner) ?? [], declaration]);
|
|
913
|
-
else
|
|
914
|
-
append(source, declaration);
|
|
1089
|
+
append(classOwner ?? source, expression, declaration);
|
|
915
1090
|
const scope = classOwner ?? source;
|
|
916
1091
|
scopes.set(scope, [...scopes.get(scope) ?? [], site]);
|
|
917
1092
|
return `${classOwner ? "this." : ""}${site}.start(${params.map((value) => value.expression).join(",")});`;
|
|
@@ -929,7 +1104,7 @@ var lowerPromises = (program, sdk) => {
|
|
|
929
1104
|
return;
|
|
930
1105
|
}
|
|
931
1106
|
if (ts4.isCallExpression(node) && official(node.expression, "asyncDiagnostics")) {
|
|
932
|
-
|
|
1107
|
+
diagnosticOwner ??= node;
|
|
933
1108
|
diagnosticsCalls.push(node);
|
|
934
1109
|
return;
|
|
935
1110
|
}
|
|
@@ -980,16 +1155,13 @@ var lowerPromises = (program, sdk) => {
|
|
|
980
1155
|
diagnostics.push(diagnosticFor(node, "cancelAsync takes this in a controller, or no argument in a module."));
|
|
981
1156
|
const name = `tsplcCancelScope${sequence++}`;
|
|
982
1157
|
const body = (scopes.get(scope) ?? []).map((site) => `${ts4.isClassDeclaration(scope) ? "this." : ""}${site}.cancel();`).join("");
|
|
983
|
-
|
|
984
|
-
methods.set(scope, [...methods.get(scope) ?? [], `private ${name}():void{${body}}`]);
|
|
985
|
-
else
|
|
986
|
-
append(scope, `function ${name}():void{${body}}`);
|
|
1158
|
+
append(scope, node, ts4.isClassDeclaration(scope) ? `private ${name}():void{${body}}` : `function ${name}():void{${body}}`);
|
|
987
1159
|
edit(node, `${ts4.isClassDeclaration(scope) ? "this." : ""}${name}()`);
|
|
988
1160
|
}
|
|
989
|
-
if (
|
|
990
|
-
const source =
|
|
991
|
-
ensureImports(source);
|
|
992
|
-
append(source, `export class TsplcPromiseDiagnostics extends FunctionBlock<{}>{private count:UDINT=0;private lastError:UDINT=0;public report(code:UDINT,count:UDINT):BOOL{this.count=tsplcAsyncWrapAdd<UDINT>(this.count,count);this.lastError=code;return true;}public snapshot():{valid:BOOL;count:UDINT;lastError:UDINT}{return {valid:true,count:this.count,lastError:this.lastError};}protected execute(input:{}):void{}}
|
|
1161
|
+
if (diagnosticOwner) {
|
|
1162
|
+
const source = diagnosticOwner.getSourceFile();
|
|
1163
|
+
ensureImports(source, diagnosticOwner);
|
|
1164
|
+
append(source, diagnosticOwner, `export class TsplcPromiseDiagnostics extends FunctionBlock<{}>{private count:UDINT=0;private lastError:UDINT=0;public report(code:UDINT,count:UDINT):BOOL{this.count=tsplcAsyncWrapAdd<UDINT>(this.count,count);this.lastError=code;return true;}public snapshot():{valid:BOOL;count:UDINT;lastError:UDINT}{return {valid:true,count:this.count,lastError:this.lastError};}protected execute(input:{}):void{}}
|
|
993
1165
|
export const tsplcPromiseDiagnostics=new TsplcPromiseDiagnostics();`);
|
|
994
1166
|
runtimeBlocks.set(`${source.fileName}:TsplcPromiseDiagnostics`, { kind: "mailbox" });
|
|
995
1167
|
for (const file of new Set([
|
|
@@ -998,7 +1170,7 @@ export const tsplcPromiseDiagnostics=new TsplcPromiseDiagnostics();`);
|
|
|
998
1170
|
])) {
|
|
999
1171
|
if (file !== source) {
|
|
1000
1172
|
const path = relative2(dirname3(file.fileName), source.fileName).replaceAll("\\", "/");
|
|
1001
|
-
append(file, `import {${diag()}} from ${JSON.stringify(path.startsWith(".") ? path : `./${path}`)};`);
|
|
1173
|
+
append(file, file, `import {${diag()}} from ${JSON.stringify(path.startsWith(".") ? path : `./${path}`)};`);
|
|
1002
1174
|
}
|
|
1003
1175
|
}
|
|
1004
1176
|
for (const call of diagnosticsCalls)
|
|
@@ -1008,28 +1180,23 @@ export const tsplcPromiseDiagnostics=new TsplcPromiseDiagnostics();`);
|
|
|
1008
1180
|
const source = owner.getSourceFile();
|
|
1009
1181
|
edits.set(source, [
|
|
1010
1182
|
...edits.get(source) ?? [],
|
|
1011
|
-
{ start: owner.end - 1, end: owner.end - 1, text: `
|
|
1012
|
-
`
|
|
1013
|
-
`) }
|
|
1183
|
+
{ start: owner.end - 1, end: owner.end - 1, text: mapped`\n${joined(texts, `
|
|
1184
|
+
`)}` }
|
|
1014
1185
|
]);
|
|
1015
1186
|
}
|
|
1016
1187
|
for (const source of files) {
|
|
1017
1188
|
const changes = edits.get(source) ?? [], extra = additions.get(source) ?? [];
|
|
1018
1189
|
if (!changes.length && !extra.length)
|
|
1019
1190
|
continue;
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
text = text.slice(0, change.start) + change.text + text.slice(change.end);
|
|
1023
|
-
sources.set(source.fileName, text + `
|
|
1024
|
-
` + extra.join(`
|
|
1025
|
-
`));
|
|
1191
|
+
sources.set(source.fileName, mapped`${edited(source, changes)}\n${joined(extra, `
|
|
1192
|
+
`)}`);
|
|
1026
1193
|
}
|
|
1027
1194
|
return { sources, diagnostics, runtimeBlocks };
|
|
1028
1195
|
};
|
|
1029
1196
|
|
|
1030
1197
|
// packages/compiler/src/frontend/async.ts
|
|
1031
1198
|
import ts6 from "typescript";
|
|
1032
|
-
import { dirname as dirname5, resolve, relative as relative3 } from "node:path";
|
|
1199
|
+
import { dirname as dirname5, resolve as resolve2, relative as relative3 } from "node:path";
|
|
1033
1200
|
|
|
1034
1201
|
// packages/compiler/src/frontend/cooperative.ts
|
|
1035
1202
|
var cooperativeSite = (name, parameters, worker, inline) => {
|
|
@@ -1092,7 +1259,7 @@ var symbolAt = (checker, node) => {
|
|
|
1092
1259
|
symbol = checker.getAliasedSymbol(symbol);
|
|
1093
1260
|
return symbol;
|
|
1094
1261
|
};
|
|
1095
|
-
var lowerEnvironment = (program, sdk) => {
|
|
1262
|
+
var lowerEnvironment = (program, sdk, positions) => {
|
|
1096
1263
|
const checker = program.getTypeChecker();
|
|
1097
1264
|
const sources = new Map;
|
|
1098
1265
|
const diagnostics = [];
|
|
@@ -1117,16 +1284,9 @@ var lowerEnvironment = (program, sdk) => {
|
|
|
1117
1284
|
message = `Required environment value ${name.text} is missing.`;
|
|
1118
1285
|
else if (value.includes("\x00"))
|
|
1119
1286
|
message = `Environment value ${name.text} contains an unsupported NUL byte.`;
|
|
1120
|
-
if (message)
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
file: source.fileName,
|
|
1124
|
-
start,
|
|
1125
|
-
end: node.end,
|
|
1126
|
-
line: position.line + 1,
|
|
1127
|
-
column: position.character + 1
|
|
1128
|
-
}));
|
|
1129
|
-
} else if (value !== undefined)
|
|
1287
|
+
if (message)
|
|
1288
|
+
diagnostics.push(error4("PLC1011", message, positions.node(node)));
|
|
1289
|
+
else if (value !== undefined)
|
|
1130
1290
|
edits.push({
|
|
1131
1291
|
start: node.getStart(source),
|
|
1132
1292
|
end: node.end,
|
|
@@ -1138,12 +1298,8 @@ var lowerEnvironment = (program, sdk) => {
|
|
|
1138
1298
|
ts5.forEachChild(node, visit);
|
|
1139
1299
|
};
|
|
1140
1300
|
visit(source);
|
|
1141
|
-
if (
|
|
1142
|
-
|
|
1143
|
-
let text = source.text;
|
|
1144
|
-
for (const edit of edits.sort((a, b) => b.start - a.start))
|
|
1145
|
-
text = text.slice(0, edit.start) + edit.text + text.slice(edit.end);
|
|
1146
|
-
sources.set(source.fileName, text);
|
|
1301
|
+
if (edits.length)
|
|
1302
|
+
sources.set(source.fileName, edited(source, edits));
|
|
1147
1303
|
}
|
|
1148
1304
|
return { sources, diagnostics };
|
|
1149
1305
|
};
|
|
@@ -1215,11 +1371,14 @@ var staticString = (checker, root) => {
|
|
|
1215
1371
|
|
|
1216
1372
|
// packages/compiler/src/frontend/async.ts
|
|
1217
1373
|
import { error as error5 } from "@tsplc/compiler/ir";
|
|
1218
|
-
var
|
|
1219
|
-
var
|
|
1374
|
+
var terminated = (node) => ts6.isExpressionStatement(node) || ts6.isVariableStatement(node) || ts6.isReturnStatement(node) || ts6.isThrowStatement(node) || ts6.isBreakOrContinueStatement(node);
|
|
1375
|
+
var awaitedCall = (node) => ts6.isAwaitExpression(node) ? node.expression : node;
|
|
1376
|
+
var copyValue = (value, aggregate) => aggregate ? mapped`copy(${value})` : value;
|
|
1377
|
+
var lowerAsync = (program, sdk, positions) => {
|
|
1220
1378
|
const result = {
|
|
1221
1379
|
sources: new Map,
|
|
1222
1380
|
blocks: new Map,
|
|
1381
|
+
jobs: new Map,
|
|
1223
1382
|
programs: {},
|
|
1224
1383
|
schedules: new Map,
|
|
1225
1384
|
diagnostics: [],
|
|
@@ -1236,18 +1395,7 @@ var lowerAsync = (program, sdk) => {
|
|
|
1236
1395
|
const s = symbol(node);
|
|
1237
1396
|
return s?.name === name && s.declarations?.some((d) => d.getSourceFile().fileName.startsWith(dirname5(sdk) + "/"));
|
|
1238
1397
|
};
|
|
1239
|
-
const diagnosticFor = (node, message) =>
|
|
1240
|
-
const source = node.getSourceFile();
|
|
1241
|
-
const start = node.getStart(source);
|
|
1242
|
-
const position = source.getLineAndCharacterOfPosition(start);
|
|
1243
|
-
return error5("PLC1010", message, {
|
|
1244
|
-
file: source.fileName,
|
|
1245
|
-
start,
|
|
1246
|
-
end: node.end,
|
|
1247
|
-
line: position.line + 1,
|
|
1248
|
-
column: position.character + 1
|
|
1249
|
-
});
|
|
1250
|
-
};
|
|
1398
|
+
const diagnosticFor = (node, message) => error5("PLC1010", message, positions.node(node));
|
|
1251
1399
|
const fail = (node, message) => {
|
|
1252
1400
|
throw { asyncDiagnostic: diagnosticFor(node, message) };
|
|
1253
1401
|
};
|
|
@@ -1277,7 +1425,6 @@ var lowerAsync = (program, sdk) => {
|
|
|
1277
1425
|
if (!functions.size)
|
|
1278
1426
|
return result;
|
|
1279
1427
|
const aliasPrefix = (fn) => `TsplcAsync${fn.name.getText(fn.getSourceFile())}${fn.getStart(fn.getSourceFile())}`;
|
|
1280
|
-
const printer = ts6.createPrinter({ removeComments: false });
|
|
1281
1428
|
let sequence = 0;
|
|
1282
1429
|
const ownedContinuations = new Map;
|
|
1283
1430
|
const ownedJobs = new Map;
|
|
@@ -1356,8 +1503,8 @@ var lowerAsync = (program, sdk) => {
|
|
|
1356
1503
|
type = `${aliasPrefix(called)}Result`;
|
|
1357
1504
|
const path = relative3(dirname5(source.fileName), called.getSourceFile().fileName).replaceAll("\\", "/");
|
|
1358
1505
|
const statement = `import type {${type}} from ${JSON.stringify(path.startsWith(".") ? path : `./${path}`)};`;
|
|
1359
|
-
if (!extra.
|
|
1360
|
-
extra.push(statement);
|
|
1506
|
+
if (!extra.some((item) => item.text === statement))
|
|
1507
|
+
extra.push(from(node, statement));
|
|
1361
1508
|
}
|
|
1362
1509
|
}
|
|
1363
1510
|
}
|
|
@@ -1374,44 +1521,54 @@ var lowerAsync = (program, sdk) => {
|
|
|
1374
1521
|
};
|
|
1375
1522
|
collect(fn.body);
|
|
1376
1523
|
const rewrite = (node) => {
|
|
1377
|
-
const
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1524
|
+
const edits = [];
|
|
1525
|
+
const visit = (n) => {
|
|
1526
|
+
const replacement = (() => {
|
|
1527
|
+
if (method && ts6.isPropertyAccessExpression(n) && n.expression.kind === ts6.SyntaxKind.ThisKeyword)
|
|
1528
|
+
return `this[${JSON.stringify(n.name.text)}]`;
|
|
1529
|
+
if (ts6.isIdentifier(n) && !(ts6.isPropertyAccessExpression(n.parent) && n.parent.name === n) && !(ts6.isPropertyAssignment(n.parent) && n.parent.name === n)) {
|
|
1530
|
+
const field = fields.get(symbol(n));
|
|
1531
|
+
if (field)
|
|
1532
|
+
return `this.${field.name}`;
|
|
1533
|
+
}
|
|
1534
|
+
if (ts6.isShorthandPropertyAssignment(n)) {
|
|
1535
|
+
const value = checker.getShorthandAssignmentValueSymbol(n), field = value && fields.get(value);
|
|
1536
|
+
if (field)
|
|
1537
|
+
return `${n.name.text}: this.${field.name}`;
|
|
1538
|
+
}
|
|
1539
|
+
return;
|
|
1540
|
+
})();
|
|
1541
|
+
if (replacement === undefined)
|
|
1542
|
+
ts6.forEachChild(n, visit);
|
|
1543
|
+
else
|
|
1544
|
+
edits.push({ start: n.getStart(source), end: n.end, text: replacement });
|
|
1545
|
+
};
|
|
1546
|
+
visit(node);
|
|
1547
|
+
const text = copied(node);
|
|
1548
|
+
const start = node.getStart(source);
|
|
1549
|
+
const result = edited(text, edits.map((edit) => ({ ...edit, start: edit.start - start, end: edit.end - start })));
|
|
1550
|
+
return terminated(node) && !result.text.endsWith(";") ? mapped`${result};` : result;
|
|
1401
1551
|
};
|
|
1402
1552
|
const nodes = new Map;
|
|
1403
1553
|
const yielding = new Set;
|
|
1554
|
+
const steps = [];
|
|
1404
1555
|
let nextId = 1;
|
|
1405
|
-
const state = (body, yields = false) => {
|
|
1556
|
+
const state = (body, origin, kind, yields = false) => {
|
|
1406
1557
|
const id = nextId++;
|
|
1407
|
-
nodes.set(id, body);
|
|
1558
|
+
nodes.set(id, from(origin, body));
|
|
1559
|
+
steps.push({
|
|
1560
|
+
step: id,
|
|
1561
|
+
kind,
|
|
1562
|
+
span: positions.node(origin),
|
|
1563
|
+
text: positions.excerpt(kind === "await" ? awaitedCall(origin) : origin)
|
|
1564
|
+
});
|
|
1408
1565
|
if (yields)
|
|
1409
1566
|
yielding.add(id);
|
|
1410
1567
|
return id;
|
|
1411
1568
|
};
|
|
1412
1569
|
const children = [], resets = [], cancels = [];
|
|
1413
|
-
const finish = (value) => `this.value = ${copyValue(value, resultAggregate)}; this.busy = false; this.done = true; this.step = 0;`;
|
|
1414
|
-
const failure = (error) => `this.error = ${error}; if(this.error === 0)this.error=4; this.busy = false; this.done = true; this.step = 0;`;
|
|
1570
|
+
const finish = (value) => mapped`this.value = ${copyValue(value, resultAggregate)}; this.busy = false; this.done = true; this.step = 0;`;
|
|
1571
|
+
const failure = (error) => mapped`this.error = ${error}; if(this.error === 0)this.error=4; this.busy = false; this.done = true; this.step = 0;`;
|
|
1415
1572
|
const awaitState = (awaited, target, next, reject) => {
|
|
1416
1573
|
const expression = ts6.isAwaitExpression(awaited) ? awaited.expression : awaited;
|
|
1417
1574
|
if (!ts6.isCallExpression(expression))
|
|
@@ -1423,8 +1580,8 @@ var lowerAsync = (program, sdk) => {
|
|
|
1423
1580
|
fail(call, "sleep takes one TIME and returns void.");
|
|
1424
1581
|
children.push(`private ${child} = new OnDelayTimer();`);
|
|
1425
1582
|
resets.push(`this.${child}.update({enabled:false,duration:ms(0)});`);
|
|
1426
|
-
const poll = state(`this.${child}.update({enabled:true,duration:${rewrite(call.arguments[0])}}); if(this.${child}.out.done) { this.step = ${next}; }
|
|
1427
|
-
return state(`this.${child}.update({enabled:true,duration:${rewrite(call.arguments[0])}});this.step=${poll};`, true);
|
|
1583
|
+
const poll = state(mapped`this.${child}.update({enabled:true,duration:${rewrite(call.arguments[0])}}); if(this.${child}.out.done) { this.step = ${next}; }`, awaited, "await");
|
|
1584
|
+
return state(mapped`this.${child}.update({enabled:true,duration:${rewrite(call.arguments[0])}});this.step=${poll};`, awaited, "await", true);
|
|
1428
1585
|
}
|
|
1429
1586
|
if (official(name, "fetch") || official(name, "opcuaCall")) {
|
|
1430
1587
|
const rpc = official(name, "opcuaCall");
|
|
@@ -1457,7 +1614,7 @@ var lowerAsync = (program, sdk) => {
|
|
|
1457
1614
|
const responseType = text(call.typeArguments[0]), httpName = `Tsplc${rpc ? "Rpc" : "Http"}${sequence++}`;
|
|
1458
1615
|
let requestType = `${httpName}Request`;
|
|
1459
1616
|
if (!json)
|
|
1460
|
-
extra.push(`interface ${requestType} {reserved:BOOL}`);
|
|
1617
|
+
extra.push(from(call, `interface ${requestType} {reserved:BOOL}`));
|
|
1461
1618
|
if (json) {
|
|
1462
1619
|
if (call.typeArguments[1])
|
|
1463
1620
|
requestType = text(call.typeArguments[1]);
|
|
@@ -1468,9 +1625,9 @@ var lowerAsync = (program, sdk) => {
|
|
|
1468
1625
|
requestType = checker.typeToString(layout, json, ts6.TypeFormatFlags.NoTruncation | ts6.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope);
|
|
1469
1626
|
}
|
|
1470
1627
|
}
|
|
1471
|
-
extra.push(`interface ${httpName}Input {start:BOOL;cancel:BOOL;request:${requestType}}
|
|
1628
|
+
extra.push(from(call, `interface ${httpName}Input {start:BOOL;cancel:BOOL;request:${requestType}}
|
|
1472
1629
|
interface ${httpName}Output {busy:BOOL;done:BOOL;error:UDINT;result:${responseType}}
|
|
1473
|
-
class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { protected execute(input:${httpName}Input):${httpName}Output {return {busy:false,done:false,error:0,result:defaultValue<${responseType}>()};} }`);
|
|
1630
|
+
class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { protected execute(input:${httpName}Input):${httpName}Output {return {busy:false,done:false,error:0,result:defaultValue<${responseType}>()};} }`));
|
|
1474
1631
|
result.blocks.set(`${source.fileName}:${httpName}`, rpc ? { kind: "rpc", path: url } : {
|
|
1475
1632
|
kind: "http",
|
|
1476
1633
|
url,
|
|
@@ -1480,7 +1637,7 @@ class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { pr
|
|
|
1480
1637
|
children.push(`private ${child} = new ${httpName}();`);
|
|
1481
1638
|
resets.push(`this.${child}.update({start:false,cancel:false,request:defaultValue<${requestType}>()});`);
|
|
1482
1639
|
cancels.push(`this.${child}.update({start:false,cancel:true,request:defaultValue<${requestType}>()});`);
|
|
1483
|
-
return state(`this.${child}.update({start:true,cancel:false,request:${json ? rewrite(json) : `defaultValue<${requestType}>()`}}); if(this.${child}.out.done) { if(this.${child}.out.error !== 0) {${reject(`this.${child}.out.error`, true)}} else {${target ? `${target} = ${copyValue(`this.${child}.out.result`, Boolean(checker.getAwaitedType(checker.getTypeAtLocation(call)).flags & ts6.TypeFlags.Object))};` : ""}this.step = ${next};} }
|
|
1640
|
+
return state(mapped`this.${child}.update({start:true,cancel:false,request:${json ? rewrite(json) : `defaultValue<${requestType}>()`}}); if(this.${child}.out.done) { if(this.${child}.out.error !== 0) {${reject(`this.${child}.out.error`, true)}} else {${target ? mapped`${target} = ${copyValue(`this.${child}.out.result`, Boolean(checker.getAwaitedType(checker.getTypeAtLocation(call)).flags & ts6.TypeFlags.Object))};` : ""}this.step = ${next};} }`, awaited, "await");
|
|
1484
1641
|
}
|
|
1485
1642
|
const jobDeclaration = symbol(name)?.declarations?.find((node) => ts6.isVariableDeclaration(node) || ts6.isPropertyDeclaration(node));
|
|
1486
1643
|
const jobInitializer = jobDeclaration && (ts6.isVariableDeclaration(jobDeclaration) || ts6.isPropertyDeclaration(jobDeclaration)) ? jobDeclaration.initializer : undefined;
|
|
@@ -1489,8 +1646,8 @@ class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { pr
|
|
|
1489
1646
|
children.push(`private ${borrow}:BOOL=false;`);
|
|
1490
1647
|
resets.push(`this.${borrow}=false;`);
|
|
1491
1648
|
cancels.push(`if(this.${borrow}){${receiver}.cancel();const borrowed=${receiver}.snapshot();if(!borrowed.valid||borrowed.busy)return;if(!${receiver}.reset())return;this.${borrow}=false;}`);
|
|
1492
|
-
const poll = state(`const borrowed=${receiver}.snapshot();if(borrowed.valid&&borrowed.done){if(${receiver}.reset()){this.${borrow}=false;if(borrowed.error!==0){${reject("borrowed.error", true)}}else{${target ? `${target}=${copyValue("borrowed.result", Boolean(checker.getAwaitedType(checker.getTypeAtLocation(call)).flags & ts6.TypeFlags.Object))};` : ""}this.step=${next};}}}
|
|
1493
|
-
return state(`const available=${receiver}.snapshot();if(!available.valid)return;if(available.busy||available.done){${reject("7")}}else{const accepted:BOOL=${receiver}.start(${call.arguments.map(rewrite)
|
|
1649
|
+
const poll = state(mapped`const borrowed=${receiver}.snapshot();if(borrowed.valid&&borrowed.done){if(${receiver}.reset()){this.${borrow}=false;if(borrowed.error!==0){${reject("borrowed.error", true)}}else{${target ? mapped`${target}=${copyValue("borrowed.result", Boolean(checker.getAwaitedType(checker.getTypeAtLocation(call)).flags & ts6.TypeFlags.Object))};` : ""}this.step=${next};}}}`, awaited, "await");
|
|
1650
|
+
return state(mapped`const available=${receiver}.snapshot();if(!available.valid)return;if(available.busy||available.done){${reject("7")}}else{const accepted:BOOL=${receiver}.start(${joined(call.arguments.map(rewrite), ",")});if(accepted){this.${borrow}=true;this.step=${poll};}}`, awaited, "await", true);
|
|
1494
1651
|
}
|
|
1495
1652
|
const called = functions.get(symbol(name));
|
|
1496
1653
|
if (!called)
|
|
@@ -1504,16 +1661,16 @@ class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { pr
|
|
|
1504
1661
|
children.push(`private ${borrow}:BOOL=false;`);
|
|
1505
1662
|
resets.push(`if(this.${borrow}){${receiver}.${calledMethod.reset}();this.${borrow}=false;}`);
|
|
1506
1663
|
cancels.push(`if(this.${borrow}){${receiver}.${calledMethod.advance}({cancel:true});const cancellingChild=${receiver}.${calledMethod.snapshot}();if(cancellingChild.busy)return;${receiver}.${calledMethod.reset}();this.${borrow}=false;}`);
|
|
1507
|
-
const poll = state(`${receiver}.${calledMethod.advance}({cancel:false});const childState=${receiver}.${calledMethod.snapshot}();if(childState.done){${receiver}.${calledMethod.reset}();this.${borrow}=false;if(childState.error!==0){${reject("childState.error", true)}}else{${target ? `${target}=${copyValue("childState.result", Boolean(checker.getAwaitedType(checker.getTypeAtLocation(call)).flags & ts6.TypeFlags.Object))};` : ""}this.step=${next};}}
|
|
1508
|
-
return state(`const accepted:BOOL=${receiver}.${calledMethod.start}(${call.arguments.map(rewrite)
|
|
1664
|
+
const poll = state(mapped`${receiver}.${calledMethod.advance}({cancel:false});const childState=${receiver}.${calledMethod.snapshot}();if(childState.done){${receiver}.${calledMethod.reset}();this.${borrow}=false;if(childState.error!==0){${reject("childState.error", true)}}else{${target ? mapped`${target}=${copyValue("childState.result", Boolean(checker.getAwaitedType(checker.getTypeAtLocation(call)).flags & ts6.TypeFlags.Object))};` : ""}this.step=${next};}}`, awaited, "await");
|
|
1665
|
+
return state(mapped`const accepted:BOOL=${receiver}.${calledMethod.start}(${joined(call.arguments.map(rewrite), ",")});if(!accepted){${reject("7")}}else{this.${borrow}=true;${receiver}.${calledMethod.advance}({cancel:false});this.step=${poll};}`, awaited, "await", true);
|
|
1509
1666
|
}
|
|
1510
1667
|
if (!ts6.isIdentifier(call.expression))
|
|
1511
1668
|
fail(call, "Async helpers require a static function.");
|
|
1512
1669
|
children.push(`private ${child} = new ${text(call.expression)}();`);
|
|
1513
1670
|
resets.push(`this.${child}.reset();`);
|
|
1514
1671
|
cancels.push(`this.${child}.update({cancel:true});const cancellingChild=this.${child}.snapshot();if(cancellingChild.busy)return;`);
|
|
1515
|
-
const poll = state(`this.${child}.update({cancel:false}); const childState = this.${child}.snapshot(); if(childState.done) {if(childState.error !== 0) {${reject("childState.error", true)}} else {${target ? `${target} = ${copyValue("childState.result", Boolean(checker.getAwaitedType(checker.getTypeAtLocation(call)).flags & ts6.TypeFlags.Object))};` : ""}this.step = ${next};} }
|
|
1516
|
-
return state(`const accepted:BOOL = this.${child}.start(${call.arguments.map(rewrite)
|
|
1672
|
+
const poll = state(mapped`this.${child}.update({cancel:false}); const childState = this.${child}.snapshot(); if(childState.done) {if(childState.error !== 0) {${reject("childState.error", true)}} else {${target ? mapped`${target} = ${copyValue("childState.result", Boolean(checker.getAwaitedType(checker.getTypeAtLocation(call)).flags & ts6.TypeFlags.Object))};` : ""}this.step = ${next};} }`, awaited, "await");
|
|
1673
|
+
return state(mapped`const accepted:BOOL = this.${child}.start(${joined(call.arguments.map(rewrite), ",")}); if(accepted){this.${child}.update({cancel:false});this.step = ${poll};}`, awaited, "await", true);
|
|
1517
1674
|
};
|
|
1518
1675
|
const block = (statements, next, reject = failure) => {
|
|
1519
1676
|
let entry = next;
|
|
@@ -1524,7 +1681,7 @@ class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { pr
|
|
|
1524
1681
|
}
|
|
1525
1682
|
if (ts6.isIfStatement(stmt)) {
|
|
1526
1683
|
const yes = block([stmt.thenStatement], entry, reject), no = stmt.elseStatement ? block([stmt.elseStatement], entry, reject) : entry;
|
|
1527
|
-
entry = state(`if(${rewrite(stmt.expression)}) this.step = ${yes}; else this.step = ${no}
|
|
1684
|
+
entry = state(mapped`if(${rewrite(stmt.expression)}) this.step = ${yes}; else this.step = ${no};`, stmt.expression, "statement");
|
|
1528
1685
|
continue;
|
|
1529
1686
|
}
|
|
1530
1687
|
if (ts6.isTryStatement(stmt)) {
|
|
@@ -1534,27 +1691,27 @@ class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { pr
|
|
|
1534
1691
|
const declaration = stmt.catchClause.variableDeclaration;
|
|
1535
1692
|
const field = declaration && fields.get(symbol(declaration.name));
|
|
1536
1693
|
entry = block(stmt.tryBlock.statements, entry, (error, cancellable) => {
|
|
1537
|
-
const recover = `${field ? `this.${field.name} = ${error};` : ""}this.step = ${caught};`;
|
|
1538
|
-
return cancellable ? `if(${error} === 1) {${failure(error)}} else {${recover}}` : recover;
|
|
1694
|
+
const recover = mapped`${field ? mapped`this.${field.name} = ${error};` : ""}this.step = ${caught};`;
|
|
1695
|
+
return cancellable ? mapped`if(${error} === 1) {${failure(error)}} else {${recover}}` : recover;
|
|
1539
1696
|
});
|
|
1540
1697
|
continue;
|
|
1541
1698
|
}
|
|
1542
1699
|
if (ts6.isThrowStatement(stmt)) {
|
|
1543
1700
|
if (!checker.isTypeAssignableTo(checker.getTypeAtLocation(stmt.expression), checker.getNumberType()))
|
|
1544
1701
|
fail(stmt, "Async throw requires a numeric error code.");
|
|
1545
|
-
entry = state(reject(rewrite(stmt.expression)));
|
|
1702
|
+
entry = state(reject(rewrite(stmt.expression)), stmt, "throw");
|
|
1546
1703
|
continue;
|
|
1547
1704
|
}
|
|
1548
1705
|
if (ts6.isReturnStatement(stmt)) {
|
|
1549
1706
|
if (!stmt.expression) {
|
|
1550
1707
|
if (!returnsVoid)
|
|
1551
1708
|
fail(stmt, "Async routines must return a value.");
|
|
1552
|
-
entry = state(finish("true"));
|
|
1709
|
+
entry = state(finish("true"), stmt, "return");
|
|
1553
1710
|
continue;
|
|
1554
1711
|
}
|
|
1555
1712
|
const adopted = ts6.isCallExpression(stmt.expression) && checker.getAwaitedType(checker.getTypeAtLocation(stmt.expression)) !== checker.getTypeAtLocation(stmt.expression) ? stmt.expression : undefined;
|
|
1556
1713
|
const suspension = ts6.isAwaitExpression(stmt.expression) ? stmt.expression : adopted;
|
|
1557
|
-
entry = suspension ? awaitState(suspension, returnsVoid ? undefined : "this.value", state(finish(returnsVoid ? "true" : "this.value")), reject) : state(finish(rewrite(stmt.expression)));
|
|
1714
|
+
entry = suspension ? awaitState(suspension, returnsVoid ? undefined : "this.value", state(finish(returnsVoid ? "true" : "this.value"), stmt, "return"), reject) : state(finish(rewrite(stmt.expression)), stmt, "return");
|
|
1558
1715
|
continue;
|
|
1559
1716
|
}
|
|
1560
1717
|
if (ts6.isVariableStatement(stmt)) {
|
|
@@ -1563,7 +1720,7 @@ class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { pr
|
|
|
1563
1720
|
if (!field || !dec.initializer)
|
|
1564
1721
|
fail(dec, "Invalid async local.");
|
|
1565
1722
|
const target = `this.${field.name}`;
|
|
1566
|
-
entry = ts6.isAwaitExpression(dec.initializer) ? awaitState(dec.initializer, target, entry, reject) : state(`${target} = ${copyValue(rewrite(dec.initializer), field.aggregate)}; this.step = ${entry}
|
|
1723
|
+
entry = ts6.isAwaitExpression(dec.initializer) ? awaitState(dec.initializer, target, entry, reject) : state(mapped`${target} = ${copyValue(rewrite(dec.initializer), field.aggregate)}; this.step = ${entry};`, dec, "statement");
|
|
1567
1724
|
}
|
|
1568
1725
|
continue;
|
|
1569
1726
|
}
|
|
@@ -1575,17 +1732,17 @@ class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { pr
|
|
|
1575
1732
|
fail(stmt, "This suspension position is not supported; await into a named local or return.");
|
|
1576
1733
|
if (ts6.isWhileStatement(stmt) || ts6.isDoStatement(stmt))
|
|
1577
1734
|
fail(stmt, "Unbounded loops are not supported in async routines.");
|
|
1578
|
-
entry = state(`${rewrite(stmt)} this.step = ${entry}
|
|
1735
|
+
entry = state(mapped`${rewrite(stmt)} this.step = ${entry};`, stmt, "statement");
|
|
1579
1736
|
}
|
|
1580
1737
|
return entry;
|
|
1581
1738
|
};
|
|
1582
|
-
const
|
|
1739
|
+
const end = fn.body.getLastToken(source);
|
|
1740
|
+
const entry = block(fn.body.statements, returnsVoid ? state(finish("true"), end, "return") : state(failure("4"), end, "throw"));
|
|
1583
1741
|
const exported = fn.modifiers?.some((m) => m.kind === ts6.SyntaxKind.ExportKeyword) ? "export " : "";
|
|
1584
1742
|
const aliases = `export type ${aliasPrefix(fn)}Result = ${returnType};
|
|
1585
1743
|
${parameters.map((p, i) => `export type ${aliasPrefix(fn)}Argument${i} = ${p.type};`).join(`
|
|
1586
1744
|
`)}`;
|
|
1587
|
-
const generated = `${aliases}
|
|
1588
|
-
${exported}class ${fn.name.getText(source)} extends FunctionBlock<{cancel:BOOL}> {
|
|
1745
|
+
const generated = mapped`${aliases}\n${exported}class ${fn.name.getText(source)} extends FunctionBlock<{cancel:BOOL}> {
|
|
1589
1746
|
private step:UINT=0; private cancelling:BOOL=false; private busy:BOOL=false; private done:BOOL=false; private error:UDINT=0; private value:${returnType}=defaultValue<${returnType}>();
|
|
1590
1747
|
${[...fields.values()].map((f) => `private ${f.name}:${f.type}=defaultValue<${f.type}>();`).join(`
|
|
1591
1748
|
`)}
|
|
@@ -1594,14 +1751,19 @@ ${children.join(`
|
|
|
1594
1751
|
start(${parameters.map((p) => `${p.name}:${p.type}`).join(",")}):BOOL {if(this.busy || this.done)return false; ${parameters.map((p) => `this.${p.field} = ${copyValue(p.name, p.aggregate)};`).join(" ")} ${resets.join(" ")} this.value = defaultValue<${returnType}>(); this.error=0;this.cancelling=false;this.busy=true;this.done=false;this.step=${entry};return true;}
|
|
1595
1752
|
reset():void {${resets.join(" ")} this.busy=false;this.cancelling=false;this.done=false;this.error=0;this.step=0;}
|
|
1596
1753
|
snapshot():{busy:BOOL;done:BOOL;error:UDINT;result:${returnType}} {return {busy:this.busy,done:this.done,error:this.error,result:${copyValue("this.value", resultAggregate)}};}
|
|
1597
|
-
protected execute(input:{cancel:BOOL}):void {if(!this.busy)return;if(input.cancel)this.cancelling=true;if(this.cancelling){${cancels.map((cancel) => `{${cancel}}`).join(" ")}${failure("1")}return;}for(let transition:DINT=0;transition<${nodes.size + 1};transition++){const previous:UINT=this.step;switch(this.step){${[...nodes].map(([id, body]) => `case ${id}: {${body}} break;`)
|
|
1754
|
+
protected execute(input:{cancel:BOOL}):void {if(!this.busy)return;if(input.cancel)this.cancelling=true;if(this.cancelling){${cancels.map((cancel) => `{${cancel}}`).join(" ")}${failure("1")}return;}for(let transition:DINT=0;transition<${nodes.size + 1};transition++){const previous:UINT=this.step;switch(this.step){${joined([...nodes].map(([id, body]) => mapped`case ${id}: {${body}} break;`), `
|
|
1598
1755
|
`)} }if(!this.busy||this.step===previous${[...yielding].map((id) => `||previous===${id}`).join("")})return;}}
|
|
1599
1756
|
|
|
1600
1757
|
}`;
|
|
1601
|
-
if (!method)
|
|
1758
|
+
if (!method) {
|
|
1602
1759
|
replacements.push({ start: fn.getStart(source), end: fn.end, text: generated });
|
|
1603
|
-
|
|
1604
|
-
|
|
1760
|
+
result.jobs.set(`${source.fileName}:${fn.name.getText(source)}`, {
|
|
1761
|
+
name: fn.name.getText(source),
|
|
1762
|
+
span: positions.node(fn),
|
|
1763
|
+
steps
|
|
1764
|
+
});
|
|
1765
|
+
} else {
|
|
1766
|
+
const parsed = ts6.createSourceFile(source.fileName, generated.text, ts6.ScriptTarget.Latest, true);
|
|
1605
1767
|
const worker = parsed.statements.find(ts6.isClassDeclaration);
|
|
1606
1768
|
const names = new Map(worker.members.map((member) => [
|
|
1607
1769
|
member.name.getText(parsed),
|
|
@@ -1611,34 +1773,51 @@ protected execute(input:{cancel:BOOL}):void {if(!this.busy)return;if(input.cance
|
|
|
1611
1773
|
names.set("reset", method.reset);
|
|
1612
1774
|
names.set("snapshot", method.snapshot);
|
|
1613
1775
|
names.set("execute", method.advance);
|
|
1614
|
-
const
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
};
|
|
1631
|
-
return
|
|
1776
|
+
const members = worker.members;
|
|
1777
|
+
const edits = [
|
|
1778
|
+
...members.map((member, index) => ({
|
|
1779
|
+
start: index ? members[index - 1].end : 0,
|
|
1780
|
+
end: member.getStart(parsed),
|
|
1781
|
+
text: index ? `
|
|
1782
|
+
` : ""
|
|
1783
|
+
})),
|
|
1784
|
+
{ start: members.at(-1).end, end: generated.text.length, text: "" }
|
|
1785
|
+
];
|
|
1786
|
+
const visit = (node) => {
|
|
1787
|
+
if (ts6.isElementAccessExpression(node) && node.expression.kind === ts6.SyntaxKind.ThisKeyword && ts6.isStringLiteral(node.argumentExpression)) {
|
|
1788
|
+
edits.push({
|
|
1789
|
+
start: node.getStart(parsed),
|
|
1790
|
+
end: node.end,
|
|
1791
|
+
text: `this.${node.argumentExpression.text}`
|
|
1792
|
+
});
|
|
1793
|
+
return;
|
|
1632
1794
|
}
|
|
1633
|
-
|
|
1634
|
-
|
|
1795
|
+
const renamed = ts6.isPropertyAccessExpression(node) && node.expression.kind === ts6.SyntaxKind.ThisKeyword || ts6.isPropertyDeclaration(node) || ts6.isMethodDeclaration(node) ? node.name : undefined;
|
|
1796
|
+
if (renamed && ts6.isIdentifier(renamed) && names.has(renamed.text)) {
|
|
1797
|
+
const name = names.get(renamed.text);
|
|
1798
|
+
const modifiers = ts6.isMethodDeclaration(node) ? node.modifiers : undefined;
|
|
1799
|
+
if (modifiers?.length)
|
|
1800
|
+
edits.push({
|
|
1801
|
+
start: modifiers[0].getStart(parsed),
|
|
1802
|
+
end: modifiers.at(-1).end,
|
|
1803
|
+
text: "public"
|
|
1804
|
+
});
|
|
1805
|
+
edits.push({
|
|
1806
|
+
start: renamed.getStart(parsed),
|
|
1807
|
+
end: renamed.end,
|
|
1808
|
+
text: ts6.isMethodDeclaration(node) && !modifiers?.length ? `public ${name}` : name
|
|
1809
|
+
});
|
|
1810
|
+
if (ts6.isPropertyAccessExpression(node))
|
|
1811
|
+
return;
|
|
1812
|
+
}
|
|
1813
|
+
ts6.forEachChild(node, visit);
|
|
1814
|
+
};
|
|
1815
|
+
visit(worker);
|
|
1635
1816
|
replacements.push({
|
|
1636
1817
|
start: fn.getStart(source),
|
|
1637
1818
|
end: fn.end,
|
|
1638
|
-
text:
|
|
1639
|
-
`)
|
|
1819
|
+
text: edited(generated, edits)
|
|
1640
1820
|
});
|
|
1641
|
-
transformed.dispose();
|
|
1642
1821
|
}
|
|
1643
1822
|
}
|
|
1644
1823
|
const workTypes = (fn, dec) => {
|
|
@@ -1663,7 +1842,7 @@ protected execute(input:{cancel:BOOL}):void {if(!this.busy)return;if(input.cance
|
|
|
1663
1842
|
for (let i = 0;i < params.length; i++)
|
|
1664
1843
|
params[i].type = `${prefix}Argument${i}`;
|
|
1665
1844
|
const path = relative3(dirname5(source.fileName), fn.getSourceFile().fileName).replaceAll("\\", "/");
|
|
1666
|
-
extra.push(`import type {${valueType},${params.map((p) => p.type).join(",")}} from ${JSON.stringify(path.startsWith(".") ? path : `./${path}`)};`);
|
|
1845
|
+
extra.push(from(dec, `import type {${valueType},${params.map((p) => p.type).join(",")}} from ${JSON.stringify(path.startsWith(".") ? path : `./${path}`)};`));
|
|
1667
1846
|
}
|
|
1668
1847
|
const valueAggregate = Boolean(promised.flags & ts6.TypeFlags.Object);
|
|
1669
1848
|
return { params, valueType, valueAggregate };
|
|
@@ -1717,15 +1896,18 @@ protected execute(input:{cancel:BOOL}):void {if(!this.busy)return;if(input.cance
|
|
|
1717
1896
|
visit(owner);
|
|
1718
1897
|
} else {
|
|
1719
1898
|
const name = `TsplcTaskSite${sequence++}`, entry = `tsplcContinuation${sequence++}`;
|
|
1720
|
-
extra.push(`class ${name} extends FunctionBlock<{}>{${site.body}protected execute(input:{}):void{}}
|
|
1721
|
-
export function ${entry}():void{${dec.name.text}.poll();}`);
|
|
1899
|
+
extra.push(from(dec, `class ${name} extends FunctionBlock<{}>{${site.body}protected execute(input:{}):void{}}
|
|
1900
|
+
export function ${entry}():void{${dec.name.text}.poll();}`));
|
|
1722
1901
|
replacements.push({
|
|
1723
1902
|
start: init.getStart(source),
|
|
1724
1903
|
end: init.end,
|
|
1725
1904
|
text: `new ${name}()`
|
|
1726
1905
|
});
|
|
1727
|
-
result.programs[entry] = { module:
|
|
1728
|
-
result.continuations.set(entry, {
|
|
1906
|
+
result.programs[entry] = { module: resolve2(source.fileName), export: entry };
|
|
1907
|
+
result.continuations.set(entry, {
|
|
1908
|
+
instance: dec.name.text,
|
|
1909
|
+
file: positions.node(dec).file
|
|
1910
|
+
});
|
|
1729
1911
|
}
|
|
1730
1912
|
continue;
|
|
1731
1913
|
}
|
|
@@ -1775,15 +1957,18 @@ export function ${entry}():void{${dec.name.text}.poll();}`);
|
|
|
1775
1957
|
visit(owner);
|
|
1776
1958
|
} else {
|
|
1777
1959
|
const name = `TsplcCooperativeSite${sequence++}`, entry = `tsplcContinuation${sequence++}`;
|
|
1778
|
-
extra.push(`class ${name} extends FunctionBlock<{}>{${site.body}protected execute(input:{}):void{}}
|
|
1779
|
-
export function ${entry}():void{${dec.name.text}.poll();}`);
|
|
1960
|
+
extra.push(from(dec, `class ${name} extends FunctionBlock<{}>{${site.body}protected execute(input:{}):void{}}
|
|
1961
|
+
export function ${entry}():void{${dec.name.text}.poll();}`));
|
|
1780
1962
|
replacements.push({
|
|
1781
1963
|
start: init.getStart(source),
|
|
1782
1964
|
end: init.end,
|
|
1783
1965
|
text: `new ${name}()`
|
|
1784
1966
|
});
|
|
1785
|
-
result.programs[entry] = { module:
|
|
1786
|
-
result.continuations.set(entry, {
|
|
1967
|
+
result.programs[entry] = { module: resolve2(source.fileName), export: entry };
|
|
1968
|
+
result.continuations.set(entry, {
|
|
1969
|
+
instance: dec.name.text,
|
|
1970
|
+
file: positions.node(dec).file
|
|
1971
|
+
});
|
|
1787
1972
|
}
|
|
1788
1973
|
continue;
|
|
1789
1974
|
}
|
|
@@ -1797,7 +1982,7 @@ export function ${entry}():void{${dec.name.text}.poll();}`);
|
|
|
1797
1982
|
const requestType = `{ready:BOOL;${params.map((p) => `${p.field}:${p.type}`).join(";")}}`;
|
|
1798
1983
|
const snapshotType = `{valid:BOOL;busy:BOOL;done:BOOL;cancelRequested:BOOL;error:UDINT;result:${valueType}}`;
|
|
1799
1984
|
const emptySnapshot = `{valid:true,busy:this.pending || this.active,done:this.completed,cancelRequested:this.cancelRequested,error:this.failure,result:${copyValue("this.value", valueAggregate)}}`;
|
|
1800
|
-
extra.push(`class ${mailbox} extends FunctionBlock<{}> {
|
|
1985
|
+
extra.push(from(dec, `class ${mailbox} extends FunctionBlock<{}> {
|
|
1801
1986
|
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}>();
|
|
1802
1987
|
${params.map((p) => `private ${p.field}:${p.type}=defaultValue<${p.type}>();`).join(`
|
|
1803
1988
|
`)}
|
|
@@ -1809,7 +1994,7 @@ cancel():BOOL {if(this.pending){this.pending=false;this.completed=true;this.fail
|
|
|
1809
1994
|
reset():BOOL {if(this.pending || this.active)return false;this.completed=false;this.failure=0;this.cancelRequested=false;this.value=defaultValue<${valueType}>();return true;}
|
|
1810
1995
|
protected execute(input:{}):void {}
|
|
1811
1996
|
}
|
|
1812
|
-
`);
|
|
1997
|
+
`));
|
|
1813
1998
|
const receiver = owner ? `this.${dec.name.text}` : dec.name.text;
|
|
1814
1999
|
const workerReceiver = owner ? `this.${worker}` : worker;
|
|
1815
2000
|
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();}`;
|
|
@@ -1819,11 +2004,11 @@ protected execute(input:{}):void {}
|
|
|
1819
2004
|
replacements.push({
|
|
1820
2005
|
start: owner.end - 1,
|
|
1821
2006
|
end: owner.end - 1,
|
|
1822
|
-
text: `private ${worker}=new ${text(init.arguments[0])}();public ${entry}():void{${run}}`
|
|
2007
|
+
text: from(dec, `private ${worker}=new ${text(init.arguments[0])}();public ${entry}():void{${run}}`)
|
|
1823
2008
|
});
|
|
1824
2009
|
result.blocks.set(`${source.fileName}:${owner.name.text}`, { kind: "backgroundHost" });
|
|
1825
2010
|
} else
|
|
1826
|
-
extra.push(`const ${worker}=new ${text(init.arguments[0])}();export function ${entry}():void{${run}}`);
|
|
2011
|
+
extra.push(from(dec, `const ${worker}=new ${text(init.arguments[0])}();export function ${entry}():void{${run}}`));
|
|
1827
2012
|
result.blocks.set(`${source.fileName}:${mailbox}`, { kind: "mailbox" });
|
|
1828
2013
|
const opts = new Map(init.arguments[1].properties.filter(ts6.isPropertyAssignment).map((p) => [
|
|
1829
2014
|
p.name.getText(source),
|
|
@@ -1846,7 +2031,7 @@ protected execute(input:{}):void {}
|
|
|
1846
2031
|
const key = symbol(owner.name);
|
|
1847
2032
|
ownedJobs.set(key, [...ownedJobs.get(key) ?? [], { method: entry, schedule }]);
|
|
1848
2033
|
} else {
|
|
1849
|
-
result.programs[entry] = { module:
|
|
2034
|
+
result.programs[entry] = { module: resolve2(source.fileName), export: entry };
|
|
1850
2035
|
result.schedules.set(entry, schedule);
|
|
1851
2036
|
}
|
|
1852
2037
|
replacements.push({
|
|
@@ -1856,18 +2041,15 @@ protected execute(input:{}):void {}
|
|
|
1856
2041
|
});
|
|
1857
2042
|
}
|
|
1858
2043
|
if (replacements.length) {
|
|
1859
|
-
|
|
1860
|
-
for (const edit of replacements.sort((a, b) => b.start - a.start))
|
|
1861
|
-
changed = changed.slice(0, edit.start) + edit.text + changed.slice(edit.end);
|
|
1862
|
-
const generated = ts6.createSourceFile(source.fileName, extra.join(`
|
|
1863
|
-
`), ts6.ScriptTarget.Latest, true);
|
|
1864
|
-
const before = generated.statements.filter(ts6.isClassDeclaration).map((n) => n.getText(generated)).join(`
|
|
1865
|
-
`);
|
|
1866
|
-
const after = generated.statements.filter((n) => !ts6.isClassDeclaration(n)).map((n) => n.getText(generated)).join(`
|
|
2044
|
+
const added = joined(extra, `
|
|
1867
2045
|
`);
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
2046
|
+
const generated = ts6.createSourceFile(source.fileName, added.text, ts6.ScriptTarget.Latest, true);
|
|
2047
|
+
const part = (node) => slice(added, node.getStart(generated), node.end);
|
|
2048
|
+
const before = generated.statements.filter(ts6.isClassDeclaration).map(part);
|
|
2049
|
+
const after = generated.statements.filter((n) => !ts6.isClassDeclaration(n)).map(part);
|
|
2050
|
+
result.sources.set(source.fileName, mapped`${joined(before, `
|
|
2051
|
+
`)}\n${edited(source, replacements)}\n${joined(after, `
|
|
2052
|
+
`)}`);
|
|
1871
2053
|
}
|
|
1872
2054
|
} catch (cause) {
|
|
1873
2055
|
if (typeof cause === "object" && cause !== null && "asyncDiagnostic" in cause)
|
|
@@ -1908,14 +2090,17 @@ protected execute(input:{}):void {}
|
|
|
1908
2090
|
const name = declaration.name.text;
|
|
1909
2091
|
for (const poll of polls ?? []) {
|
|
1910
2092
|
const entry = `tsplcContinuation${sequence++}`;
|
|
1911
|
-
entries.push(instance.first === undefined ? `export function ${entry}():void{${name}.${poll}();}` : `export function ${entry}():void{for(let element:DINT=${instance.first};element<=${instance.last};element++){${name}[element].${poll}();}}`);
|
|
1912
|
-
result.programs[entry] = { module:
|
|
1913
|
-
result.continuations.set(entry, {
|
|
2093
|
+
entries.push(from(node, instance.first === undefined ? `export function ${entry}():void{${name}.${poll}();}` : `export function ${entry}():void{for(let element:DINT=${instance.first};element<=${instance.last};element++){${name}[element].${poll}();}}`));
|
|
2094
|
+
result.programs[entry] = { module: resolve2(source.fileName), export: entry };
|
|
2095
|
+
result.continuations.set(entry, {
|
|
2096
|
+
instance: name,
|
|
2097
|
+
file: positions.node(declaration).file
|
|
2098
|
+
});
|
|
1914
2099
|
}
|
|
1915
2100
|
for (const job of jobs ?? []) {
|
|
1916
2101
|
const entry = `tsplcBackground${sequence++}`;
|
|
1917
|
-
entries.push(`export function ${entry}():void{${name}.${job.method}();}`);
|
|
1918
|
-
result.programs[entry] = { module:
|
|
2102
|
+
entries.push(from(node, `export function ${entry}():void{${name}.${job.method}();}`));
|
|
2103
|
+
result.programs[entry] = { module: resolve2(source.fileName), export: entry };
|
|
1919
2104
|
result.schedules.set(entry, { ...job.schedule, worker: name });
|
|
1920
2105
|
}
|
|
1921
2106
|
}
|
|
@@ -1924,9 +2109,8 @@ protected execute(input:{}):void {}
|
|
|
1924
2109
|
};
|
|
1925
2110
|
visit(source);
|
|
1926
2111
|
if (entries.length)
|
|
1927
|
-
result.sources.set(source.fileName,
|
|
1928
|
-
`
|
|
1929
|
-
`));
|
|
2112
|
+
result.sources.set(source.fileName, mapped`${result.sources.get(source.fileName) ?? edited(source, [])}\n${joined(entries, `
|
|
2113
|
+
`)}`);
|
|
1930
2114
|
}
|
|
1931
2115
|
return result;
|
|
1932
2116
|
};
|
|
@@ -1934,7 +2118,7 @@ protected execute(input:{}):void {}
|
|
|
1934
2118
|
// packages/compiler/src/frontend/const-functions.ts
|
|
1935
2119
|
import ts7 from "typescript";
|
|
1936
2120
|
import { error as error6 } from "@tsplc/compiler/ir";
|
|
1937
|
-
var lowerConstFunctions = (program) => {
|
|
2121
|
+
var lowerConstFunctions = (program, positions) => {
|
|
1938
2122
|
const checker = program.getTypeChecker();
|
|
1939
2123
|
const printer = ts7.createPrinter();
|
|
1940
2124
|
const sources = new Map;
|
|
@@ -1952,30 +2136,25 @@ var lowerConstFunctions = (program) => {
|
|
|
1952
2136
|
const result = signature && checker.getAwaitedType(checker.getReturnTypeOfSignature(signature));
|
|
1953
2137
|
if (result && result.flags & ts7.TypeFlags.Void) {
|
|
1954
2138
|
const position = routine.body.getStart(source);
|
|
1955
|
-
edits.push({ start: position, end: position, text: ":Promise<void> " });
|
|
2139
|
+
edits.push({ start: position, end: position, text: from(routine, ":Promise<void> ") });
|
|
1956
2140
|
}
|
|
1957
2141
|
}
|
|
1958
2142
|
}
|
|
1959
2143
|
for (const statement of source.statements) {
|
|
1960
2144
|
if (!ts7.isVariableStatement(statement) || !statement.declarationList.declarations.some((declaration) => declaration.initializer && ts7.isArrowFunction(declaration.initializer)))
|
|
1961
2145
|
continue;
|
|
2146
|
+
const print = (node) => printer.printNode(ts7.EmitHint.Unspecified, node, source);
|
|
1962
2147
|
const declarations = [];
|
|
1963
2148
|
for (const declaration of statement.declarationList.declarations) {
|
|
1964
2149
|
const arrow = declaration.initializer;
|
|
1965
2150
|
if (!arrow || !ts7.isArrowFunction(arrow)) {
|
|
1966
|
-
declarations.push(ts7.factory.updateVariableStatement(statement, statement.modifiers, ts7.factory.updateVariableDeclarationList(statement.declarationList, [
|
|
2151
|
+
declarations.push(from(declaration, print(ts7.factory.updateVariableStatement(statement, statement.modifiers, ts7.factory.updateVariableDeclarationList(statement.declarationList, [
|
|
2152
|
+
declaration
|
|
2153
|
+
])))));
|
|
1967
2154
|
continue;
|
|
1968
2155
|
}
|
|
1969
2156
|
if (!(statement.declarationList.flags & ts7.NodeFlags.Const) || !ts7.isIdentifier(declaration.name)) {
|
|
1970
|
-
const
|
|
1971
|
-
const position = source.getLineAndCharacterOfPosition(start);
|
|
1972
|
-
diagnostics.push(error6("PLC1007", "PLC routines require named const bindings; mutable function values are unsupported.", {
|
|
1973
|
-
file: source.fileName,
|
|
1974
|
-
start,
|
|
1975
|
-
end: declaration.end,
|
|
1976
|
-
line: position.line + 1,
|
|
1977
|
-
column: position.character + 1
|
|
1978
|
-
}));
|
|
2157
|
+
diagnostics.push(error6("PLC1007", "PLC routines require named const bindings; mutable function values are unsupported.", positions.node(declaration)));
|
|
1979
2158
|
continue;
|
|
1980
2159
|
}
|
|
1981
2160
|
const contextual = declaration.type && ts7.isFunctionTypeNode(declaration.type) ? declaration.type : undefined;
|
|
@@ -1988,32 +2167,29 @@ var lowerConstFunctions = (program) => {
|
|
|
1988
2167
|
]) : undefined;
|
|
1989
2168
|
const result = arrow.type ?? contextual?.type ?? (returnsVoid ? ts7.factory.createKeywordTypeNode(ts7.SyntaxKind.VoidKeyword) : inferredType);
|
|
1990
2169
|
const parameters = arrow.parameters.map((parameter, index) => ts7.factory.updateParameterDeclaration(parameter, parameter.modifiers, parameter.dotDotDotToken, parameter.name, parameter.questionToken, parameter.type ?? contextual?.parameters[index]?.type, parameter.initializer));
|
|
1991
|
-
const
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
declarations.push(ts7.factory.createFunctionDeclaration([...statement.modifiers ?? [], ...arrow.modifiers ?? []], undefined, declaration.name, arrow.typeParameters ?? contextual?.typeParameters, parameters, result, body));
|
|
2170
|
+
const head = print(ts7.factory.createFunctionDeclaration([...statement.modifiers ?? [], ...arrow.modifiers ?? []], undefined, declaration.name, arrow.typeParameters ?? contextual?.typeParameters, parameters, result, ts7.factory.createBlock([]))).replace(/\{\s*\}$/, "");
|
|
2171
|
+
const body = copied(arrow.body);
|
|
2172
|
+
declarations.push(from(declaration, ts7.isBlock(arrow.body) ? mapped`${head}${body}` : result?.kind === ts7.SyntaxKind.VoidKeyword ? mapped`${head}{ ${body}; }` : mapped`${head}{ return ${body}; }`));
|
|
1995
2173
|
}
|
|
1996
2174
|
edits.push({
|
|
1997
2175
|
start: statement.getStart(source),
|
|
1998
2176
|
end: statement.end,
|
|
1999
|
-
text: declarations
|
|
2177
|
+
text: joined(declarations, `
|
|
2000
2178
|
`)
|
|
2001
2179
|
});
|
|
2002
2180
|
}
|
|
2003
|
-
if (
|
|
2004
|
-
|
|
2005
|
-
let text = source.text;
|
|
2006
|
-
for (const edit of edits.reverse())
|
|
2007
|
-
text = text.slice(0, edit.start) + edit.text + text.slice(edit.end);
|
|
2008
|
-
sources.set(source.fileName, text);
|
|
2181
|
+
if (edits.length)
|
|
2182
|
+
sources.set(source.fileName, edited(source, edits));
|
|
2009
2183
|
}
|
|
2010
2184
|
return { sources, diagnostics };
|
|
2011
2185
|
};
|
|
2012
2186
|
|
|
2013
2187
|
// packages/compiler/src/frontend/elaborate/index.ts
|
|
2014
2188
|
import ts12 from "typescript";
|
|
2015
|
-
import { dirname as dirname6, join as join3, relative as relative4, resolve as
|
|
2016
|
-
import {
|
|
2189
|
+
import { dirname as dirname6, join as join3, relative as relative4, resolve as resolve3 } from "node:path";
|
|
2190
|
+
import {
|
|
2191
|
+
error as error7
|
|
2192
|
+
} from "@tsplc/compiler/ir";
|
|
2017
2193
|
|
|
2018
2194
|
// packages/compiler/src/frontend/elaborate/graph.ts
|
|
2019
2195
|
import ts8 from "typescript";
|
|
@@ -2080,6 +2256,7 @@ ${result.stderr.trim()}`);
|
|
|
2080
2256
|
|
|
2081
2257
|
// packages/compiler/src/frontend/elaborate/model.ts
|
|
2082
2258
|
import ts9 from "typescript";
|
|
2259
|
+
var tsPath = (owner) => owner.root.name + owner.steps.map((step) => step.kind === "index" ? `[${step.index}]` : /^\d+$/.test(step.name) ? `[${step.name}]` : `.${step.name}`).join("");
|
|
2083
2260
|
|
|
2084
2261
|
class Model {
|
|
2085
2262
|
graph;
|
|
@@ -2254,6 +2431,12 @@ class Layouts {
|
|
|
2254
2431
|
imports.set(file, names);
|
|
2255
2432
|
return name;
|
|
2256
2433
|
}
|
|
2434
|
+
get literalEnums() {
|
|
2435
|
+
return [...this.enums.values()].map((declared) => ({
|
|
2436
|
+
name: declared.name,
|
|
2437
|
+
members: Object.fromEntries(declared.members.map((member) => [enumMember(member), member]))
|
|
2438
|
+
}));
|
|
2439
|
+
}
|
|
2257
2440
|
get enumNames() {
|
|
2258
2441
|
return [...this.declarations].filter(([, text]) => text.startsWith("export enum")).map(([name]) => name);
|
|
2259
2442
|
}
|
|
@@ -2513,12 +2696,16 @@ class SpecializeError extends Error {
|
|
|
2513
2696
|
}
|
|
2514
2697
|
|
|
2515
2698
|
class Emitter {
|
|
2699
|
+
origin;
|
|
2516
2700
|
lines = [];
|
|
2517
2701
|
depth = 1;
|
|
2518
2702
|
used = new Set;
|
|
2519
2703
|
temporaries = 0;
|
|
2704
|
+
constructor(origin) {
|
|
2705
|
+
this.origin = origin;
|
|
2706
|
+
}
|
|
2520
2707
|
line(text) {
|
|
2521
|
-
this.lines.push(`${" ".repeat(this.depth)}${text}`);
|
|
2708
|
+
this.lines.push(from(this.origin, mapped`${" ".repeat(this.depth)}${text}`));
|
|
2522
2709
|
}
|
|
2523
2710
|
open(text) {
|
|
2524
2711
|
this.line(text);
|
|
@@ -2547,7 +2734,9 @@ class Specializer {
|
|
|
2547
2734
|
kept;
|
|
2548
2735
|
rootModule;
|
|
2549
2736
|
layouts;
|
|
2737
|
+
readConstants = new Set;
|
|
2550
2738
|
routines = [];
|
|
2739
|
+
origins = new Map;
|
|
2551
2740
|
namespaces = new Map;
|
|
2552
2741
|
imports = new Map;
|
|
2553
2742
|
specialized = new Map;
|
|
@@ -2656,16 +2845,17 @@ class Specializer {
|
|
|
2656
2845
|
const namespace = this.namespace(owner.root);
|
|
2657
2846
|
let text = this.flattened(owner.root) ? namespace : `${namespace}.${owner.root.name}`;
|
|
2658
2847
|
owner.steps.forEach((step, index) => {
|
|
2659
|
-
|
|
2660
|
-
if (step.kind === "index")
|
|
2661
|
-
text += `[${step.index}]`;
|
|
2662
|
-
else if (/^\d+$/.test(step.name) && holder?.type)
|
|
2663
|
-
text += `[${this.keyText(holder.type, step.name)}]`;
|
|
2664
|
-
else
|
|
2665
|
-
text += `.${step.name}`;
|
|
2848
|
+
text += this.placeStep(this.at(owner.root, owner.steps.slice(0, index)), step);
|
|
2666
2849
|
});
|
|
2667
2850
|
return text;
|
|
2668
2851
|
}
|
|
2852
|
+
placeStep(holder, step) {
|
|
2853
|
+
if (step.kind === "index")
|
|
2854
|
+
return `[${step.index}]`;
|
|
2855
|
+
if (/^\d+$/.test(step.name) && holder?.type)
|
|
2856
|
+
return `[${this.keyText(holder.type, step.name)}]`;
|
|
2857
|
+
return `.${step.name}`;
|
|
2858
|
+
}
|
|
2669
2859
|
keyText(type, key) {
|
|
2670
2860
|
const keyType = type.aliasSymbol?.name === "Record" ? type.aliasTypeArguments?.[0] : undefined;
|
|
2671
2861
|
const member = keyType && this.enumMemberName(keyType, Number(key));
|
|
@@ -2921,7 +3111,7 @@ class Specializer {
|
|
|
2921
3111
|
}
|
|
2922
3112
|
entry(declaration) {
|
|
2923
3113
|
const frame = {
|
|
2924
|
-
emitter: new Emitter,
|
|
3114
|
+
emitter: new Emitter(declaration),
|
|
2925
3115
|
env: new Map,
|
|
2926
3116
|
returns: undefined,
|
|
2927
3117
|
async: false
|
|
@@ -2934,7 +3124,7 @@ class Specializer {
|
|
|
2934
3124
|
const returnType = signature && this.checker.getReturnTypeOfSignature(signature);
|
|
2935
3125
|
const isAsync = Boolean(ts11.canHaveModifiers(declaration) && ts11.getModifiers(declaration)?.some((modifier) => modifier.kind === ts11.SyntaxKind.AsyncKeyword));
|
|
2936
3126
|
const frame = {
|
|
2937
|
-
emitter: new Emitter,
|
|
3127
|
+
emitter: new Emitter(declaration),
|
|
2938
3128
|
env: new Map(closure),
|
|
2939
3129
|
self,
|
|
2940
3130
|
returns: returnType && (isAsync ? this.checker.getAwaitedType(returnType) : returnType),
|
|
@@ -2965,14 +3155,24 @@ class Specializer {
|
|
|
2965
3155
|
const name = this.routineName(declaration, self);
|
|
2966
3156
|
this.specialized.set(key, name);
|
|
2967
3157
|
if (ts11.isArrowFunction(declaration) && !ts11.isBlock(declaration.body)) {
|
|
3158
|
+
frame.emitter.origin = declaration.body;
|
|
2968
3159
|
const result = this.expression(declaration.body, frame, frame.returns);
|
|
2969
|
-
frame.emitter.line(`return ${this.code(result, frame.returns, frame)};`);
|
|
3160
|
+
frame.emitter.line(mapped`return ${this.code(result, frame.returns, frame)};`);
|
|
2970
3161
|
} else
|
|
2971
3162
|
this.body(declaration.body, frame);
|
|
2972
3163
|
const resultText = frame.returns && !(frame.returns.flags & ts11.TypeFlags.Void) ? this.layouts.text(frame.returns) : "void";
|
|
2973
3164
|
const head = `${frame.async ? "async " : ""}function ${name}(${parameters.join(", ")}): ${frame.async ? `Promise<${resultText}>` : resultText} {`;
|
|
2974
|
-
const
|
|
2975
|
-
|
|
3165
|
+
const instance = self?.owner && tsPath(self.owner);
|
|
3166
|
+
if (self?.captured.kind === "instance" && (ts11.isMethodDeclaration(declaration) || ts11.isGetAccessorDeclaration(declaration)))
|
|
3167
|
+
this.origins.set(name, {
|
|
3168
|
+
name: `${self.captured.name}.${declaration.name.getText()}`,
|
|
3169
|
+
...instance && { instance }
|
|
3170
|
+
});
|
|
3171
|
+
this.routines.push(joined([
|
|
3172
|
+
from(declaration, `${head}${instance ? ` /* ${instance} */` : ""}`),
|
|
3173
|
+
...frame.emitter.lines,
|
|
3174
|
+
from(closingBrace(declaration), "}")
|
|
3175
|
+
], `
|
|
2976
3176
|
`));
|
|
2977
3177
|
return { name, args: runtimeArgs, returns: frame.returns };
|
|
2978
3178
|
}
|
|
@@ -3027,10 +3227,18 @@ class Specializer {
|
|
|
3027
3227
|
if (ts11.isBlock(node))
|
|
3028
3228
|
for (const statement of node.statements)
|
|
3029
3229
|
this.statement(statement, frame);
|
|
3030
|
-
else
|
|
3031
|
-
frame.emitter.
|
|
3230
|
+
else {
|
|
3231
|
+
frame.emitter.origin = node;
|
|
3232
|
+
frame.emitter.line(mapped`${this.code(this.expression(node, frame), undefined, frame)};`);
|
|
3233
|
+
}
|
|
3032
3234
|
}
|
|
3033
3235
|
statement(node, frame) {
|
|
3236
|
+
const enclosing = frame.emitter.origin;
|
|
3237
|
+
frame.emitter.origin = node;
|
|
3238
|
+
this.specializeStatement(node, frame);
|
|
3239
|
+
frame.emitter.origin = enclosing;
|
|
3240
|
+
}
|
|
3241
|
+
specializeStatement(node, frame) {
|
|
3034
3242
|
const { emitter } = frame;
|
|
3035
3243
|
if (ts11.isBlock(node)) {
|
|
3036
3244
|
emitter.open("{");
|
|
@@ -3059,7 +3267,7 @@ class Specializer {
|
|
|
3059
3267
|
this.statement(node.elseStatement, frame);
|
|
3060
3268
|
return;
|
|
3061
3269
|
}
|
|
3062
|
-
emitter.open(`if (${this.condition(condition, node.expression, frame)}) {`);
|
|
3270
|
+
emitter.open(mapped`if (${this.condition(condition, node.expression, frame)}) {`);
|
|
3063
3271
|
this.inner(node.thenStatement, frame);
|
|
3064
3272
|
if (node.elseStatement) {
|
|
3065
3273
|
emitter.close("} else {");
|
|
@@ -3080,7 +3288,7 @@ class Specializer {
|
|
|
3080
3288
|
return;
|
|
3081
3289
|
}
|
|
3082
3290
|
const value = this.expression(node.expression, frame, frame.returns);
|
|
3083
|
-
emitter.line(`return ${this.code(value, frame.returns, frame)};`);
|
|
3291
|
+
emitter.line(mapped`return ${this.code(value, frame.returns, frame)};`);
|
|
3084
3292
|
return;
|
|
3085
3293
|
}
|
|
3086
3294
|
if (ts11.isForOfStatement(node)) {
|
|
@@ -3103,9 +3311,17 @@ class Specializer {
|
|
|
3103
3311
|
for (const statement of node.tryBlock.statements)
|
|
3104
3312
|
this.statement(statement, frame);
|
|
3105
3313
|
if (node.catchClause) {
|
|
3106
|
-
|
|
3314
|
+
const binding = node.catchClause.variableDeclaration?.name;
|
|
3315
|
+
emitter.close(`} catch${binding ? ` (${binding.getText()})` : ""} {`);
|
|
3107
3316
|
emitter.open("");
|
|
3108
3317
|
emitter.lines.pop();
|
|
3318
|
+
if (binding && ts11.isIdentifier(binding))
|
|
3319
|
+
frame.env.set(this.checker.getSymbolAtLocation(binding), {
|
|
3320
|
+
kind: "code",
|
|
3321
|
+
text: binding.text,
|
|
3322
|
+
declared: this.checker.getTypeAtLocation(binding),
|
|
3323
|
+
place: true
|
|
3324
|
+
});
|
|
3109
3325
|
for (const statement of node.catchClause.block.statements)
|
|
3110
3326
|
this.statement(statement, frame);
|
|
3111
3327
|
}
|
|
@@ -3113,7 +3329,7 @@ class Specializer {
|
|
|
3113
3329
|
return;
|
|
3114
3330
|
}
|
|
3115
3331
|
if (ts11.isBreakStatement(node) || ts11.isContinueStatement(node)) {
|
|
3116
|
-
emitter.line(node
|
|
3332
|
+
emitter.line(copied(node));
|
|
3117
3333
|
return;
|
|
3118
3334
|
}
|
|
3119
3335
|
if (ts11.isEmptyStatement(node))
|
|
@@ -3179,7 +3395,7 @@ class Specializer {
|
|
|
3179
3395
|
}
|
|
3180
3396
|
const local = frame.emitter.local(name.text);
|
|
3181
3397
|
const type = value.kind === "code" && value.iec ? value.iec : this.localType(declared);
|
|
3182
|
-
frame.emitter.line(`${mutable ? "let" : "const"} ${local}: ${type} = ${this.code(value, declared, frame)};`);
|
|
3398
|
+
frame.emitter.line(mapped`${mutable ? "let" : "const"} ${local}: ${type} = ${this.code(value, declared, frame)};`);
|
|
3183
3399
|
frame.env.set(symbol, {
|
|
3184
3400
|
kind: "code",
|
|
3185
3401
|
text: local,
|
|
@@ -3226,7 +3442,7 @@ class Specializer {
|
|
|
3226
3442
|
if (!ts11.isIdentifier(name))
|
|
3227
3443
|
throw new SpecializeError(name, "Destructure a runtime element inside the loop.");
|
|
3228
3444
|
const local = frame.emitter.local(name.text);
|
|
3229
|
-
frame.emitter.open(`for (const ${local} of ${iterable.text}) {`);
|
|
3445
|
+
frame.emitter.open(mapped`for (const ${local} of ${iterable.text}) {`);
|
|
3230
3446
|
frame.env.set(this.checker.getSymbolAtLocation(name), {
|
|
3231
3447
|
kind: "code",
|
|
3232
3448
|
text: local,
|
|
@@ -3253,7 +3469,7 @@ class Specializer {
|
|
|
3253
3469
|
});
|
|
3254
3470
|
return local;
|
|
3255
3471
|
});
|
|
3256
|
-
frame.emitter.open(`for (const [${index
|
|
3472
|
+
frame.emitter.open(mapped`for (const [${[index, item].join(", ")}] of ${array}.entries()) {`);
|
|
3257
3473
|
this.inner(node.statement, frame);
|
|
3258
3474
|
frame.emitter.close();
|
|
3259
3475
|
}
|
|
@@ -3278,15 +3494,15 @@ class Specializer {
|
|
|
3278
3494
|
place: true,
|
|
3279
3495
|
iec
|
|
3280
3496
|
});
|
|
3281
|
-
const test = `${this.code(this.expression(condition.left, frame), declared, frame)} ${condition.operatorToken.getText()} ${this.code(this.expression(condition.right, frame), declared, frame)}`;
|
|
3497
|
+
const test = mapped`${this.code(this.expression(condition.left, frame), declared, frame)} ${condition.operatorToken.getText()} ${this.code(this.expression(condition.right, frame), declared, frame)}`;
|
|
3282
3498
|
let step;
|
|
3283
3499
|
if (ts11.isPrefixUnaryExpression(incrementor) || ts11.isPostfixUnaryExpression(incrementor))
|
|
3284
3500
|
step = `${local}${ts11.tokenToString(incrementor.operator)}`;
|
|
3285
3501
|
else if (ts11.isBinaryExpression(incrementor))
|
|
3286
|
-
step = `${local} ${incrementor.operatorToken.getText()} ${this.code(this.expression(incrementor.right, frame), declared, frame)}`;
|
|
3502
|
+
step = mapped`${local} ${incrementor.operatorToken.getText()} ${this.code(this.expression(incrementor.right, frame), declared, frame)}`;
|
|
3287
3503
|
else
|
|
3288
3504
|
throw new SpecializeError(incrementor, "Use i++, i--, i += step or i -= step in the for header.");
|
|
3289
|
-
frame.emitter.open(`for (let ${local}: ${iec ?? this.localType(declared)} = ${start}; ${test}; ${step}) {`);
|
|
3505
|
+
frame.emitter.open(mapped`for (let ${local}: ${iec ?? this.localType(declared)} = ${start}; ${test}; ${step}) {`);
|
|
3290
3506
|
this.inner(node.statement, frame);
|
|
3291
3507
|
frame.emitter.close();
|
|
3292
3508
|
}
|
|
@@ -3327,7 +3543,7 @@ class Specializer {
|
|
|
3327
3543
|
}
|
|
3328
3544
|
return;
|
|
3329
3545
|
}
|
|
3330
|
-
frame.emitter.open(`switch (${this.code(subject, declared, frame)}) {`);
|
|
3546
|
+
frame.emitter.open(mapped`switch (${this.code(subject, declared, frame)}) {`);
|
|
3331
3547
|
for (const clause of node.caseBlock.clauses) {
|
|
3332
3548
|
if (ts11.isDefaultClause(clause)) {
|
|
3333
3549
|
const unreachable = clause.statements.some((statement) => ts11.isReturnStatement(statement) && statement.expression && ts11.isSatisfiesExpression(statement.expression) && this.isNever(statement.expression.type));
|
|
@@ -3341,7 +3557,7 @@ class Specializer {
|
|
|
3341
3557
|
continue;
|
|
3342
3558
|
}
|
|
3343
3559
|
const label = this.expression(clause.expression, frame, declared);
|
|
3344
|
-
frame.emitter.open(`case ${this.code(label, declared, frame)}: {`);
|
|
3560
|
+
frame.emitter.open(mapped`case ${this.code(label, declared, frame)}: {`);
|
|
3345
3561
|
for (const statement of clause.statements)
|
|
3346
3562
|
this.statement(statement, frame);
|
|
3347
3563
|
frame.emitter.close();
|
|
@@ -3352,7 +3568,7 @@ class Specializer {
|
|
|
3352
3568
|
if (ts11.isVoidExpression(node)) {
|
|
3353
3569
|
const value = this.expression(node.expression, frame);
|
|
3354
3570
|
if (value.kind === "code")
|
|
3355
|
-
frame.emitter.line(`void ${value.text};`);
|
|
3571
|
+
frame.emitter.line(mapped`void ${value.text};`);
|
|
3356
3572
|
return;
|
|
3357
3573
|
}
|
|
3358
3574
|
if (ts11.isBinaryExpression(node) && isAssignment(node.operatorToken.kind)) {
|
|
@@ -3362,12 +3578,12 @@ class Specializer {
|
|
|
3362
3578
|
if ((ts11.isPrefixUnaryExpression(node) || ts11.isPostfixUnaryExpression(node)) && (node.operator === ts11.SyntaxKind.PlusPlusToken || node.operator === ts11.SyntaxKind.MinusMinusToken)) {
|
|
3363
3579
|
const target = this.expression(node.operand, frame);
|
|
3364
3580
|
const text = this.placeText(target, node.operand);
|
|
3365
|
-
frame.emitter.line(this.store(target, `${text} ${node.operator === ts11.SyntaxKind.PlusPlusToken ? "+" : "-"} 1`));
|
|
3581
|
+
frame.emitter.line(this.store(target, mapped`${text} ${node.operator === ts11.SyntaxKind.PlusPlusToken ? "+" : "-"} 1`));
|
|
3366
3582
|
return;
|
|
3367
3583
|
}
|
|
3368
3584
|
const value = this.expression(node, frame);
|
|
3369
|
-
if (value.kind === "code" && value.text.includes("("))
|
|
3370
|
-
frame.emitter.line(`${value.text};`);
|
|
3585
|
+
if (value.kind === "code" && String(value.text).includes("("))
|
|
3586
|
+
frame.emitter.line(mapped`${value.text};`);
|
|
3371
3587
|
}
|
|
3372
3588
|
assign(node, frame) {
|
|
3373
3589
|
const target = this.expression(node.left, frame);
|
|
@@ -3376,7 +3592,7 @@ class Specializer {
|
|
|
3376
3592
|
const operator = node.operatorToken.kind;
|
|
3377
3593
|
if (operator === ts11.SyntaxKind.QuestionQuestionEqualsToken) {
|
|
3378
3594
|
const value = this.expression(node.right, frame, declared && this.checker.getNonNullableType(declared));
|
|
3379
|
-
frame.emitter.open(`if (${this.isUndefinedText(text, declared)}) {`);
|
|
3595
|
+
frame.emitter.open(mapped`if (${this.isUndefinedText(text, declared)}) {`);
|
|
3380
3596
|
frame.emitter.line(this.store(target, this.wrapDefined(this.code(value, declared && this.checker.getNonNullableType(declared), frame), declared)));
|
|
3381
3597
|
frame.emitter.close();
|
|
3382
3598
|
return;
|
|
@@ -3389,18 +3605,18 @@ class Specializer {
|
|
|
3389
3605
|
const binary = compoundOperator(operator);
|
|
3390
3606
|
if (!binary)
|
|
3391
3607
|
throw new SpecializeError(node, `${node.operatorToken.getText()} is not supported.`);
|
|
3392
|
-
frame.emitter.line(this.store(target, `${text} ${binary} ${this.code(value, declared, frame)}`));
|
|
3608
|
+
frame.emitter.line(this.store(target, mapped`${text} ${binary} ${this.code(value, declared, frame)}`));
|
|
3393
3609
|
}
|
|
3394
3610
|
store(target, text) {
|
|
3395
3611
|
if (target.kind !== "code")
|
|
3396
3612
|
throw new Error("Not a place.");
|
|
3397
|
-
return target.setter ? `${target.setter}(${text});` : `${target.text} = ${text};`;
|
|
3613
|
+
return target.setter ? mapped`${target.setter}(${text});` : mapped`${target.text} = ${text};`;
|
|
3398
3614
|
}
|
|
3399
3615
|
assignmentText(value, declared, frame, iec) {
|
|
3400
3616
|
const target = iec ?? (declared && declared.flags & ts11.TypeFlags.Number ? "DINT" : undefined);
|
|
3401
3617
|
if (target && value.kind === "code" && needsConversion(value.iec ?? "DINT", target)) {
|
|
3402
3618
|
this.typeImports.add("wrap");
|
|
3403
|
-
return `wrap<${target}>(${this.code(value, undefined, frame)})`;
|
|
3619
|
+
return mapped`wrap<${target}>(${this.code(value, undefined, frame)})`;
|
|
3404
3620
|
}
|
|
3405
3621
|
if (declared && this.isOptionalRecord(declared)) {
|
|
3406
3622
|
if (value.kind === "const" && value.value === undefined)
|
|
@@ -3412,14 +3628,14 @@ class Specializer {
|
|
|
3412
3628
|
return this.code(value, declared, frame);
|
|
3413
3629
|
}
|
|
3414
3630
|
wrapDefined(text, declared) {
|
|
3415
|
-
return declared && this.isOptionalRecord(declared) ? `{ has: true, value: ${text} }` : text;
|
|
3631
|
+
return declared && this.isOptionalRecord(declared) ? mapped`{ has: true, value: ${text} }` : text;
|
|
3416
3632
|
}
|
|
3417
3633
|
isUndefinedText(text, declared) {
|
|
3418
3634
|
if (declared && this.isOptionalRecord(declared))
|
|
3419
|
-
return `!${text}.has`;
|
|
3635
|
+
return mapped`!${text}.has`;
|
|
3420
3636
|
const literal = declared && this.layouts.literalEnum(declared);
|
|
3421
3637
|
if (literal)
|
|
3422
|
-
return `${text} === ${this.layouts.member(literal, undefined)}`;
|
|
3638
|
+
return mapped`${text} === ${this.layouts.member(literal, undefined)}`;
|
|
3423
3639
|
throw new Error("Only optional values can be undefined.");
|
|
3424
3640
|
}
|
|
3425
3641
|
placeText(value, node) {
|
|
@@ -3428,6 +3644,12 @@ class Specializer {
|
|
|
3428
3644
|
throw new SpecializeError(node, "Assign to stored state: a field scan code owns, or a let.");
|
|
3429
3645
|
}
|
|
3430
3646
|
expression(node, frame, expected) {
|
|
3647
|
+
const value = this.evaluate(node, frame, expected);
|
|
3648
|
+
if (value.kind !== "code")
|
|
3649
|
+
return value;
|
|
3650
|
+
return { ...value, text: from(node, ts11.isIdentifier(node) ? String(value.text) : value.text) };
|
|
3651
|
+
}
|
|
3652
|
+
evaluate(node, frame, expected) {
|
|
3431
3653
|
if (ts11.isParenthesizedExpression(node) || ts11.isNonNullExpression(node) || ts11.isAsExpression(node) || ts11.isSatisfiesExpression(node))
|
|
3432
3654
|
return this.expression(node.expression, frame, expected);
|
|
3433
3655
|
if (ts11.isNumericLiteral(node))
|
|
@@ -3448,6 +3670,9 @@ class Specializer {
|
|
|
3448
3670
|
if (ts11.isIdentifier(node))
|
|
3449
3671
|
return this.identifier(node, frame);
|
|
3450
3672
|
if (ts11.isPropertyAccessExpression(node)) {
|
|
3673
|
+
const member = this.checker.getSymbolAtLocation(node.name)?.valueDeclaration;
|
|
3674
|
+
if (member && ts11.isEnumMember(member))
|
|
3675
|
+
return constant(this.checker.getConstantValue(member));
|
|
3451
3676
|
const object = this.expression(node.expression, frame);
|
|
3452
3677
|
if (node.questionDotToken && object.kind === "const" && object.value === undefined)
|
|
3453
3678
|
return constant(undefined);
|
|
@@ -3464,7 +3689,7 @@ class Specializer {
|
|
|
3464
3689
|
const value = this.expression(node.expression, frame);
|
|
3465
3690
|
return {
|
|
3466
3691
|
kind: "code",
|
|
3467
|
-
text: `await ${this.code(value, undefined, frame)}`,
|
|
3692
|
+
text: mapped`await ${this.code(value, undefined, frame)}`,
|
|
3468
3693
|
declared: this.checker.getTypeAtLocation(node)
|
|
3469
3694
|
};
|
|
3470
3695
|
}
|
|
@@ -3481,7 +3706,7 @@ class Specializer {
|
|
|
3481
3706
|
const whenFalse = this.expression(node.whenFalse, frame, declared);
|
|
3482
3707
|
return {
|
|
3483
3708
|
kind: "code",
|
|
3484
|
-
text: `(${this.condition(condition, node.condition, frame)} ? ${this.code(whenTrue, declared, frame)} : ${this.code(whenFalse, declared, frame)})`,
|
|
3709
|
+
text: mapped`(${this.condition(condition, node.condition, frame)} ? ${this.code(whenTrue, declared, frame)} : ${this.code(whenFalse, declared, frame)})`,
|
|
3485
3710
|
declared
|
|
3486
3711
|
};
|
|
3487
3712
|
}
|
|
@@ -3588,6 +3813,8 @@ class Specializer {
|
|
|
3588
3813
|
const stored = step.kind === "field" ? this.stored(holder, step.name) : this.storedArray(holder);
|
|
3589
3814
|
if (stored)
|
|
3590
3815
|
return this.storedField(holder, step);
|
|
3816
|
+
if (holder.owner)
|
|
3817
|
+
this.readConstants.add(tsPath({ root: holder.owner.root, steps: [...holder.owner.steps, step] }));
|
|
3591
3818
|
return this.capturedConstant(value, holder.type?.symbol?.valueDeclaration ?? this.sources[0]);
|
|
3592
3819
|
}
|
|
3593
3820
|
fieldDeclaration(holder, name) {
|
|
@@ -3601,13 +3828,54 @@ class Specializer {
|
|
|
3601
3828
|
const element = node && ts11.isArrayTypeNode(node) ? node.elementType : node && ts11.isTypeReferenceNode(node) ? node.typeArguments?.[0] : undefined;
|
|
3602
3829
|
return element ? this.layouts.iecName({ type: element }) : undefined;
|
|
3603
3830
|
}
|
|
3604
|
-
|
|
3831
|
+
arrayDeclaration(array) {
|
|
3605
3832
|
const owner = array.owner;
|
|
3606
3833
|
const last = owner?.steps.at(-1);
|
|
3607
3834
|
if (!owner || last?.kind !== "field")
|
|
3608
3835
|
return;
|
|
3609
3836
|
const holder = this.at(owner.root, owner.steps.slice(0, -1));
|
|
3610
|
-
return holder && this.
|
|
3837
|
+
return holder && this.fieldDeclaration(holder, last.name);
|
|
3838
|
+
}
|
|
3839
|
+
arrayElementIec(array) {
|
|
3840
|
+
return this.elementIec(this.arrayDeclaration(array));
|
|
3841
|
+
}
|
|
3842
|
+
folded() {
|
|
3843
|
+
const found = [];
|
|
3844
|
+
const visit = (node, owner, whole) => {
|
|
3845
|
+
const captured = node.captured;
|
|
3846
|
+
const stores = whole || captured.kind === "object" && !(owner.steps.length === 0 && this.flattened(owner.root)) && this.storedWhole(node) || captured.kind === "array" && this.storedArray(node);
|
|
3847
|
+
const members = captured.kind === "array" ? captured.items.map((item, index) => [{ kind: "index", index }, item]) : captured.kind === "object" || captured.kind === "instance" ? Object.entries(captured.fields).map(([name, field]) => [
|
|
3848
|
+
{ kind: "field", name },
|
|
3849
|
+
field
|
|
3850
|
+
]) : [];
|
|
3851
|
+
for (const [step, value] of members) {
|
|
3852
|
+
const at = { root: owner.root, steps: [...owner.steps, step] };
|
|
3853
|
+
const inner = this.model.node(value);
|
|
3854
|
+
if (inner) {
|
|
3855
|
+
if (inner.owner?.root === at.root && tsPath(inner.owner) === tsPath(at))
|
|
3856
|
+
visit(inner, at, stores);
|
|
3857
|
+
continue;
|
|
3858
|
+
}
|
|
3859
|
+
if (value.kind === "undefined" || stores || !this.readConstants.has(tsPath(at)))
|
|
3860
|
+
continue;
|
|
3861
|
+
if (step.kind === "field" && this.stored(node, step.name))
|
|
3862
|
+
continue;
|
|
3863
|
+
const declaration = step.kind === "field" ? this.fieldDeclaration(node, step.name) : this.arrayDeclaration(node);
|
|
3864
|
+
const iec = step.kind === "field" ? this.fieldIec(node, step.name) : this.arrayElementIec(node);
|
|
3865
|
+
found.push({
|
|
3866
|
+
path: tsPath(at),
|
|
3867
|
+
value,
|
|
3868
|
+
declaration: declaration ?? owner.root.declaration,
|
|
3869
|
+
...iec && { iec }
|
|
3870
|
+
});
|
|
3871
|
+
}
|
|
3872
|
+
};
|
|
3873
|
+
for (const root of this.model.roots) {
|
|
3874
|
+
const node = this.model.node(this.model.rootValues.get(root));
|
|
3875
|
+
if (node?.owner?.root === root && !root.exported && !this.kept(root.file))
|
|
3876
|
+
visit(node, { root, steps: [] }, false);
|
|
3877
|
+
}
|
|
3878
|
+
return found;
|
|
3611
3879
|
}
|
|
3612
3880
|
storedField(holder, step) {
|
|
3613
3881
|
const declared = step.kind === "index" ? holder.type && this.model.elementType(holder.type) : holder.captured.kind === "instance" ? (() => {
|
|
@@ -3617,7 +3885,7 @@ class Specializer {
|
|
|
3617
3885
|
const global = step.kind === "field" && holder.owner?.steps.length === 0 && this.flattened(holder.owner.root);
|
|
3618
3886
|
return {
|
|
3619
3887
|
kind: "code",
|
|
3620
|
-
text: `${this.pathText(holder)}${
|
|
3888
|
+
text: `${this.pathText(holder)}${this.placeStep(holder, step)}`,
|
|
3621
3889
|
declared,
|
|
3622
3890
|
place: true,
|
|
3623
3891
|
...step.kind === "field" ? {
|
|
@@ -3671,7 +3939,7 @@ class Specializer {
|
|
|
3671
3939
|
const property = object.declared && this.checker.getPropertyOfType(this.checker.getNonNullableType(object.declared), name);
|
|
3672
3940
|
return {
|
|
3673
3941
|
kind: "code",
|
|
3674
|
-
text: `${object.text}.${name}`,
|
|
3942
|
+
text: mapped`${object.text}.${name}`,
|
|
3675
3943
|
declared,
|
|
3676
3944
|
place: object.place,
|
|
3677
3945
|
iec: this.layouts.iecName(property?.valueDeclaration),
|
|
@@ -3693,7 +3961,7 @@ class Specializer {
|
|
|
3693
3961
|
return value;
|
|
3694
3962
|
return {
|
|
3695
3963
|
kind: "code",
|
|
3696
|
-
text: `${value.text}.value`,
|
|
3964
|
+
text: mapped`${value.text}.value`,
|
|
3697
3965
|
declared: this.checker.getNonNullableType(value.declared),
|
|
3698
3966
|
place: value.place
|
|
3699
3967
|
};
|
|
@@ -3741,10 +4009,10 @@ class Specializer {
|
|
|
3741
4009
|
if (object.kind === "static") {
|
|
3742
4010
|
const node = object.node;
|
|
3743
4011
|
const declared = node.type && (node.captured.kind === "array" ? this.model.elementType(node.type) : this.recordElement(node.type));
|
|
3744
|
-
const text = this.storedNode(node) ? this.pathText(node) : this.table(node);
|
|
4012
|
+
const text = this.storedNode(node) ? this.pathText(node) : this.table(node, at);
|
|
3745
4013
|
return {
|
|
3746
4014
|
kind: "code",
|
|
3747
|
-
text: `${text}[${this.code(index, undefined, frame)}]`,
|
|
4015
|
+
text: mapped`${text}[${this.code(index, undefined, frame)}]`,
|
|
3748
4016
|
declared,
|
|
3749
4017
|
place: true
|
|
3750
4018
|
};
|
|
@@ -3753,7 +4021,7 @@ class Specializer {
|
|
|
3753
4021
|
const declared = object.declared && (this.model.elementType(object.declared) ?? this.recordElement(object.declared));
|
|
3754
4022
|
return {
|
|
3755
4023
|
kind: "code",
|
|
3756
|
-
text: `${object.text}[${this.code(index, undefined, frame)}]`,
|
|
4024
|
+
text: mapped`${object.text}[${this.code(index, undefined, frame)}]`,
|
|
3757
4025
|
declared,
|
|
3758
4026
|
place: object.place,
|
|
3759
4027
|
iec: object.elementIec
|
|
@@ -3763,7 +4031,7 @@ class Specializer {
|
|
|
3763
4031
|
const text = this.materialize(object, at, frame);
|
|
3764
4032
|
return {
|
|
3765
4033
|
kind: "code",
|
|
3766
|
-
text: `${text}[${this.code(index, undefined, frame)}]`,
|
|
4034
|
+
text: mapped`${text}[${this.code(index, undefined, frame)}]`,
|
|
3767
4035
|
declared: this.checker.getTypeAtLocation(at)
|
|
3768
4036
|
};
|
|
3769
4037
|
}
|
|
@@ -3777,7 +4045,7 @@ class Specializer {
|
|
|
3777
4045
|
}
|
|
3778
4046
|
tables = new Map;
|
|
3779
4047
|
tableDeclarations = [];
|
|
3780
|
-
table(node) {
|
|
4048
|
+
table(node, at) {
|
|
3781
4049
|
const known = this.tables.get(node.id);
|
|
3782
4050
|
if (known)
|
|
3783
4051
|
return known;
|
|
@@ -3786,7 +4054,7 @@ class Specializer {
|
|
|
3786
4054
|
const name = `tsplcTable${this.tables.size + 1}`;
|
|
3787
4055
|
this.tables.set(node.id, name);
|
|
3788
4056
|
const type = this.layouts.text(node.type, { kind: "node", id: node.id });
|
|
3789
|
-
this.tableDeclarations.push(`const ${name}: ${type} = ${this.valueText({ kind: "node", id: node.id }, node.type, type)};`);
|
|
4057
|
+
this.tableDeclarations.push(from(at, `const ${name}: ${type} = ${this.valueText({ kind: "node", id: node.id }, node.type, type)};`));
|
|
3790
4058
|
return name;
|
|
3791
4059
|
}
|
|
3792
4060
|
materialize(value, at, frame) {
|
|
@@ -3795,7 +4063,7 @@ class Specializer {
|
|
|
3795
4063
|
if (!element || value.kind !== "virtual" || !value.items)
|
|
3796
4064
|
throw new SpecializeError(at, "Not an array.");
|
|
3797
4065
|
const local = frame.emitter.temporary();
|
|
3798
|
-
frame.emitter.line(`const ${local}: FixedArray<${this.layouts.text(element)}, ${Math.max(value.items.length, 1)}> = [${value.items.map((item) => this.code(item, element, frame))
|
|
4066
|
+
frame.emitter.line(mapped`const ${local}: FixedArray<${this.layouts.text(element)}, ${Math.max(value.items.length, 1)}> = [${joined(value.items.map((item) => this.code(item, element, frame)), ", ")}];`);
|
|
3799
4067
|
return local;
|
|
3800
4068
|
}
|
|
3801
4069
|
objectLiteral(node, frame) {
|
|
@@ -3822,7 +4090,7 @@ class Specializer {
|
|
|
3822
4090
|
return constant(false);
|
|
3823
4091
|
return {
|
|
3824
4092
|
kind: "code",
|
|
3825
|
-
text: `!${this.condition(operand, node.operand, frame)}`,
|
|
4093
|
+
text: mapped`!${this.condition(operand, node.operand, frame)}`,
|
|
3826
4094
|
declared: this.checker.getBooleanType()
|
|
3827
4095
|
};
|
|
3828
4096
|
case ts11.SyntaxKind.MinusToken:
|
|
@@ -3830,7 +4098,7 @@ class Specializer {
|
|
|
3830
4098
|
return constant(-operand.value);
|
|
3831
4099
|
return {
|
|
3832
4100
|
kind: "code",
|
|
3833
|
-
text: `-${this.code(operand, undefined, frame)}`,
|
|
4101
|
+
text: mapped`-${this.code(operand, undefined, frame)}`,
|
|
3834
4102
|
declared: this.checker.getTypeAtLocation(node)
|
|
3835
4103
|
};
|
|
3836
4104
|
case ts11.SyntaxKind.PlusToken:
|
|
@@ -3863,7 +4131,7 @@ class Specializer {
|
|
|
3863
4131
|
}
|
|
3864
4132
|
return {
|
|
3865
4133
|
kind: "code",
|
|
3866
|
-
text: `(${this.condition(left, node.left, frame)} ${and ? "&&" : "||"} ${this.condition(right, node.right, frame)})`,
|
|
4134
|
+
text: mapped`(${this.condition(left, node.left, frame)} ${and ? "&&" : "||"} ${this.condition(right, node.right, frame)})`,
|
|
3867
4135
|
declared: this.checker.getBooleanType()
|
|
3868
4136
|
};
|
|
3869
4137
|
}
|
|
@@ -3877,7 +4145,7 @@ class Specializer {
|
|
|
3877
4145
|
const right = this.expression(node.right, frame, declared && this.checker.getNonNullableType(declared));
|
|
3878
4146
|
return {
|
|
3879
4147
|
kind: "code",
|
|
3880
|
-
text: `(${this.isUndefinedText(this.code(left, declared, frame), declared)} ? ${this.code(right, declared && this.checker.getNonNullableType(declared), frame)} : ${this.code(left, undefined, frame)}${declared && this.isOptionalRecord(declared) ? ".value" : ""})`,
|
|
4148
|
+
text: mapped`(${this.isUndefinedText(this.code(left, declared, frame), declared)} ? ${this.code(right, declared && this.checker.getNonNullableType(declared), frame)} : ${this.code(left, undefined, frame)}${declared && this.isOptionalRecord(declared) ? ".value" : ""})`,
|
|
3881
4149
|
declared: declared && this.checker.getNonNullableType(declared)
|
|
3882
4150
|
};
|
|
3883
4151
|
}
|
|
@@ -3901,14 +4169,14 @@ class Specializer {
|
|
|
3901
4169
|
const test = this.isUndefinedText(code.text, code.declared);
|
|
3902
4170
|
return {
|
|
3903
4171
|
kind: "code",
|
|
3904
|
-
text: negate ? `!(${test})` : test,
|
|
4172
|
+
text: negate ? mapped`!(${test})` : test,
|
|
3905
4173
|
declared: this.checker.getBooleanType()
|
|
3906
4174
|
};
|
|
3907
4175
|
}
|
|
3908
4176
|
const declared = code.kind === "code" ? code.declared : undefined;
|
|
3909
4177
|
const [leftText, rightText] = this.comparable(left, right, declared, frame);
|
|
3910
|
-
const text = `${leftText} ${negate ? "!==" : "==="} ${rightText}`;
|
|
3911
|
-
return { kind: "code", text: `(${text})`, declared: this.checker.getBooleanType() };
|
|
4178
|
+
const text = mapped`${leftText} ${negate ? "!==" : "==="} ${rightText}`;
|
|
4179
|
+
return { kind: "code", text: mapped`(${text})`, declared: this.checker.getBooleanType() };
|
|
3912
4180
|
}
|
|
3913
4181
|
if (left.kind === "const" && right.kind === "const" && typeof left.value === "number" && typeof right.value === "number") {
|
|
3914
4182
|
const folded = foldNumber(kind, left.value, right.value);
|
|
@@ -3920,7 +4188,7 @@ class Specializer {
|
|
|
3920
4188
|
throw new SpecializeError(node, `${node.operatorToken.getText()} is not supported.`);
|
|
3921
4189
|
const declared = this.checker.getTypeAtLocation(node);
|
|
3922
4190
|
const [leftText, rightText] = ["<", "<=", ">", ">="].includes(operator) ? this.comparable(left, right, undefined, frame) : [this.code(left, undefined, frame), this.code(right, undefined, frame)];
|
|
3923
|
-
return { kind: "code", text: `(${leftText} ${operator} ${rightText})`, declared };
|
|
4191
|
+
return { kind: "code", text: mapped`(${leftText} ${operator} ${rightText})`, declared };
|
|
3924
4192
|
}
|
|
3925
4193
|
comparable(left, right, declared, frame) {
|
|
3926
4194
|
const leftText = this.code(left, declared, frame), rightText = this.code(right, declared, frame);
|
|
@@ -3930,7 +4198,7 @@ class Specializer {
|
|
|
3930
4198
|
if (!needsConversion(from, to) || !needsConversion(to, from))
|
|
3931
4199
|
return [leftText, rightText];
|
|
3932
4200
|
this.typeImports.add("wrap");
|
|
3933
|
-
return [`wrap<LINT>(${leftText})`, `wrap<LINT>(${rightText})`];
|
|
4201
|
+
return [mapped`wrap<LINT>(${leftText})`, mapped`wrap<LINT>(${rightText})`];
|
|
3934
4202
|
}
|
|
3935
4203
|
equal(left, right) {
|
|
3936
4204
|
if (left.kind === "const" && right.kind === "const")
|
|
@@ -3947,11 +4215,11 @@ class Specializer {
|
|
|
3947
4215
|
if (this.isOptionalRecord(declared) && !ts11.isPrefixUnaryExpression(at)) {
|
|
3948
4216
|
const type = this.checker.getTypeAtLocation(at);
|
|
3949
4217
|
if (!(type.flags & ts11.TypeFlags.BooleanLike))
|
|
3950
|
-
return `${value.text}.has`;
|
|
4218
|
+
return mapped`${value.text}.has`;
|
|
3951
4219
|
}
|
|
3952
4220
|
const literal = this.layouts.literalEnum(declared);
|
|
3953
4221
|
if (literal?.optional)
|
|
3954
|
-
return `${value.text} !== ${this.layouts.member(literal, undefined)}`;
|
|
4222
|
+
return mapped`${value.text} !== ${this.layouts.member(literal, undefined)}`;
|
|
3955
4223
|
}
|
|
3956
4224
|
return this.code(value, undefined, frame);
|
|
3957
4225
|
}
|
|
@@ -3970,6 +4238,12 @@ class Specializer {
|
|
|
3970
4238
|
};
|
|
3971
4239
|
throw new SpecializeError(node, "Object.values needs a record setup built.");
|
|
3972
4240
|
}
|
|
4241
|
+
if (this.telemetryCall(callee))
|
|
4242
|
+
return {
|
|
4243
|
+
kind: "code",
|
|
4244
|
+
text: this.telemetry(node, callee, frame),
|
|
4245
|
+
declared: this.checker.getTypeAtLocation(node)
|
|
4246
|
+
};
|
|
3973
4247
|
const receiver = this.expression(callee.expression, frame);
|
|
3974
4248
|
const items = this.items(receiver);
|
|
3975
4249
|
if (items && isArrayMethod(name))
|
|
@@ -4019,19 +4293,45 @@ class Specializer {
|
|
|
4019
4293
|
let symbol = this.checker.getSymbolAtLocation(callee);
|
|
4020
4294
|
while (symbol && symbol.flags & ts11.SymbolFlags.Alias)
|
|
4021
4295
|
symbol = this.checker.getAliasedSymbol(symbol);
|
|
4022
|
-
|
|
4296
|
+
return this.sdkFile(symbol?.declarations?.[0]?.getSourceFile().fileName ?? "");
|
|
4297
|
+
}
|
|
4298
|
+
sdkFile(file) {
|
|
4023
4299
|
return file.includes("/@tsplc/compiler/") || file.includes("/packages/compiler/");
|
|
4024
4300
|
}
|
|
4301
|
+
telemetryCall(callee) {
|
|
4302
|
+
const file = this.checker.getSymbolAtLocation(callee.name)?.declarations?.[0]?.getSourceFile().fileName ?? "";
|
|
4303
|
+
return file.endsWith("/telemetry.d.ts") && this.sdkFile(file);
|
|
4304
|
+
}
|
|
4305
|
+
telemetry(node, callee, frame) {
|
|
4306
|
+
const value = (argument) => ts11.isCallExpression(argument) && ts11.isPropertyAccessExpression(argument.expression) && this.telemetryCall(argument.expression) ? this.telemetry(argument, argument.expression, frame) : this.code(this.expression(argument, frame), this.checker.getTypeAtLocation(argument), frame);
|
|
4307
|
+
const args = node.arguments.map((argument) => {
|
|
4308
|
+
if (ts11.isStringLiteral(argument) || ts11.isNoSubstitutionTemplateLiteral(argument))
|
|
4309
|
+
return copied(argument);
|
|
4310
|
+
if (!ts11.isObjectLiteralExpression(argument))
|
|
4311
|
+
return value(argument);
|
|
4312
|
+
const properties = argument.properties.map((property) => {
|
|
4313
|
+
if (ts11.isShorthandPropertyAssignment(property))
|
|
4314
|
+
return mapped`${copied(property.name)}: ${value(property.name)}`;
|
|
4315
|
+
if (!ts11.isPropertyAssignment(property))
|
|
4316
|
+
throw new SpecializeError(property, "Name each telemetry property.");
|
|
4317
|
+
return mapped`${copied(property.name)}: ${value(property.initializer)}`;
|
|
4318
|
+
});
|
|
4319
|
+
return mapped`{ ${joined(properties, ", ")} }`;
|
|
4320
|
+
});
|
|
4321
|
+
this.telemetryImport = true;
|
|
4322
|
+
return from(node, mapped`telemetry.${callee.name.text}(${joined(args, ", ")})`);
|
|
4323
|
+
}
|
|
4025
4324
|
sdk(name, node, frame) {
|
|
4026
4325
|
const args = node.arguments.map((argument) => this.code(this.expression(argument, frame), undefined, frame));
|
|
4027
4326
|
this.sdkImports.add(name);
|
|
4028
4327
|
return {
|
|
4029
4328
|
kind: "code",
|
|
4030
|
-
text: `${name}(${args
|
|
4329
|
+
text: mapped`${name}(${joined(args, ", ")})`,
|
|
4031
4330
|
declared: this.checker.getTypeAtLocation(node)
|
|
4032
4331
|
};
|
|
4033
4332
|
}
|
|
4034
4333
|
sdkImports = new Set;
|
|
4334
|
+
telemetryImport = false;
|
|
4035
4335
|
typeImports = new Set;
|
|
4036
4336
|
math(name, node, frame) {
|
|
4037
4337
|
const args = node.arguments.map((argument) => this.expression(argument, frame));
|
|
@@ -4046,7 +4346,7 @@ class Specializer {
|
|
|
4046
4346
|
switch (name) {
|
|
4047
4347
|
case "abs": {
|
|
4048
4348
|
const local = frame.emitter.temporary();
|
|
4049
|
-
frame.emitter.line(`const ${local}: number = ${texts[0]};`);
|
|
4349
|
+
frame.emitter.line(mapped`const ${local}: number = ${texts[0]};`);
|
|
4050
4350
|
return { kind: "code", text: `(${local} < 0 ? 0 - ${local} : ${local})`, declared };
|
|
4051
4351
|
}
|
|
4052
4352
|
case "min":
|
|
@@ -4055,7 +4355,7 @@ class Specializer {
|
|
|
4055
4355
|
throw new SpecializeError(node, `Math.${name} takes two values.`);
|
|
4056
4356
|
return {
|
|
4057
4357
|
kind: "code",
|
|
4058
|
-
text: `(${texts[0]} ${name === "min" ? "<" : ">"} ${texts[1]} ? ${texts[0]} : ${texts[1]})`,
|
|
4358
|
+
text: mapped`(${texts[0]} ${name === "min" ? "<" : ">"} ${texts[1]} ? ${texts[0]} : ${texts[1]})`,
|
|
4059
4359
|
declared
|
|
4060
4360
|
};
|
|
4061
4361
|
default:
|
|
@@ -4075,7 +4375,7 @@ class Specializer {
|
|
|
4075
4375
|
const args = node.arguments.map((argument) => this.code(this.expression(argument, frame, this.checker.getContextualType(argument)), this.checker.getContextualType(argument), frame));
|
|
4076
4376
|
return {
|
|
4077
4377
|
kind: "code",
|
|
4078
|
-
text: `${client.name}.${path}(${args
|
|
4378
|
+
text: mapped`${client.name}.${path}(${joined(args, ", ")})`,
|
|
4079
4379
|
declared: this.checker.getTypeAtLocation(node)
|
|
4080
4380
|
};
|
|
4081
4381
|
}
|
|
@@ -4093,22 +4393,22 @@ class Specializer {
|
|
|
4093
4393
|
return this.expression(declaration.body, inline, expected);
|
|
4094
4394
|
}
|
|
4095
4395
|
const called = this.routine(declaration, target.self, args, target.env);
|
|
4096
|
-
const text = `${called.name}(${called.args
|
|
4396
|
+
const text = mapped`${called.name}(${joined(called.args, ", ")})`;
|
|
4097
4397
|
const returns = called.returns;
|
|
4098
4398
|
if (!returns || returns.flags & ts11.TypeFlags.Void) {
|
|
4099
4399
|
if (ts11.isExpressionStatement(at.parent))
|
|
4100
4400
|
return { kind: "code", text, declared: returns };
|
|
4101
|
-
frame.emitter.line(`${text};`);
|
|
4401
|
+
frame.emitter.line(mapped`${text};`);
|
|
4102
4402
|
return constant(undefined);
|
|
4103
4403
|
}
|
|
4104
4404
|
return { kind: "code", text, declared: returns };
|
|
4105
4405
|
}
|
|
4106
4406
|
temporaryOf(value, frame) {
|
|
4107
|
-
if (/^[\w.[\]]+$/.test(value.text))
|
|
4407
|
+
if (/^[\w.[\]]+$/.test(String(value.text)))
|
|
4108
4408
|
return value;
|
|
4109
4409
|
const local = frame.emitter.temporary();
|
|
4110
4410
|
const type = value.declared ? this.localType(value.declared) : "number";
|
|
4111
|
-
frame.emitter.line(`const ${local}: ${type} = ${value.text};`);
|
|
4411
|
+
frame.emitter.line(mapped`const ${local}: ${type} = ${value.text};`);
|
|
4112
4412
|
return { kind: "code", text: local, declared: value.declared, place: true };
|
|
4113
4413
|
}
|
|
4114
4414
|
arrayMethod(name, items, node, frame) {
|
|
@@ -4153,7 +4453,7 @@ class Specializer {
|
|
|
4153
4453
|
items.forEach((item, index) => {
|
|
4154
4454
|
const result = apply([item, constant(index)]);
|
|
4155
4455
|
if (result.kind === "code")
|
|
4156
|
-
frame.emitter.line(`${result.text};`);
|
|
4456
|
+
frame.emitter.line(mapped`${result.text};`);
|
|
4157
4457
|
});
|
|
4158
4458
|
return constant(undefined);
|
|
4159
4459
|
case "some":
|
|
@@ -4173,7 +4473,7 @@ class Specializer {
|
|
|
4173
4473
|
return constant(!some);
|
|
4174
4474
|
return {
|
|
4175
4475
|
kind: "code",
|
|
4176
|
-
text: `(${runtime
|
|
4476
|
+
text: mapped`(${joined(runtime, some ? " || " : " && ")})`,
|
|
4177
4477
|
declared: this.checker.getBooleanType()
|
|
4178
4478
|
};
|
|
4179
4479
|
}
|
|
@@ -4209,17 +4509,17 @@ class Specializer {
|
|
|
4209
4509
|
}
|
|
4210
4510
|
}
|
|
4211
4511
|
settle(value, frame) {
|
|
4212
|
-
if (value.kind !== "code" || /^[\w.[\]]+$/.test(value.text))
|
|
4512
|
+
if (value.kind !== "code" || /^[\w.[\]]+$/.test(String(value.text)))
|
|
4213
4513
|
return value;
|
|
4214
4514
|
const local = frame.emitter.temporary();
|
|
4215
|
-
frame.emitter.line(`const ${local}: ${value.declared ? this.localType(value.declared) : "boolean"} = ${value.text};`);
|
|
4515
|
+
frame.emitter.line(mapped`const ${local}: ${value.declared ? this.localType(value.declared) : "boolean"} = ${value.text};`);
|
|
4216
4516
|
return { kind: "code", text: local, declared: value.declared, place: true };
|
|
4217
4517
|
}
|
|
4218
4518
|
code(value, expected, frame) {
|
|
4219
4519
|
switch (value.kind) {
|
|
4220
4520
|
case "code":
|
|
4221
4521
|
if (expected && value.declared && this.isOptionalRecord(value.declared) && !this.isOptionalRecord(expected))
|
|
4222
|
-
return `${value.text}.value`;
|
|
4522
|
+
return mapped`${value.text}.value`;
|
|
4223
4523
|
return value.text;
|
|
4224
4524
|
case "const": {
|
|
4225
4525
|
const literal = expected && this.layouts.literalEnum(expected);
|
|
@@ -4257,7 +4557,7 @@ class Specializer {
|
|
|
4257
4557
|
}
|
|
4258
4558
|
if (value.items) {
|
|
4259
4559
|
const element = expected && this.model.elementType(expected);
|
|
4260
|
-
return `[${value.items.map((item) => this.code(item, element, frame))
|
|
4560
|
+
return mapped`[${joined(value.items.map((item) => this.code(item, element, frame)), ", ")}]`;
|
|
4261
4561
|
}
|
|
4262
4562
|
throw new Error("Empty value.");
|
|
4263
4563
|
}
|
|
@@ -4268,14 +4568,14 @@ class Specializer {
|
|
|
4268
4568
|
recordLiteral(fields, type, frame) {
|
|
4269
4569
|
const tagged = this.layouts.tagged(type);
|
|
4270
4570
|
const names = tagged ? this.taggedFields(tagged) : this.checker.getPropertiesOfType(type).map((property) => property.name);
|
|
4271
|
-
return `{ ${names.map((name) => {
|
|
4571
|
+
return mapped`{ ${joined(names.map((name) => {
|
|
4272
4572
|
const fieldType = tagged ? name === tagged.tag ? this.tagType(type, tagged) : this.taggedFieldType(type, tagged, name) : this.checker.getTypeOfSymbol(this.checker.getPropertyOfType(type, name));
|
|
4273
4573
|
const value = fields.get(name);
|
|
4274
4574
|
if (!value)
|
|
4275
4575
|
return `${name}: ${this.defaultOf(fieldType)}`;
|
|
4276
4576
|
const property = this.checker.getPropertyOfType(type, name);
|
|
4277
|
-
return `${name}: ${this.assignmentText(value, fieldType, frame, this.layouts.iecName(property?.valueDeclaration))}`;
|
|
4278
|
-
})
|
|
4577
|
+
return mapped`${name}: ${this.assignmentText(value, fieldType, frame, this.layouts.iecName(property?.valueDeclaration))}`;
|
|
4578
|
+
}), ", ")} }`;
|
|
4279
4579
|
}
|
|
4280
4580
|
}
|
|
4281
4581
|
var integerWidths = {
|
|
@@ -4314,6 +4614,7 @@ var isChild = (node, holder, field) => {
|
|
|
4314
4614
|
const last = owner.steps.at(-1);
|
|
4315
4615
|
return field === undefined || last.kind === "field" && last.name === field;
|
|
4316
4616
|
};
|
|
4617
|
+
var closingBrace = (declaration) => declaration.body && ts11.isBlock(declaration.body) ? declaration.body.getLastToken() : declaration;
|
|
4317
4618
|
var setterName = (name) => `tsplcSet_${name}`;
|
|
4318
4619
|
var stepText = (step) => step.kind === "index" ? `[${step.index}]` : `.${step.name}`;
|
|
4319
4620
|
var declarationKey = (declaration) => `${declaration.getSourceFile().fileName}:${declaration.pos}`;
|
|
@@ -4424,26 +4725,42 @@ var importPath = (from, to) => {
|
|
|
4424
4725
|
const path = relative4(dirname6(from), to).replace(/\\/g, "/").replace(/\.tsx?$/, "");
|
|
4425
4726
|
return path.startsWith("./") || path.startsWith("../") ? path : `./${path}`;
|
|
4426
4727
|
};
|
|
4427
|
-
var
|
|
4728
|
+
var constant2 = (value, iec) => {
|
|
4729
|
+
switch (value.kind) {
|
|
4730
|
+
case "number":
|
|
4731
|
+
return Number.isInteger(value.value) ? { value: { kind: "integer", value: String(value.value) }, type: iec ?? "DINT" } : { value: { kind: "float", value: value.value }, type: iec ?? "LREAL" };
|
|
4732
|
+
case "bigint":
|
|
4733
|
+
return { value: { kind: "integer", value: value.value }, type: iec ?? "LINT" };
|
|
4734
|
+
case "boolean":
|
|
4735
|
+
return { value: { kind: "bool", value: value.value }, type: "BOOL" };
|
|
4736
|
+
case "string":
|
|
4737
|
+
return { value: { kind: "string", value: value.value } };
|
|
4738
|
+
default:
|
|
4739
|
+
return;
|
|
4740
|
+
}
|
|
4741
|
+
};
|
|
4742
|
+
var lowerElaboration = (program, sdk, entries, root, positions) => {
|
|
4428
4743
|
const sources = new Map;
|
|
4429
4744
|
const diagnostics = [];
|
|
4745
|
+
const origins = new Map;
|
|
4746
|
+
const folded = [];
|
|
4747
|
+
const literals = new Map;
|
|
4748
|
+
const result = { sources, diagnostics, origins, folded, literals };
|
|
4430
4749
|
const runtime = runtimeSources(program).filter((source) => !source.isDeclarationFile && !source.fileName.startsWith(`${dirname6(sdk)}/`));
|
|
4431
4750
|
if (!needsElaboration(runtime, sdk))
|
|
4432
|
-
return
|
|
4751
|
+
return result;
|
|
4433
4752
|
const programEntries = Object.values(entries);
|
|
4434
|
-
if (programEntries.length !== 1)
|
|
4435
|
-
|
|
4436
|
-
|
|
4437
|
-
|
|
4438
|
-
};
|
|
4753
|
+
if (programEntries.length !== 1) {
|
|
4754
|
+
diagnostics.push(error7("PLC1001", "A plain TypeScript program has one entry function."));
|
|
4755
|
+
return result;
|
|
4756
|
+
}
|
|
4439
4757
|
const [entry] = programEntries;
|
|
4440
|
-
const entryFile =
|
|
4758
|
+
const entryFile = resolve3(root, entry.module).replace(/\\/g, "/");
|
|
4441
4759
|
const entrySource = program.getSourceFile(entryFile);
|
|
4442
|
-
if (!entrySource)
|
|
4443
|
-
|
|
4444
|
-
|
|
4445
|
-
|
|
4446
|
-
};
|
|
4760
|
+
if (!entrySource) {
|
|
4761
|
+
diagnostics.push(error7("PLC1001", `${entry.module} is not part of the program.`));
|
|
4762
|
+
return result;
|
|
4763
|
+
}
|
|
4447
4764
|
const checker = program.getTypeChecker();
|
|
4448
4765
|
const kept = new Set(runtime.filter((source) => keptModule(source, sdk)).map((source) => source.fileName));
|
|
4449
4766
|
const isKept = (file) => kept.has(file);
|
|
@@ -4464,12 +4781,13 @@ var lowerElaboration = (program, sdk, entries, root) => {
|
|
|
4464
4781
|
const value = model.rootValues.get(item);
|
|
4465
4782
|
const node = model.node(value);
|
|
4466
4783
|
const lines = [];
|
|
4467
|
-
const global = (name, layout, initial) => lines.push(`export let ${name}: ${layout} = ${initial}
|
|
4784
|
+
const global = (name, layout, initial, declaration = item.declaration) => lines.push(from(declaration, `export let ${name}: ${layout} = ${initial};`), from(declaration, `export function ${setterName(name)}(value: ${layout}): void { ${name} = value; }`));
|
|
4468
4785
|
if (specializer.flattened(item)) {
|
|
4469
4786
|
const captured = node.captured;
|
|
4470
4787
|
if (captured.kind === "instance") {
|
|
4788
|
+
const declaration = model.classOf(node);
|
|
4471
4789
|
for (const [name, layout] of specializer.instanceFields(node))
|
|
4472
|
-
global(name, layout, specializer.instanceFieldInitializer(node, name, layout));
|
|
4790
|
+
global(name, layout, specializer.instanceFieldInitializer(node, name, layout), model.member(declaration, name));
|
|
4473
4791
|
} else if (captured.kind === "object") {
|
|
4474
4792
|
for (const [name, field] of Object.entries(captured.fields)) {
|
|
4475
4793
|
const inner = model.node(field);
|
|
@@ -4482,7 +4800,7 @@ var lowerElaboration = (program, sdk, entries, root) => {
|
|
|
4482
4800
|
const layout = inner && !item.exported ? specializer.storageType(inner) : specializer.layouts.declaredText(node.type?.getProperty(name)?.valueDeclaration, declared, field, name.charAt(0).toUpperCase() + name.slice(1));
|
|
4483
4801
|
if (!layout)
|
|
4484
4802
|
continue;
|
|
4485
|
-
global(name, layout, specializer.valueText(field, declared, layout));
|
|
4803
|
+
global(name, layout, specializer.valueText(field, declared, layout), node.type?.getProperty(name)?.valueDeclaration);
|
|
4486
4804
|
}
|
|
4487
4805
|
}
|
|
4488
4806
|
} else {
|
|
@@ -4490,7 +4808,7 @@ var lowerElaboration = (program, sdk, entries, root) => {
|
|
|
4490
4808
|
const layout = specializer.layouts.declaredText(item.declaration, declared, value);
|
|
4491
4809
|
global(item.name, layout, specializer.valueText(value, declared, layout));
|
|
4492
4810
|
}
|
|
4493
|
-
storage.set(
|
|
4811
|
+
storage.set(item, lines);
|
|
4494
4812
|
}
|
|
4495
4813
|
const typeImports = (file) => [
|
|
4496
4814
|
...[...specializer.layouts.imports].map(([module, names]) => `import { ${[...names].join(", ")} } from "${importPath(file, module)}";`),
|
|
@@ -4502,51 +4820,55 @@ var lowerElaboration = (program, sdk, entries, root) => {
|
|
|
4502
4820
|
...enums.length ? [`import { ${enums.join(", ")} } from "${importPath(file, typesFile)}";`] : [],
|
|
4503
4821
|
...interfaces.length ? [`import type { ${interfaces.join(", ")} } from "${importPath(file, typesFile)}";`] : []
|
|
4504
4822
|
];
|
|
4505
|
-
sources.set(typesFile, [...typeImports(typesFile), ...specializer.layouts.declarations.values()]
|
|
4823
|
+
sources.set(typesFile, joined([...typeImports(typesFile), ...specializer.layouts.declarations.values()], `
|
|
4506
4824
|
`));
|
|
4507
|
-
for (const [
|
|
4508
|
-
|
|
4825
|
+
for (const [item, lines] of storage) {
|
|
4826
|
+
const file = rootModule(item);
|
|
4827
|
+
const imports = [...typeImports(file), ...importTypes(file)];
|
|
4828
|
+
sources.set(file, joined([...imports.map((line) => from(item.declaration, line)), ...lines], `
|
|
4509
4829
|
`));
|
|
4830
|
+
}
|
|
4510
4831
|
const header = [
|
|
4511
4832
|
...typeImports(entryFile),
|
|
4512
4833
|
...importTypes(entryFile),
|
|
4513
4834
|
...[...specializer.namespaces].map(([name, file]) => `import * as ${name} from "${importPath(entryFile, file)}";`),
|
|
4514
4835
|
...[...specializer.imports].map(([file, names]) => `import { ${[...names].join(", ")} } from "${importPath(entryFile, file)}";`),
|
|
4515
4836
|
...specializer.sdkImports.size ? [`import { ${[...specializer.sdkImports].join(", ")} } from "@tsplc/compiler/clock";`] : [],
|
|
4837
|
+
...specializer.telemetryImport ? [`import { telemetry } from "@tsplc/compiler/telemetry";`] : [],
|
|
4516
4838
|
...specializer.typeImports.size ? [`import { ${[...specializer.typeImports].join(", ")} } from "@tsplc/compiler/types";`] : []
|
|
4517
4839
|
];
|
|
4518
|
-
sources.set(entryFile, [
|
|
4519
|
-
...header,
|
|
4840
|
+
sources.set(entryFile, joined([
|
|
4841
|
+
...header.map((line) => from(main, line)),
|
|
4520
4842
|
...specializer.tableDeclarations,
|
|
4521
4843
|
...specializer.routines,
|
|
4522
|
-
`export function ${entry.export}(): void {
|
|
4844
|
+
from(main, `export function ${entry.export}(): void {`),
|
|
4523
4845
|
...body,
|
|
4524
|
-
"}"
|
|
4525
|
-
]
|
|
4846
|
+
from(closingBrace(main), "}")
|
|
4847
|
+
], `
|
|
4526
4848
|
`));
|
|
4849
|
+
for (const [name, origin] of specializer.origins)
|
|
4850
|
+
origins.set(`${entryFile}:${name}`, origin);
|
|
4851
|
+
for (const { name, members } of specializer.layouts.literalEnums)
|
|
4852
|
+
literals.set(`${typesFile}:${name}`, members);
|
|
4853
|
+
for (const item of specializer.folded()) {
|
|
4854
|
+
const known = constant2(item.value, item.iec);
|
|
4855
|
+
if (known)
|
|
4856
|
+
folded.push({ path: item.path, ...known, span: positions.node(item.declaration) });
|
|
4857
|
+
}
|
|
4527
4858
|
for (const source of runtime)
|
|
4528
4859
|
if (source.fileName !== entryFile && !isKept(source.fileName))
|
|
4529
|
-
sources.set(source.fileName, [
|
|
4530
|
-
...source.statements.filter((statement) => ts12.isInterfaceDeclaration(statement) || ts12.isTypeAliasDeclaration(statement) || ts12.isImportDeclaration(statement) && statement.importClause?.isTypeOnly).map(
|
|
4860
|
+
sources.set(source.fileName, joined([
|
|
4861
|
+
...source.statements.filter((statement) => ts12.isInterfaceDeclaration(statement) || ts12.isTypeAliasDeclaration(statement) || ts12.isImportDeclaration(statement) && statement.importClause?.isTypeOnly).map(copied),
|
|
4531
4862
|
"export {};"
|
|
4532
|
-
]
|
|
4863
|
+
], `
|
|
4533
4864
|
`));
|
|
4534
4865
|
} catch (cause) {
|
|
4535
|
-
if (cause instanceof SpecializeError)
|
|
4536
|
-
|
|
4537
|
-
|
|
4538
|
-
const position = source.getLineAndCharacterOfPosition(start);
|
|
4539
|
-
diagnostics.push(error7("PLC1010", cause.message, {
|
|
4540
|
-
file: source.fileName,
|
|
4541
|
-
start,
|
|
4542
|
-
end: cause.node.getEnd(),
|
|
4543
|
-
line: position.line + 1,
|
|
4544
|
-
column: position.character + 1
|
|
4545
|
-
}));
|
|
4546
|
-
} else
|
|
4866
|
+
if (cause instanceof SpecializeError)
|
|
4867
|
+
diagnostics.push(error7("PLC1010", cause.message, positions.node(cause.node)));
|
|
4868
|
+
else
|
|
4547
4869
|
diagnostics.push(error7("PLC1010", cause instanceof Error ? process.env.TSPLC_DEBUG ? String(cause.stack) : cause.message : String(cause)));
|
|
4548
4870
|
}
|
|
4549
|
-
return
|
|
4871
|
+
return result;
|
|
4550
4872
|
};
|
|
4551
4873
|
var findEntry = (source, name) => {
|
|
4552
4874
|
for (const statement of source.statements) {
|
|
@@ -4572,7 +4894,7 @@ import {
|
|
|
4572
4894
|
|
|
4573
4895
|
// packages/compiler/src/frontend/types.ts
|
|
4574
4896
|
import ts13 from "typescript";
|
|
4575
|
-
import { dirname as dirname7, relative as relative5, resolve as
|
|
4897
|
+
import { dirname as dirname7, relative as relative5, resolve as resolve4 } from "node:path";
|
|
4576
4898
|
import {
|
|
4577
4899
|
instancedBlock,
|
|
4578
4900
|
primitiveTypes,
|
|
@@ -4584,6 +4906,7 @@ function calleeName(node) {
|
|
|
4584
4906
|
return node;
|
|
4585
4907
|
return ts13.isPropertyAccessExpression(node) ? node.name : undefined;
|
|
4586
4908
|
}
|
|
4909
|
+
var telemetryMethods = ["capture", "info", "warn", "error", "captureException", "text"];
|
|
4587
4910
|
|
|
4588
4911
|
class TypeResolver {
|
|
4589
4912
|
checker;
|
|
@@ -4618,8 +4941,15 @@ class TypeResolver {
|
|
|
4618
4941
|
const symbol = this.symbol(node);
|
|
4619
4942
|
return symbol.declarations?.some((declaration) => declaration.getSourceFile().fileName.startsWith(`${dirname7(this.sdk)}/`)) ? symbol.getName() : undefined;
|
|
4620
4943
|
}
|
|
4944
|
+
telemetryMethod(node) {
|
|
4945
|
+
if (!ts13.isPropertyAccessExpression(node.expression))
|
|
4946
|
+
return;
|
|
4947
|
+
const symbol = this.checker.getSymbolAtLocation(node.expression.name);
|
|
4948
|
+
const declared = symbol?.declarations?.some((declaration) => declaration.getSourceFile().fileName === `${dirname7(this.sdk)}/telemetry.d.ts`);
|
|
4949
|
+
return declared ? telemetryMethods.find((name) => name === symbol?.name) : undefined;
|
|
4950
|
+
}
|
|
4621
4951
|
mathHelper(node, name) {
|
|
4622
|
-
return
|
|
4952
|
+
return resolve4(node.getSourceFile().fileName) === resolve4(dirname7(this.sdk), "../stdlib/math.ts") && (name === "min" || name === "max" || name === "clamp") ? name : undefined;
|
|
4623
4953
|
}
|
|
4624
4954
|
id(node, name) {
|
|
4625
4955
|
return `${relative5(this.root, node.getSourceFile().fileName).replaceAll("\\", "/")}:${node.getStart()}:${name}`;
|
|
@@ -5259,21 +5589,7 @@ class SemanticError extends Error {
|
|
|
5259
5589
|
this.diagnostic = diagnostic;
|
|
5260
5590
|
}
|
|
5261
5591
|
}
|
|
5262
|
-
function
|
|
5263
|
-
const position = source.getLineAndCharacterOfPosition(start);
|
|
5264
|
-
return {
|
|
5265
|
-
file: source.fileName,
|
|
5266
|
-
start,
|
|
5267
|
-
end,
|
|
5268
|
-
line: position.line + 1,
|
|
5269
|
-
column: position.character + 1
|
|
5270
|
-
};
|
|
5271
|
-
}
|
|
5272
|
-
function span(node) {
|
|
5273
|
-
const source = node.getSourceFile();
|
|
5274
|
-
return sourceSpan(source, node.getStart(source), node.getEnd());
|
|
5275
|
-
}
|
|
5276
|
-
function tsDiagnostic(diagnostic) {
|
|
5592
|
+
function tsDiagnostic(diagnostic, locate = sourceSpan) {
|
|
5277
5593
|
const result = {
|
|
5278
5594
|
origin: "typescript",
|
|
5279
5595
|
code: `TS${diagnostic.code}`,
|
|
@@ -5282,10 +5598,10 @@ function tsDiagnostic(diagnostic) {
|
|
|
5282
5598
|
`)
|
|
5283
5599
|
};
|
|
5284
5600
|
if (diagnostic.file && diagnostic.start !== undefined)
|
|
5285
|
-
result.span =
|
|
5601
|
+
result.span = locate(diagnostic.file, diagnostic.start, diagnostic.start + (diagnostic.length ?? 1));
|
|
5286
5602
|
return result;
|
|
5287
5603
|
}
|
|
5288
|
-
var suppressionDiagnostics = (source) => {
|
|
5604
|
+
var suppressionDiagnostics = (source, positions) => {
|
|
5289
5605
|
const diagnostics = [];
|
|
5290
5606
|
const scanner = ts15.createScanner(ts15.ScriptTarget.Latest, false, ts15.LanguageVariant.Standard, source.text);
|
|
5291
5607
|
for (let token = scanner.scan();token !== ts15.SyntaxKind.EndOfFileToken; token = scanner.scan()) {
|
|
@@ -5296,7 +5612,7 @@ var suppressionDiagnostics = (source) => {
|
|
|
5296
5612
|
if (!match)
|
|
5297
5613
|
continue;
|
|
5298
5614
|
const start = scanner.getTokenPos() + comment.indexOf(match[1] ?? "@ts-");
|
|
5299
|
-
diagnostics.push(error8("PLC1009", "TypeScript diagnostic suppression is not allowed in PLC source.",
|
|
5615
|
+
diagnostics.push(error8("PLC1009", "TypeScript diagnostic suppression is not allowed in PLC source.", positions.span(source, start, start + (match[1]?.length ?? 4))));
|
|
5300
5616
|
}
|
|
5301
5617
|
return diagnostics;
|
|
5302
5618
|
};
|
|
@@ -5325,14 +5641,14 @@ var sdkFor = (project, options) => {
|
|
|
5325
5641
|
}
|
|
5326
5642
|
};
|
|
5327
5643
|
function analyze(options) {
|
|
5328
|
-
const filename =
|
|
5644
|
+
const filename = resolve5(options.tsconfig);
|
|
5329
5645
|
const config = ts15.readConfigFile(filename, ts15.sys.readFile);
|
|
5330
5646
|
if (config.error)
|
|
5331
5647
|
return { diagnostics: [tsDiagnostic(config.error)] };
|
|
5332
5648
|
const parsed = ts15.parseJsonConfigFileContent(config.config, ts15.sys, dirname8(filename), undefined, filename);
|
|
5333
5649
|
if (parsed.errors.length)
|
|
5334
|
-
return { diagnostics: parsed.errors.map(tsDiagnostic) };
|
|
5335
|
-
const programFiles = Object.values(options.programs).map((entry) =>
|
|
5650
|
+
return { diagnostics: parsed.errors.map((diagnostic) => tsDiagnostic(diagnostic)) };
|
|
5651
|
+
const programFiles = Object.values(options.programs).map((entry) => resolve5(dirname8(filename), entry.module));
|
|
5336
5652
|
const scope = options.sourceScope ?? (options.services ? "entry" : "project");
|
|
5337
5653
|
const ambient = parsed.fileNames.filter((file) => /\.d\.[cm]?ts$/.test(file) && file.startsWith(`${dirname8(filename)}/`));
|
|
5338
5654
|
const projectFiles = scope === "project" ? parsed.fileNames : ambient;
|
|
@@ -5365,6 +5681,7 @@ function analyze(options) {
|
|
|
5365
5681
|
files.add(source);
|
|
5366
5682
|
return files;
|
|
5367
5683
|
};
|
|
5684
|
+
const positions = new Positions;
|
|
5368
5685
|
const sourceDiagnostics = (program) => [
|
|
5369
5686
|
...program.getConfigFileParsingDiagnostics(),
|
|
5370
5687
|
...program.getOptionsDiagnostics(),
|
|
@@ -5373,7 +5690,7 @@ function analyze(options) {
|
|
|
5373
5690
|
...program.getSyntacticDiagnostics(file),
|
|
5374
5691
|
...program.getSemanticDiagnostics(file)
|
|
5375
5692
|
])
|
|
5376
|
-
].map(tsDiagnostic);
|
|
5693
|
+
].map((diagnostic) => tsDiagnostic(diagnostic, positions.span));
|
|
5377
5694
|
const diagnostics = sourceDiagnostics(program);
|
|
5378
5695
|
if (program.getSyntacticDiagnostics().some((item) => !item.file || plcFiles(program).has(item.file)))
|
|
5379
5696
|
return { diagnostics };
|
|
@@ -5383,18 +5700,19 @@ function analyze(options) {
|
|
|
5383
5700
|
diagnostics.push(...lowering.diagnostics);
|
|
5384
5701
|
for (const source of runtimeSources(program))
|
|
5385
5702
|
if (lowering.sources.has(source.fileName))
|
|
5386
|
-
diagnostics.push(...suppressionDiagnostics(source));
|
|
5703
|
+
diagnostics.push(...suppressionDiagnostics(source, positions));
|
|
5387
5704
|
if (lowering.diagnostics.length || lowering.sources.size && hasErrors(diagnostics))
|
|
5388
5705
|
return false;
|
|
5389
5706
|
if (lowering.sources.size) {
|
|
5707
|
+
positions.record(lowering.sources, program);
|
|
5390
5708
|
for (const [path, text] of lowering.sources)
|
|
5391
|
-
virtualSources.set(path, text);
|
|
5709
|
+
virtualSources.set(path, text.text);
|
|
5392
5710
|
const dump = process.env.TSPLC_LOWERED;
|
|
5393
5711
|
if (dump)
|
|
5394
5712
|
for (const [path, text] of lowering.sources) {
|
|
5395
5713
|
const target = join4(dump, relative6(dirname8(filename), path));
|
|
5396
5714
|
mkdirSync(dirname8(target), { recursive: true });
|
|
5397
|
-
writeFileSync2(target, text);
|
|
5715
|
+
writeFileSync2(target, text.text);
|
|
5398
5716
|
}
|
|
5399
5717
|
host = ts15.createCompilerHost(compilerOptions);
|
|
5400
5718
|
const read = host.readFile, exists = host.fileExists;
|
|
@@ -5407,38 +5725,58 @@ function analyze(options) {
|
|
|
5407
5725
|
}
|
|
5408
5726
|
return true;
|
|
5409
5727
|
};
|
|
5410
|
-
|
|
5728
|
+
const elaboration = lowerElaboration(program, sdk, options.programs, dirname8(filename), positions);
|
|
5729
|
+
if (!apply(elaboration))
|
|
5411
5730
|
return { diagnostics };
|
|
5412
|
-
const services = lowerServices(program, sdk, options.services);
|
|
5731
|
+
const services = lowerServices(program, sdk, positions, options.services);
|
|
5413
5732
|
if (!apply(services))
|
|
5414
5733
|
return { diagnostics };
|
|
5415
|
-
const exposure = lowerExposure(program, sdk);
|
|
5734
|
+
const exposure = lowerExposure(program, sdk, positions);
|
|
5416
5735
|
if (!apply(exposure))
|
|
5417
5736
|
return { diagnostics };
|
|
5418
|
-
if (!apply(lowerEnvironment(program, sdk)))
|
|
5737
|
+
if (!apply(lowerEnvironment(program, sdk, positions)))
|
|
5419
5738
|
return { diagnostics };
|
|
5420
|
-
if (!apply(lowerConstFunctions(program)))
|
|
5739
|
+
if (!apply(lowerConstFunctions(program, positions)))
|
|
5421
5740
|
return { diagnostics };
|
|
5422
|
-
const promises = lowerPromises(program, sdk);
|
|
5741
|
+
const promises = lowerPromises(program, sdk, positions);
|
|
5423
5742
|
if (!apply(promises))
|
|
5424
5743
|
return { diagnostics };
|
|
5425
|
-
const lowering = lowerAsync(program, sdk);
|
|
5744
|
+
const lowering = lowerAsync(program, sdk, positions);
|
|
5426
5745
|
for (const [key, value] of promises.runtimeBlocks)
|
|
5427
5746
|
lowering.blocks.set(key, value);
|
|
5428
5747
|
if (!apply(lowering))
|
|
5429
5748
|
return { diagnostics };
|
|
5430
|
-
const analyzer = new Analyzer(program, host, dirname8(filename), sdk, diagnostics, serviceRecords(program, services));
|
|
5749
|
+
const analyzer = new Analyzer(program, host, dirname8(filename), sdk, diagnostics, positions, serviceRecords(program, services));
|
|
5431
5750
|
const module = analyzer.run({ ...options.programs, ...lowering.programs });
|
|
5751
|
+
const declared = (item) => `${resolve5(dirname8(filename), item.id.slice(0, item.id.indexOf(":")))}:${item.name}`;
|
|
5432
5752
|
for (const variable of module.variables) {
|
|
5433
|
-
const item = exposure.variables.get(
|
|
5753
|
+
const item = exposure.variables.get(declared(variable));
|
|
5434
5754
|
if (item)
|
|
5435
5755
|
variable.exposure = item;
|
|
5436
5756
|
}
|
|
5757
|
+
for (const fn of module.functions) {
|
|
5758
|
+
const origin = elaboration.origins.get(declared(fn));
|
|
5759
|
+
if (origin)
|
|
5760
|
+
fn.origin = origin;
|
|
5761
|
+
}
|
|
5762
|
+
module.types = module.types.map((type) => {
|
|
5763
|
+
const literals = type.kind === "enum" && elaboration.literals.get(declared({ id: type.id, name: type.id.split(":").at(-1) }));
|
|
5764
|
+
return type.kind === "enum" && literals ? {
|
|
5765
|
+
...type,
|
|
5766
|
+
members: type.members.map((member) => ({ ...member, text: literals[member.name] }))
|
|
5767
|
+
} : type;
|
|
5768
|
+
});
|
|
5437
5769
|
for (const block of module.blocks) {
|
|
5438
|
-
const runtime = lowering.blocks.get(
|
|
5770
|
+
const runtime = lowering.blocks.get(declared(block));
|
|
5439
5771
|
if (runtime)
|
|
5440
5772
|
block.runtime = runtime;
|
|
5773
|
+
const job = lowering.jobs.get(declared(block));
|
|
5774
|
+
const origin = elaboration.origins.get(declared(block));
|
|
5775
|
+
if (job)
|
|
5776
|
+
block.job = origin ? { ...job, ...origin } : job;
|
|
5441
5777
|
}
|
|
5778
|
+
if (elaboration.folded.length)
|
|
5779
|
+
module.folded = elaboration.folded;
|
|
5442
5780
|
for (const entry of module.programs) {
|
|
5443
5781
|
const background = lowering.schedules.get(entry.name);
|
|
5444
5782
|
if (background)
|
|
@@ -5461,7 +5799,7 @@ function checkHostConfig(file) {
|
|
|
5461
5799
|
skipLibCheck: true,
|
|
5462
5800
|
types: [bunTypes]
|
|
5463
5801
|
});
|
|
5464
|
-
return ts15.getPreEmitDiagnostics(program).map(tsDiagnostic);
|
|
5802
|
+
return ts15.getPreEmitDiagnostics(program).map((diagnostic) => tsDiagnostic(diagnostic));
|
|
5465
5803
|
}
|
|
5466
5804
|
|
|
5467
5805
|
class Analyzer {
|
|
@@ -5470,6 +5808,7 @@ class Analyzer {
|
|
|
5470
5808
|
root;
|
|
5471
5809
|
sdk;
|
|
5472
5810
|
diagnostics;
|
|
5811
|
+
positions;
|
|
5473
5812
|
checker;
|
|
5474
5813
|
variables = new Map;
|
|
5475
5814
|
functions = new Map;
|
|
@@ -5489,20 +5828,21 @@ class Analyzer {
|
|
|
5489
5828
|
copySources = [];
|
|
5490
5829
|
breakTargets = [];
|
|
5491
5830
|
activeFunction;
|
|
5492
|
-
constructor(program, host, root, sdk, diagnostics, serviceRecord) {
|
|
5831
|
+
constructor(program, host, root, sdk, diagnostics, positions, serviceRecord) {
|
|
5493
5832
|
this.program = program;
|
|
5494
5833
|
this.host = host;
|
|
5495
5834
|
this.root = root;
|
|
5496
5835
|
this.sdk = sdk;
|
|
5497
5836
|
this.diagnostics = diagnostics;
|
|
5837
|
+
this.positions = positions;
|
|
5498
5838
|
this.checker = program.getTypeChecker();
|
|
5499
5839
|
this.resolver = new TypeResolver(this.checker, root, sdk, this.fail, serviceRecord);
|
|
5500
|
-
this.blocks = new BlockResolver(this.resolver,
|
|
5840
|
+
this.blocks = new BlockResolver(this.resolver, positions.node, this.fail, positions.node(program.getSourceFile(sdk)));
|
|
5501
5841
|
const roots = new Set(program.getRootFileNames());
|
|
5502
5842
|
this.sources = runtimeSources(program).filter((source) => source.fileName !== sdk && !source.fileName.startsWith(`${dirname8(sdk)}/`) && !program.isSourceFileDefaultLibrary(source) && (!source.isDeclarationFile || roots.has(source.fileName)));
|
|
5503
5843
|
}
|
|
5504
5844
|
fail = (node, code, message) => {
|
|
5505
|
-
throw new SemanticError(error8(code, message,
|
|
5845
|
+
throw new SemanticError(error8(code, message, this.positions.node(node)));
|
|
5506
5846
|
};
|
|
5507
5847
|
type(node) {
|
|
5508
5848
|
return this.resolver.resolve(node, this.environment);
|
|
@@ -5550,7 +5890,7 @@ class Analyzer {
|
|
|
5550
5890
|
});
|
|
5551
5891
|
}
|
|
5552
5892
|
for (const source of this.sources) {
|
|
5553
|
-
this.diagnostics.push(...suppressionDiagnostics(source));
|
|
5893
|
+
this.diagnostics.push(...suppressionDiagnostics(source, this.positions));
|
|
5554
5894
|
for (const statement of source.statements) {
|
|
5555
5895
|
this.guard(() => this.declaration(statement));
|
|
5556
5896
|
}
|
|
@@ -5659,7 +5999,7 @@ class Analyzer {
|
|
|
5659
5999
|
resolvePrograms(entries) {
|
|
5660
6000
|
const programs = [];
|
|
5661
6001
|
for (const [name, entry] of Object.entries(entries)) {
|
|
5662
|
-
const source = this.program.getSourceFile(
|
|
6002
|
+
const source = this.program.getSourceFile(resolve5(this.root, entry.module));
|
|
5663
6003
|
if (!source) {
|
|
5664
6004
|
this.diagnostics.push(error8("PLC4001", `Program source not found: ${entry.module}.`));
|
|
5665
6005
|
continue;
|
|
@@ -5776,7 +6116,7 @@ class Analyzer {
|
|
|
5776
6116
|
mutable: !immutable,
|
|
5777
6117
|
retain: initializer?.retain ?? false,
|
|
5778
6118
|
...statement.modifiers?.some((modifier) => modifier.kind === ts15.SyntaxKind.ExportKeyword) ? { exported: true } : {},
|
|
5779
|
-
span:
|
|
6119
|
+
span: this.positions.node(declaration)
|
|
5780
6120
|
};
|
|
5781
6121
|
this.variables.set(this.resolver.symbol(declaration.name), variable);
|
|
5782
6122
|
this.globalVariables.push(variable);
|
|
@@ -5834,7 +6174,7 @@ class Analyzer {
|
|
|
5834
6174
|
mutable: mode === "inOut",
|
|
5835
6175
|
...mode && { mode },
|
|
5836
6176
|
retain: false,
|
|
5837
|
-
span:
|
|
6177
|
+
span: this.positions.node(parameter)
|
|
5838
6178
|
};
|
|
5839
6179
|
});
|
|
5840
6180
|
let result;
|
|
@@ -5857,7 +6197,7 @@ class Analyzer {
|
|
|
5857
6197
|
parameters,
|
|
5858
6198
|
locals: [],
|
|
5859
6199
|
body: [],
|
|
5860
|
-
span:
|
|
6200
|
+
span: this.positions.node(node),
|
|
5861
6201
|
...result && { result },
|
|
5862
6202
|
...bounds && { bounds }
|
|
5863
6203
|
};
|
|
@@ -5941,7 +6281,7 @@ class Analyzer {
|
|
|
5941
6281
|
this.fail(node, "PLC2002", cause instanceof Error ? cause.message : "Invalid integer literal.");
|
|
5942
6282
|
}
|
|
5943
6283
|
}
|
|
5944
|
-
return this.checked({ kind: "constant", type, value, span:
|
|
6284
|
+
return this.checked({ kind: "constant", type, value, span: this.positions.node(node) });
|
|
5945
6285
|
}
|
|
5946
6286
|
expression(node, expected) {
|
|
5947
6287
|
if (ts15.isParenthesizedExpression(node) || ts15.isSatisfiesExpression(node) || ts15.isAsExpression(node) && ts15.isConstTypeReference(node.type))
|
|
@@ -5953,7 +6293,7 @@ class Analyzer {
|
|
|
5953
6293
|
return expected ? this.coerce(value, expected) : value;
|
|
5954
6294
|
}
|
|
5955
6295
|
rawExpression(node, expected) {
|
|
5956
|
-
const origin = { span:
|
|
6296
|
+
const origin = { span: this.positions.node(node) };
|
|
5957
6297
|
if (node.kind === ts15.SyntaxKind.TrueKeyword || node.kind === ts15.SyntaxKind.FalseKeyword) {
|
|
5958
6298
|
return {
|
|
5959
6299
|
...origin,
|
|
@@ -6141,7 +6481,7 @@ class Analyzer {
|
|
|
6141
6481
|
this.fail(node, "PLC1001", `${ts15.SyntaxKind[node.kind]} is not supported in PLC expressions.`);
|
|
6142
6482
|
}
|
|
6143
6483
|
binaryExpression(node, expected) {
|
|
6144
|
-
const origin = { span:
|
|
6484
|
+
const origin = { span: this.positions.node(node) };
|
|
6145
6485
|
const operator = operators.get(node.operatorToken.kind);
|
|
6146
6486
|
if (!operator)
|
|
6147
6487
|
this.fail(node.operatorToken, "PLC2001", "Unsupported binary operation; implicit coercion is prohibited.");
|
|
@@ -6168,7 +6508,7 @@ class Analyzer {
|
|
|
6168
6508
|
});
|
|
6169
6509
|
}
|
|
6170
6510
|
sdkExpression(node, expected) {
|
|
6171
|
-
const origin = { span:
|
|
6511
|
+
const origin = { span: this.positions.node(node) };
|
|
6172
6512
|
const official = this.sdkCall(node);
|
|
6173
6513
|
if (official === "errorCode") {
|
|
6174
6514
|
if (node.arguments.length !== 1)
|
|
@@ -6323,7 +6663,7 @@ class Analyzer {
|
|
|
6323
6663
|
instance: place.root,
|
|
6324
6664
|
...index && { index },
|
|
6325
6665
|
inputs,
|
|
6326
|
-
span:
|
|
6666
|
+
span: this.positions.node(node)
|
|
6327
6667
|
};
|
|
6328
6668
|
}
|
|
6329
6669
|
call(node) {
|
|
@@ -6382,13 +6722,18 @@ class Analyzer {
|
|
|
6382
6722
|
const target = this.target(value.arguments[0]);
|
|
6383
6723
|
if (target.type !== parameter.type)
|
|
6384
6724
|
this.fail(value, "PLC2001", "Borrowed place type must exactly match its InOut parameter.");
|
|
6385
|
-
return {
|
|
6725
|
+
return {
|
|
6726
|
+
kind: "borrow",
|
|
6727
|
+
place: target.place,
|
|
6728
|
+
type: target.type,
|
|
6729
|
+
span: this.positions.node(value)
|
|
6730
|
+
};
|
|
6386
6731
|
}
|
|
6387
6732
|
if (this.resolver.types.get(parameter.type)?.kind === "block") {
|
|
6388
6733
|
const place = this.place(value);
|
|
6389
6734
|
if (placeType(place, this.resolver.types, this.byId(), this.ranges).type !== parameter.type)
|
|
6390
6735
|
this.fail(value, "PLC2001", "Pass a block instance of the parameter's type.");
|
|
6391
|
-
return { kind: "borrow", place, type: parameter.type, span:
|
|
6736
|
+
return { kind: "borrow", place, type: parameter.type, span: this.positions.node(value) };
|
|
6392
6737
|
}
|
|
6393
6738
|
return this.reference(this.expression(value, parameter.type), parameter);
|
|
6394
6739
|
}
|
|
@@ -6511,7 +6856,7 @@ class Analyzer {
|
|
|
6511
6856
|
return { place, type: type.type };
|
|
6512
6857
|
}
|
|
6513
6858
|
statement(node, locals) {
|
|
6514
|
-
const origin = { span:
|
|
6859
|
+
const origin = { span: this.positions.node(node) };
|
|
6515
6860
|
if (ts15.isBlock(node))
|
|
6516
6861
|
return this.statements(node.statements, locals);
|
|
6517
6862
|
if (ts15.isEmptyStatement(node))
|
|
@@ -6568,6 +6913,9 @@ class Analyzer {
|
|
|
6568
6913
|
if (ts15.isExpressionStatement(node)) {
|
|
6569
6914
|
const expression = node.expression;
|
|
6570
6915
|
if (ts15.isCallExpression(expression)) {
|
|
6916
|
+
const telemetry = this.telemetry(expression);
|
|
6917
|
+
if (telemetry)
|
|
6918
|
+
return [telemetry];
|
|
6571
6919
|
const update = this.update(expression);
|
|
6572
6920
|
if (update)
|
|
6573
6921
|
return [update];
|
|
@@ -6601,8 +6949,73 @@ class Analyzer {
|
|
|
6601
6949
|
}
|
|
6602
6950
|
this.fail(node, "PLC1001", `${ts15.SyntaxKind[node.kind]} is not supported in PLC scan code.`);
|
|
6603
6951
|
}
|
|
6952
|
+
telemetry(node) {
|
|
6953
|
+
const method = this.resolver.telemetryMethod(node);
|
|
6954
|
+
if (!method)
|
|
6955
|
+
return;
|
|
6956
|
+
if (method === "text")
|
|
6957
|
+
this.fail(node, "PLC2001", "telemetry.text is a property value of a telemetry call.");
|
|
6958
|
+
const [first, properties, ...rest] = node.arguments;
|
|
6959
|
+
if (!first || rest.length || node.typeArguments?.length)
|
|
6960
|
+
this.fail(node, "PLC2001", `telemetry.${method} takes one value and optional properties.`);
|
|
6961
|
+
const literal = (label) => {
|
|
6962
|
+
if (!ts15.isStringLiteral(first) && !ts15.isNoSubstitutionTemplateLiteral(first))
|
|
6963
|
+
this.fail(first, "PLC2001", `telemetry.${method} needs its ${label} as a string literal; put changing values in its properties.`);
|
|
6964
|
+
return first.text;
|
|
6965
|
+
};
|
|
6966
|
+
let record;
|
|
6967
|
+
switch (method) {
|
|
6968
|
+
case "captureException":
|
|
6969
|
+
record = { kind: "exception", code: this.expression(first, "UDINT") };
|
|
6970
|
+
break;
|
|
6971
|
+
case "capture":
|
|
6972
|
+
record = { kind: "event", event: literal("event name") };
|
|
6973
|
+
break;
|
|
6974
|
+
default:
|
|
6975
|
+
record = { kind: "log", level: method, message: literal("message") };
|
|
6976
|
+
}
|
|
6977
|
+
return {
|
|
6978
|
+
span: this.positions.node(node),
|
|
6979
|
+
kind: "telemetry",
|
|
6980
|
+
record,
|
|
6981
|
+
properties: properties ? this.telemetryProperties(properties) : []
|
|
6982
|
+
};
|
|
6983
|
+
}
|
|
6984
|
+
telemetryProperties(node) {
|
|
6985
|
+
if (!ts15.isObjectLiteralExpression(node))
|
|
6986
|
+
this.fail(node, "PLC2001", "Telemetry properties are an object literal.");
|
|
6987
|
+
if (node.properties.length > 8)
|
|
6988
|
+
this.fail(node, "PLC2001", "A telemetry call has at most 8 properties.");
|
|
6989
|
+
return node.properties.map((property) => {
|
|
6990
|
+
if (!(ts15.isPropertyAssignment(property) || ts15.isShorthandPropertyAssignment(property)) || !ts15.isIdentifier(property.name))
|
|
6991
|
+
this.fail(property, "PLC2001", "Name each telemetry property with an identifier.");
|
|
6992
|
+
const name = property.name.text;
|
|
6993
|
+
const value = ts15.isPropertyAssignment(property) ? property.initializer : property.name;
|
|
6994
|
+
if (ts15.isCallExpression(value) && this.resolver.telemetryMethod(value) === "text") {
|
|
6995
|
+
const [bytes, length] = value.arguments;
|
|
6996
|
+
if (!bytes || !length || value.arguments.length !== 2)
|
|
6997
|
+
this.fail(value, "PLC2001", "telemetry.text takes a byte array and a length.");
|
|
6998
|
+
const place = this.place(bytes), type = placeType(place, this.resolver.types, this.byId(), this.ranges).type, array = type === undefined ? undefined : this.resolver.types.get(type), element = array?.kind === "array" ? this.resolver.types.get(array.element) : undefined;
|
|
6999
|
+
if (!type || element?.kind !== "bits" && element?.kind !== "integer" || element.bits !== 8)
|
|
7000
|
+
this.fail(bytes, "PLC2001", "telemetry.text reads an array of BYTE.");
|
|
7001
|
+
const counted = this.expression(length);
|
|
7002
|
+
if (!["integer", "bits"].includes(this.resolver.types.get(counted.type)?.kind ?? ""))
|
|
7003
|
+
this.fail(length, "PLC2001", "telemetry.text needs an integer length.");
|
|
7004
|
+
return {
|
|
7005
|
+
name,
|
|
7006
|
+
value: { kind: "borrow", place, type, span: this.positions.node(bytes) },
|
|
7007
|
+
length: counted
|
|
7008
|
+
};
|
|
7009
|
+
}
|
|
7010
|
+
const expression = this.expression(value);
|
|
7011
|
+
const type = this.resolver.types.get(expression.type);
|
|
7012
|
+
if (!type || !["bool", "integer", "bits", "float", "enum", "string"].includes(type.kind) || type.kind === "string" && type.encoding !== "utf8")
|
|
7013
|
+
this.fail(value, "PLC2001", `Telemetry property ${name} is ${expression.type}; send BOOL, integers, REAL, LREAL, enums, STRINGs or telemetry.text(bytes, length).`);
|
|
7014
|
+
return { name, value: expression };
|
|
7015
|
+
});
|
|
7016
|
+
}
|
|
6604
7017
|
switchStatement(node, locals) {
|
|
6605
|
-
const origin = { span:
|
|
7018
|
+
const origin = { span: this.positions.node(node) };
|
|
6606
7019
|
this.breakTargets.push("switch");
|
|
6607
7020
|
try {
|
|
6608
7021
|
const value = this.expression(node.expression);
|
|
@@ -6642,7 +7055,7 @@ class Analyzer {
|
|
|
6642
7055
|
}
|
|
6643
7056
|
}
|
|
6644
7057
|
localDeclarations(node, locals) {
|
|
6645
|
-
const origin = { span:
|
|
7058
|
+
const origin = { span: this.positions.node(node) };
|
|
6646
7059
|
if (!(node.declarationList.flags & (ts15.NodeFlags.Let | ts15.NodeFlags.Const)))
|
|
6647
7060
|
this.fail(node, "PLC1001", "Use let or const for invocation locals.");
|
|
6648
7061
|
return node.declarationList.declarations.flatMap((declaration) => {
|
|
@@ -6674,7 +7087,7 @@ class Analyzer {
|
|
|
6674
7087
|
storage: "local",
|
|
6675
7088
|
mutable: !(node.declarationList.flags & ts15.NodeFlags.Const),
|
|
6676
7089
|
retain: false,
|
|
6677
|
-
span:
|
|
7090
|
+
span: this.positions.node(declaration)
|
|
6678
7091
|
};
|
|
6679
7092
|
this.variables.set(this.resolver.symbol(declaration.name), variable);
|
|
6680
7093
|
locals.push(variable);
|
|
@@ -6704,7 +7117,7 @@ class Analyzer {
|
|
|
6704
7117
|
storage: "local",
|
|
6705
7118
|
mutable: true,
|
|
6706
7119
|
retain: false,
|
|
6707
|
-
span:
|
|
7120
|
+
span: this.positions.node(declaration)
|
|
6708
7121
|
};
|
|
6709
7122
|
this.variables.set(this.resolver.symbol(declaration.name), counter);
|
|
6710
7123
|
locals.push(counter);
|
|
@@ -6767,7 +7180,7 @@ class Analyzer {
|
|
|
6767
7180
|
try {
|
|
6768
7181
|
return [
|
|
6769
7182
|
{
|
|
6770
|
-
span:
|
|
7183
|
+
span: this.positions.node(node),
|
|
6771
7184
|
kind: "for",
|
|
6772
7185
|
counter: counter.id,
|
|
6773
7186
|
...existing && { counterScope: "existing" },
|
|
@@ -6810,23 +7223,28 @@ class Analyzer {
|
|
|
6810
7223
|
{
|
|
6811
7224
|
kind: "assign",
|
|
6812
7225
|
destination: { root: counter.id, path: [] },
|
|
6813
|
-
value: {
|
|
6814
|
-
|
|
7226
|
+
value: {
|
|
7227
|
+
kind: "constant",
|
|
7228
|
+
type,
|
|
7229
|
+
value: start,
|
|
7230
|
+
span: this.positions.node(initializer)
|
|
7231
|
+
},
|
|
7232
|
+
span: this.positions.node(node.initializer)
|
|
6815
7233
|
}
|
|
6816
7234
|
] : [];
|
|
6817
7235
|
const limit = {
|
|
6818
7236
|
kind: "constant",
|
|
6819
7237
|
type,
|
|
6820
7238
|
value: { kind: "integer", value: String(finish) },
|
|
6821
|
-
span:
|
|
7239
|
+
span: this.positions.node(condition.right)
|
|
6822
7240
|
};
|
|
6823
7241
|
return [
|
|
6824
7242
|
{
|
|
6825
|
-
span:
|
|
7243
|
+
span: this.positions.node(node),
|
|
6826
7244
|
kind: "for",
|
|
6827
7245
|
counter: counter.id,
|
|
6828
7246
|
...existing && { counterScope: "existing" },
|
|
6829
|
-
start: { kind: "constant", type, value: start, span:
|
|
7247
|
+
start: { kind: "constant", type, value: start, span: this.positions.node(initializer) },
|
|
6830
7248
|
limit,
|
|
6831
7249
|
step: String(step),
|
|
6832
7250
|
maxIterations: Number(count),
|
|
@@ -6864,7 +7282,7 @@ class Analyzer {
|
|
|
6864
7282
|
for (const segment of place.path)
|
|
6865
7283
|
if (segment.kind === "index" && !this.unchanging(segment.value))
|
|
6866
7284
|
this.fail(node.expression, "PLC3003", "An iterated array's index must keep its value.");
|
|
6867
|
-
const origin = { span:
|
|
7285
|
+
const origin = { span: this.positions.node(node) };
|
|
6868
7286
|
const local = (declaration, name, type) => {
|
|
6869
7287
|
const variable = {
|
|
6870
7288
|
id: this.storageId(declaration, name),
|
|
@@ -6873,7 +7291,7 @@ class Analyzer {
|
|
|
6873
7291
|
storage: "local",
|
|
6874
7292
|
mutable: true,
|
|
6875
7293
|
retain: false,
|
|
6876
|
-
span:
|
|
7294
|
+
span: this.positions.node(declaration)
|
|
6877
7295
|
};
|
|
6878
7296
|
locals.push(variable);
|
|
6879
7297
|
return variable;
|
|
@@ -6953,5 +7371,5 @@ export {
|
|
|
6953
7371
|
typeCheckOnly
|
|
6954
7372
|
};
|
|
6955
7373
|
|
|
6956
|
-
//# debugId=
|
|
7374
|
+
//# debugId=C2116D995BFF027B64756E2164756E21
|
|
6957
7375
|
//# sourceMappingURL=index.js.map
|