@tsplc/compiler 0.5.5 → 0.5.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bun-runtime.js +152 -31
- package/dist/bun-runtime.js.map +10 -9
- package/dist/cli.js +8 -5
- package/dist/cli.js.map +3 -3
- package/dist/codesys.js +260 -85
- package/dist/codesys.js.map +9 -9
- package/dist/collections.js +395 -0
- package/dist/collections.js.map +10 -0
- package/dist/elaborate-capture.js +62 -4
- package/dist/elaborate-capture.js.map +4 -4
- package/dist/index.js +5322 -1058
- package/dist/index.js.map +30 -23
- package/dist/ir.js +122 -1
- package/dist/ir.js.map +6 -6
- package/dist/project.js +8 -5
- package/dist/project.js.map +3 -3
- package/package.json +14 -9
- package/src/codesys/emit.ts +8 -2
- package/src/codesys/http.ts +114 -72
- package/src/codesys/instrumentation.ts +30 -6
- package/src/codesys/numeric.ts +61 -0
- package/src/codesys/routines.ts +39 -9
- package/src/codesys/st-files.ts +73 -6
- package/src/codesys/telemetry.ts +70 -35
- package/src/frontend/control-flow.ts +752 -0
- package/src/frontend/coroutines.ts +171 -7
- package/src/frontend/elaborate/array-searches.ts +216 -0
- package/src/frontend/elaborate/assignments.ts +352 -0
- package/src/frontend/elaborate/calls.ts +467 -42
- package/src/frontend/elaborate/capture-protocol.ts +19 -0
- package/src/frontend/elaborate/capture.ts +80 -2
- package/src/frontend/elaborate/dialect.ts +116 -2
- package/src/frontend/elaborate/expressions.ts +927 -80
- package/src/frontend/elaborate/filtered-arrays.ts +607 -0
- package/src/frontend/elaborate/frame.ts +44 -1
- package/src/frontend/elaborate/generics.ts +137 -0
- package/src/frontend/elaborate/graph.ts +91 -0
- package/src/frontend/elaborate/index.ts +30 -5
- package/src/frontend/elaborate/initializers.ts +15 -1
- package/src/frontend/elaborate/iterators.ts +1677 -0
- package/src/frontend/elaborate/layouts.ts +41 -19
- package/src/frontend/elaborate/model.ts +64 -8
- package/src/frontend/elaborate/references.ts +749 -0
- package/src/frontend/elaborate/specialize.ts +459 -29
- package/src/frontend/elaborate/statements.ts +552 -133
- package/src/frontend/elaborate/storage.ts +151 -10
- package/src/frontend/elaborate/values.ts +72 -0
- package/src/frontend/elaborate/writes.ts +302 -1
- package/src/frontend/intrinsics.ts +32 -0
- package/src/frontend/module-graph.ts +2 -1
- package/src/frontend/positions.ts +12 -5
- package/src/frontend/typescript.ts +5 -1
- package/src/ir/core-model.ts +2 -6
- package/src/ir/fold.ts +30 -1
- package/src/ir/index.ts +5 -0
- package/src/ir/model.ts +53 -2
- package/src/ir/scalars.ts +126 -0
- package/src/runtime/.runtime-VaUSOu/server/router.ts +17 -0
- package/src/runtime/.runtime-VaUSOu/src/cell.ts +45 -0
- package/src/runtime/.runtime-VaUSOu/src/controller.ts +58 -0
- package/src/runtime/.runtime-VaUSOu/src/lane.ts +6 -0
- package/src/runtime/.runtime-VaUSOu/src/main.ts +11 -0
- package/src/runtime/.runtime-VaUSOu/src/services.ts +8 -0
- package/src/runtime/.runtime-VaUSOu/tsconfig.json +13 -0
- package/src/runtime/.runtime-VaUSOu/tsplc.config.ts +31 -0
- package/src/runtime/.runtime-ybIxYh/server/router.ts +17 -0
- package/src/runtime/.runtime-ybIxYh/src/cell.ts +45 -0
- package/src/runtime/.runtime-ybIxYh/src/controller.ts +58 -0
- package/src/runtime/.runtime-ybIxYh/src/lane.ts +6 -0
- package/src/runtime/.runtime-ybIxYh/src/main.ts +11 -0
- package/src/runtime/.runtime-ybIxYh/src/services.ts +8 -0
- package/src/runtime/.runtime-ybIxYh/tsconfig.json +13 -0
- package/src/runtime/.runtime-ybIxYh/tsplc.config.ts +31 -0
- package/src/runtime/async.ts +15 -12
- package/src/runtime/launch.ts +11 -4
- package/src/runtime/runtime.ts +26 -23
- package/src/runtime/telemetry.ts +14 -6
- package/src/runtime/transport.ts +172 -0
- package/stdlib/collections.ts +514 -0
- package/types/index.d.ts +18 -0
|
@@ -0,0 +1,1677 @@
|
|
|
1
|
+
import { primitiveTypes } from "@tsplc/compiler/ir";
|
|
2
|
+
import ts from "typescript";
|
|
3
|
+
import { joined, Mapped, mapped, type Part } from "../positions";
|
|
4
|
+
import type { DialectText } from "./dialect";
|
|
5
|
+
import type { ExpressionSpecializer, SpecializeContext } from "./expressions";
|
|
6
|
+
import { Emitter, type Frame } from "./frame";
|
|
7
|
+
import type { Initializers } from "./initializers";
|
|
8
|
+
import type { Model, ModelNode } from "./model";
|
|
9
|
+
import { referenceIndex, referenceLayout } from "./references";
|
|
10
|
+
import {
|
|
11
|
+
type Counted,
|
|
12
|
+
constant,
|
|
13
|
+
type FunctionLike,
|
|
14
|
+
repeatable,
|
|
15
|
+
SpecializeError,
|
|
16
|
+
type Value,
|
|
17
|
+
} from "./values";
|
|
18
|
+
|
|
19
|
+
/** How a local keeps what a traversal passes on: its PLC type, what it holds before anything is stored, and a value going in and coming out. */
|
|
20
|
+
interface Slot {
|
|
21
|
+
type: string;
|
|
22
|
+
empty: () => string | Mapped;
|
|
23
|
+
store: (value: Value) => Part;
|
|
24
|
+
read: (place: string | Mapped) => Value;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** A generator call as it runs in place: its body, the object it runs on and its arguments. */
|
|
28
|
+
export interface GeneratorCall {
|
|
29
|
+
declaration: FunctionLike;
|
|
30
|
+
self?: ModelNode;
|
|
31
|
+
args: Value[];
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The labelled statements around the code that uses one element: leaving `label` moves on to the
|
|
36
|
+
* next element, and leaving `whole` ends the traversal.
|
|
37
|
+
*/
|
|
38
|
+
export interface Jumps {
|
|
39
|
+
whole: string;
|
|
40
|
+
label: string;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** One element where a traversal reaches it. */
|
|
44
|
+
export interface Visited extends Jumps {
|
|
45
|
+
value: Value;
|
|
46
|
+
/** Its position among the traversal's elements, where the traversal knows it. */
|
|
47
|
+
index?: Value;
|
|
48
|
+
/** How many times the code written for this visit can run in one traversal; undefined when no loop bound says. */
|
|
49
|
+
repeats: number | undefined;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Elements in the order JavaScript reads them. `run` writes the code that reaches each one, and
|
|
54
|
+
* `visit` writes, inside it, the code that uses the element.
|
|
55
|
+
*/
|
|
56
|
+
export interface Traversal {
|
|
57
|
+
run(frame: Frame, visit: (element: Visited) => void): void;
|
|
58
|
+
/** Whether each element comes with its position, as an array's do. */
|
|
59
|
+
indexed?: boolean;
|
|
60
|
+
/** The most elements it can pass on whatever it reads, as `take(2)` sets. */
|
|
61
|
+
limit?: number;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Runs a generator's body in place. The statement specializer does, which is built after this. */
|
|
65
|
+
export interface GeneratorRunner {
|
|
66
|
+
run(
|
|
67
|
+
generator: GeneratorCall,
|
|
68
|
+
frame: Frame,
|
|
69
|
+
at: ts.Node,
|
|
70
|
+
each: (value: Value, jumps: Jumps) => void,
|
|
71
|
+
): void;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Iterator helpers that give another iterator, which runs only once something reads it. */
|
|
75
|
+
const adapters = new Set(["map", "filter", "take", "drop", "flatMap"]);
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* JavaScript's iterator helpers over generators, and arrays whose length is decided at run time.
|
|
79
|
+
* A generator runs in place, so a helper is code at each of its yields: `some` stops it at the
|
|
80
|
+
* first element that decides, and `toArray` copies what it yields into a local array sized for
|
|
81
|
+
* the most it can yield. A slice with runtime bounds copies nothing: it is the same elements,
|
|
82
|
+
* each read only when its index is in range.
|
|
83
|
+
*/
|
|
84
|
+
export class Iterators {
|
|
85
|
+
private readonly model: Model;
|
|
86
|
+
private readonly checker: ts.TypeChecker;
|
|
87
|
+
private readonly dialect: DialectText;
|
|
88
|
+
private readonly initializers: Initializers;
|
|
89
|
+
private runner: GeneratorRunner | undefined;
|
|
90
|
+
/** How many times the body of each loop being written can run, outermost first; undefined for a loop with no counted bound. */
|
|
91
|
+
private readonly loops: (number | undefined)[] = [];
|
|
92
|
+
|
|
93
|
+
constructor(
|
|
94
|
+
context: SpecializeContext,
|
|
95
|
+
private readonly expressions: ExpressionSpecializer,
|
|
96
|
+
) {
|
|
97
|
+
this.model = context.model;
|
|
98
|
+
this.checker = context.checker;
|
|
99
|
+
this.dialect = context.dialect;
|
|
100
|
+
this.initializers = context.initializers;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
attach(runner: GeneratorRunner): void {
|
|
104
|
+
this.runner = runner;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Writes the body of a loop that stays a loop in the PLC. A yield in it runs up to `runs` times,
|
|
109
|
+
* which sizes a snapshot of the generator; an unrolled loop needs none, as each step is written out.
|
|
110
|
+
*/
|
|
111
|
+
looping<T>(runs: number | undefined, body: () => T): T {
|
|
112
|
+
this.loops.push(runs);
|
|
113
|
+
try {
|
|
114
|
+
return body();
|
|
115
|
+
} finally {
|
|
116
|
+
this.loops.pop();
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** A helper called on an iterator: what it is worth, or undefined when the call is no iterator helper. */
|
|
121
|
+
call(node: ts.CallExpression, frame: Frame): Value | undefined {
|
|
122
|
+
const helper = this.helper(node);
|
|
123
|
+
if (!helper) {
|
|
124
|
+
return undefined;
|
|
125
|
+
}
|
|
126
|
+
if (adapters.has(helper.name)) {
|
|
127
|
+
throw new SpecializeError(
|
|
128
|
+
node,
|
|
129
|
+
`${helper.name} gives an iterator, which runs only where it is read: follow it with toArray, some, every, find, forEach or reduce, or loop over it with for…of.`,
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
return this.terminal(
|
|
133
|
+
helper.name,
|
|
134
|
+
this.pipeline(helper.receiver, frame),
|
|
135
|
+
node,
|
|
136
|
+
frame,
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** The iterator a for…of loops over, when helpers read a generator call into it. */
|
|
141
|
+
iterated(node: ts.Expression, frame: Frame): Traversal | undefined {
|
|
142
|
+
const helper = this.helper(unwrapped(node));
|
|
143
|
+
return helper && adapters.has(helper.name)
|
|
144
|
+
? this.pipeline(node, frame)
|
|
145
|
+
: undefined;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** A method called on a counted array. */
|
|
149
|
+
method(
|
|
150
|
+
name: string,
|
|
151
|
+
receiver: Counted,
|
|
152
|
+
node: ts.CallExpression,
|
|
153
|
+
frame: Frame,
|
|
154
|
+
): Value {
|
|
155
|
+
if (name === "slice") {
|
|
156
|
+
const [start, end] = node.arguments.map((argument) =>
|
|
157
|
+
this.expressions.expression(argument, frame),
|
|
158
|
+
);
|
|
159
|
+
if (receiver.source.kind === "items" || !receiver.source.snapshot) {
|
|
160
|
+
this.readInPlace(node);
|
|
161
|
+
}
|
|
162
|
+
return this.slice(receiver, { start, end }, node, frame);
|
|
163
|
+
}
|
|
164
|
+
const { source } = receiver;
|
|
165
|
+
if (
|
|
166
|
+
source.kind === "items" &&
|
|
167
|
+
(name === "some" || name === "every" || name === "includes")
|
|
168
|
+
) {
|
|
169
|
+
return this.tested(name, receiver, source.items, node, frame);
|
|
170
|
+
}
|
|
171
|
+
return this.terminal(name, this.over(receiver), node, frame);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* `array.slice(start, end)` over elements setup fixed, with a bound decided at run time. Nothing
|
|
176
|
+
* is copied, so the slice is read where it is made, before anything can change the elements.
|
|
177
|
+
*/
|
|
178
|
+
sliced(
|
|
179
|
+
items: readonly Value[],
|
|
180
|
+
bounds: { start: Value | undefined; end: Value | undefined },
|
|
181
|
+
node: ts.CallExpression,
|
|
182
|
+
frame: Frame,
|
|
183
|
+
): Value {
|
|
184
|
+
this.readInPlace(node);
|
|
185
|
+
return this.slice(
|
|
186
|
+
{
|
|
187
|
+
kind: "counted",
|
|
188
|
+
source: { kind: "items", items },
|
|
189
|
+
start: constant(0),
|
|
190
|
+
end: constant(items.length),
|
|
191
|
+
},
|
|
192
|
+
bounds,
|
|
193
|
+
node,
|
|
194
|
+
frame,
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
private readInPlace(node: ts.CallExpression): void {
|
|
199
|
+
const user = outside(node);
|
|
200
|
+
if (
|
|
201
|
+
!ts.isPropertyAccessExpression(user) &&
|
|
202
|
+
!ts.isElementAccessExpression(user) &&
|
|
203
|
+
!ts.isForOfStatement(user)
|
|
204
|
+
) {
|
|
205
|
+
throw new SpecializeError(
|
|
206
|
+
node,
|
|
207
|
+
"A slice with bounds decided at run time has no array to keep: read it where it is made, with every, some, find, findIndex, forEach, includes, indexOf, length or for…of.",
|
|
208
|
+
);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** The counted array a method is called on: the receiver when it is one, or a runtime array a slice is taken of. */
|
|
213
|
+
receiver(value: Value, method: string): Counted | undefined {
|
|
214
|
+
if (value.kind === "counted") {
|
|
215
|
+
return value;
|
|
216
|
+
}
|
|
217
|
+
return method === "slice" ? this.storage(value) : undefined;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* A runtime array as a counted array of all its elements, for a slice of it: one a routine was
|
|
222
|
+
* passed, or a runtime record's field, whose layout says how many elements it stores. Undefined
|
|
223
|
+
* for an array whose elements are each known, which a slice reads one by one.
|
|
224
|
+
*/
|
|
225
|
+
private storage(value: Value): Counted | undefined {
|
|
226
|
+
if (
|
|
227
|
+
value.kind !== "code" ||
|
|
228
|
+
value.length !== undefined ||
|
|
229
|
+
value.layout === undefined
|
|
230
|
+
) {
|
|
231
|
+
return undefined;
|
|
232
|
+
}
|
|
233
|
+
const stored = storedArray(value.layout);
|
|
234
|
+
if (!stored) {
|
|
235
|
+
return undefined;
|
|
236
|
+
}
|
|
237
|
+
const { bound } = stored;
|
|
238
|
+
const declared = value.declared && this.model.elementType(value.declared);
|
|
239
|
+
return {
|
|
240
|
+
kind: "counted",
|
|
241
|
+
source: {
|
|
242
|
+
kind: "array",
|
|
243
|
+
text: value.text,
|
|
244
|
+
layout: value.layout,
|
|
245
|
+
bound,
|
|
246
|
+
element: (index) => ({
|
|
247
|
+
kind: "code",
|
|
248
|
+
text: mapped`${value.text}[${index}]`,
|
|
249
|
+
declared,
|
|
250
|
+
place: value.place,
|
|
251
|
+
iec: value.elementIec ?? stored.iec,
|
|
252
|
+
copyOf: value.copyOf,
|
|
253
|
+
}),
|
|
254
|
+
snapshot: false,
|
|
255
|
+
},
|
|
256
|
+
start: constant(0),
|
|
257
|
+
end: constant(bound),
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** A counted array's `length`: how many elements it has now. */
|
|
262
|
+
member(counted: Counted, name: string, at: ts.Node): Value {
|
|
263
|
+
if (name !== "length") {
|
|
264
|
+
throw new SpecializeError(
|
|
265
|
+
at,
|
|
266
|
+
`${name} cannot be read from an array whose length is decided at run time.`,
|
|
267
|
+
);
|
|
268
|
+
}
|
|
269
|
+
return this.difference(counted.end, counted.start);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* `array[index]` on a counted array. Past its end JavaScript reads undefined: where the type allows
|
|
274
|
+
* undefined that is what is read, and elsewhere the element type's empty value, which a snapshot's
|
|
275
|
+
* unused slots hold.
|
|
276
|
+
*/
|
|
277
|
+
element(counted: Counted, index: Value, at: ts.Node, frame: Frame): Value {
|
|
278
|
+
const { source } = counted;
|
|
279
|
+
if (index.kind !== "const" && index.kind !== "code") {
|
|
280
|
+
throw new SpecializeError(at, "Index an array with a number.");
|
|
281
|
+
}
|
|
282
|
+
const offset = known(index);
|
|
283
|
+
if (index.kind === "const" && offset === undefined) {
|
|
284
|
+
throw new SpecializeError(at, "Index an array with a number.");
|
|
285
|
+
}
|
|
286
|
+
if (offset !== undefined && offset < 0) {
|
|
287
|
+
return constant(undefined);
|
|
288
|
+
}
|
|
289
|
+
const position = this.sum(counted.start, index);
|
|
290
|
+
const fixed = known(position);
|
|
291
|
+
const inside = all([
|
|
292
|
+
this.compare(constant(0), "<=", index),
|
|
293
|
+
this.compare(position, "<", counted.end),
|
|
294
|
+
]);
|
|
295
|
+
if (inside === false) {
|
|
296
|
+
return constant(undefined);
|
|
297
|
+
}
|
|
298
|
+
const item = this.stored(source, position, fixed, at);
|
|
299
|
+
if (item === undefined) {
|
|
300
|
+
return constant(undefined);
|
|
301
|
+
}
|
|
302
|
+
if (inside === true) {
|
|
303
|
+
return item;
|
|
304
|
+
}
|
|
305
|
+
if (item.kind === "choice") {
|
|
306
|
+
// A reference has an id for undefined, whatever the element's type says.
|
|
307
|
+
return {
|
|
308
|
+
...item,
|
|
309
|
+
index: mapped`(${inside} ? ${item.index} : -1)`,
|
|
310
|
+
optional: true,
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
if (item.kind !== "code") {
|
|
314
|
+
throw new SpecializeError(
|
|
315
|
+
at,
|
|
316
|
+
"Index the array the slice was taken from: whether the slice has this element is decided at run time.",
|
|
317
|
+
);
|
|
318
|
+
}
|
|
319
|
+
// Past the end of a whole snapshot the slot was never stored into, so it reads as empty already.
|
|
320
|
+
if (
|
|
321
|
+
source.kind === "array" &&
|
|
322
|
+
source.filled &&
|
|
323
|
+
sameNumber(source.filled, counted.end)
|
|
324
|
+
) {
|
|
325
|
+
return item;
|
|
326
|
+
}
|
|
327
|
+
const declared = this.checker.getTypeAtLocation(at);
|
|
328
|
+
const optional = this.checker.getNonNullableType(declared) !== declared;
|
|
329
|
+
const empty = optional
|
|
330
|
+
? this.dialect.assignmentText(constant(undefined), declared)
|
|
331
|
+
: this.initializers.defaultOf(declared);
|
|
332
|
+
const result = frame.emitter.temporary();
|
|
333
|
+
frame.emitter.line(
|
|
334
|
+
mapped`let ${result}: ${this.expressions.localType(declared)} = ${empty};`,
|
|
335
|
+
);
|
|
336
|
+
frame.emitter.line(
|
|
337
|
+
mapped`if (${inside}) { ${result} = ${this.dialect.assignmentText(item, declared)}; }`,
|
|
338
|
+
);
|
|
339
|
+
return {
|
|
340
|
+
kind: "code",
|
|
341
|
+
text: result,
|
|
342
|
+
declared,
|
|
343
|
+
place: true,
|
|
344
|
+
copyOf: copiedFrom([item], "slice"),
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/** A for…of over a counted array, or a method that reads each of its elements. */
|
|
349
|
+
over(counted: Counted): Traversal {
|
|
350
|
+
const { source, start, end } = counted;
|
|
351
|
+
if (source.kind === "items") {
|
|
352
|
+
return this.overItems(counted, source.items);
|
|
353
|
+
}
|
|
354
|
+
const first = known(start);
|
|
355
|
+
const last = known(end);
|
|
356
|
+
return {
|
|
357
|
+
indexed: true,
|
|
358
|
+
run: (frame, visit) => {
|
|
359
|
+
const whole = frame.emitter.local("tsplcEach");
|
|
360
|
+
const counter = frame.emitter.local("tsplcIndex");
|
|
361
|
+
// The counter never passes the array's bound, which is what proves each index in range.
|
|
362
|
+
const stop =
|
|
363
|
+
last === undefined ? source.bound : Math.min(last, source.bound);
|
|
364
|
+
frame.emitter.open(
|
|
365
|
+
`${whole}: for (let ${counter}: number = ${first ?? 0}; ${counter} < ${stop}; ${counter}++) {`,
|
|
366
|
+
);
|
|
367
|
+
if (last === undefined) {
|
|
368
|
+
frame.emitter.line(
|
|
369
|
+
mapped`if (${counter} >= ${this.text(end)}) { break ${whole}; }`,
|
|
370
|
+
);
|
|
371
|
+
}
|
|
372
|
+
if (first === undefined) {
|
|
373
|
+
frame.emitter.open(mapped`if (${counter} >= ${this.text(start)}) {`);
|
|
374
|
+
}
|
|
375
|
+
const label = frame.emitter.local("tsplcStep");
|
|
376
|
+
frame.emitter.open(`${label}: {`);
|
|
377
|
+
this.looping(source.bound, () =>
|
|
378
|
+
visit({
|
|
379
|
+
value: source.element(counter),
|
|
380
|
+
index: this.difference(this.number(counter), start),
|
|
381
|
+
whole,
|
|
382
|
+
label,
|
|
383
|
+
repeats: source.bound,
|
|
384
|
+
}),
|
|
385
|
+
);
|
|
386
|
+
frame.emitter.close();
|
|
387
|
+
if (first === undefined) {
|
|
388
|
+
frame.emitter.close();
|
|
389
|
+
}
|
|
390
|
+
frame.emitter.close();
|
|
391
|
+
},
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* Whether evaluating the expression runs a traversal as statements, outside functions it declares.
|
|
397
|
+
* JavaScript evaluates the right of `&&`, `||`, `??` and a conditional's branches only when it
|
|
398
|
+
* needs them, so one that does this is written inside the branch that needs it.
|
|
399
|
+
*/
|
|
400
|
+
traverses(node: ts.Node, frame: Frame): boolean {
|
|
401
|
+
if (ts.isFunctionLike(node)) {
|
|
402
|
+
return false;
|
|
403
|
+
}
|
|
404
|
+
if (ts.isCallExpression(node) && this.traversing(node, frame)) {
|
|
405
|
+
return true;
|
|
406
|
+
}
|
|
407
|
+
return (
|
|
408
|
+
ts.forEachChild(node, (child) => this.traverses(child, frame)) ?? false
|
|
409
|
+
);
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/**
|
|
413
|
+
* A counted array passed to a routine: the routine takes its local array and each bound decided
|
|
414
|
+
* at run time as parameters of its own, as `lift` makes them.
|
|
415
|
+
*/
|
|
416
|
+
lifted(
|
|
417
|
+
counted: Counted,
|
|
418
|
+
base: string,
|
|
419
|
+
frame: Frame,
|
|
420
|
+
parameters: string[],
|
|
421
|
+
runtimeArgs: (string | Mapped)[],
|
|
422
|
+
lift: (value: Value, name: string) => Value,
|
|
423
|
+
): Value {
|
|
424
|
+
const { source } = counted;
|
|
425
|
+
const start = lift(counted.start, `${base}_start`);
|
|
426
|
+
const end = lift(counted.end, `${base}_end`);
|
|
427
|
+
if (source.kind === "items") {
|
|
428
|
+
return {
|
|
429
|
+
kind: "counted",
|
|
430
|
+
source: {
|
|
431
|
+
kind: "items",
|
|
432
|
+
items: source.items.map((item, index) =>
|
|
433
|
+
lift(item, `${base}_${index}`),
|
|
434
|
+
),
|
|
435
|
+
},
|
|
436
|
+
start,
|
|
437
|
+
end,
|
|
438
|
+
};
|
|
439
|
+
}
|
|
440
|
+
const local = frame.emitter.local(base);
|
|
441
|
+
parameters.push(`${local}: ${source.layout}`);
|
|
442
|
+
runtimeArgs.push(source.text);
|
|
443
|
+
return {
|
|
444
|
+
kind: "counted",
|
|
445
|
+
source: {
|
|
446
|
+
...source,
|
|
447
|
+
text: local,
|
|
448
|
+
element: (index) => reread(source.element(index), local, index),
|
|
449
|
+
// The routine is passed the end as it is now, which a count it never saw can't be compared with.
|
|
450
|
+
filled: undefined,
|
|
451
|
+
},
|
|
452
|
+
start,
|
|
453
|
+
end,
|
|
454
|
+
};
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
private get generators(): GeneratorRunner {
|
|
458
|
+
if (!this.runner) {
|
|
459
|
+
throw new Error("Nothing runs generators yet.");
|
|
460
|
+
}
|
|
461
|
+
return this.runner;
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/** `iterator.name(…)`, a call to one of JavaScript's iterator helpers. */
|
|
465
|
+
private helper(
|
|
466
|
+
node: ts.Expression,
|
|
467
|
+
): { name: string; receiver: ts.Expression } | undefined {
|
|
468
|
+
if (
|
|
469
|
+
!ts.isCallExpression(node) ||
|
|
470
|
+
!ts.isPropertyAccessExpression(node.expression)
|
|
471
|
+
) {
|
|
472
|
+
return undefined;
|
|
473
|
+
}
|
|
474
|
+
const receiver = node.expression.expression;
|
|
475
|
+
const type = this.checker.getTypeAtLocation(receiver);
|
|
476
|
+
if (!type.getProperty("next") || !type.getProperty("toArray")) {
|
|
477
|
+
return undefined;
|
|
478
|
+
}
|
|
479
|
+
// The helpers are JavaScript's own, declared by its library; a program's class may share their names.
|
|
480
|
+
const declaration = this.checker.getSymbolAtLocation(node.expression.name)
|
|
481
|
+
?.declarations?.[0];
|
|
482
|
+
if (!declaration?.getSourceFile().isDeclarationFile) {
|
|
483
|
+
return undefined;
|
|
484
|
+
}
|
|
485
|
+
return { name: node.expression.name.text, receiver };
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
private traversing(node: ts.CallExpression, frame: Frame): boolean {
|
|
489
|
+
if (this.helper(node)) {
|
|
490
|
+
return true;
|
|
491
|
+
}
|
|
492
|
+
return (
|
|
493
|
+
ts.isPropertyAccessExpression(node.expression) &&
|
|
494
|
+
node.expression.name.text !== "slice" &&
|
|
495
|
+
this.loopsAtRunTime(node.expression.expression, frame, { sliced: false })
|
|
496
|
+
);
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/**
|
|
500
|
+
* Whether an array's methods loop over it at run time: a snapshot by its name, or a slice of a
|
|
501
|
+
* snapshot or of a runtime array.
|
|
502
|
+
*/
|
|
503
|
+
private loopsAtRunTime(
|
|
504
|
+
node: ts.Expression,
|
|
505
|
+
frame: Frame,
|
|
506
|
+
{ sliced }: { sliced: boolean },
|
|
507
|
+
): boolean {
|
|
508
|
+
const inner = unwrapped(node);
|
|
509
|
+
if (
|
|
510
|
+
ts.isCallExpression(inner) &&
|
|
511
|
+
ts.isPropertyAccessExpression(inner.expression) &&
|
|
512
|
+
inner.expression.name.text === "slice"
|
|
513
|
+
) {
|
|
514
|
+
return this.loopsAtRunTime(inner.expression.expression, frame, {
|
|
515
|
+
sliced: true,
|
|
516
|
+
});
|
|
517
|
+
}
|
|
518
|
+
const value = this.glance(inner, frame, { sliced });
|
|
519
|
+
if (value?.kind === "counted") {
|
|
520
|
+
return value.source.kind === "array";
|
|
521
|
+
}
|
|
522
|
+
return sliced && value !== undefined && this.storage(value) !== undefined;
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
/**
|
|
526
|
+
* What an array expression is, without writing code for it: a local by its name, and a field
|
|
527
|
+
* a slice is taken of by evaluating it and dropping the code. Undefined for anything else.
|
|
528
|
+
*/
|
|
529
|
+
private glance(
|
|
530
|
+
node: ts.Expression,
|
|
531
|
+
frame: Frame,
|
|
532
|
+
{ sliced }: { sliced: boolean },
|
|
533
|
+
): Value | undefined {
|
|
534
|
+
if (ts.isIdentifier(node)) {
|
|
535
|
+
const symbol = this.checker.getSymbolAtLocation(node);
|
|
536
|
+
return symbol && frame.env.get(symbol);
|
|
537
|
+
}
|
|
538
|
+
if (!sliced || !ts.isPropertyAccessExpression(node)) {
|
|
539
|
+
return undefined;
|
|
540
|
+
}
|
|
541
|
+
try {
|
|
542
|
+
return this.expressions.expression(node, {
|
|
543
|
+
...frame,
|
|
544
|
+
emitter: new Emitter(node),
|
|
545
|
+
});
|
|
546
|
+
} catch (cause) {
|
|
547
|
+
if (cause instanceof SpecializeError) {
|
|
548
|
+
return undefined;
|
|
549
|
+
}
|
|
550
|
+
throw cause;
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
/** A generator call, read through the helpers that give another iterator. */
|
|
555
|
+
private pipeline(node: ts.Expression, frame: Frame): Traversal {
|
|
556
|
+
const inner = unwrapped(node);
|
|
557
|
+
const generator = this.expressions.generator(inner, frame);
|
|
558
|
+
if (generator) {
|
|
559
|
+
return this.generated(generator, inner);
|
|
560
|
+
}
|
|
561
|
+
const helper = this.helper(inner);
|
|
562
|
+
if (!helper || !ts.isCallExpression(inner)) {
|
|
563
|
+
throw new SpecializeError(
|
|
564
|
+
node,
|
|
565
|
+
"A generator runs in place: call it where a for…of or an iterator helper reads it.",
|
|
566
|
+
);
|
|
567
|
+
}
|
|
568
|
+
const source = this.pipeline(helper.receiver, frame);
|
|
569
|
+
switch (helper.name) {
|
|
570
|
+
case "map":
|
|
571
|
+
return this.mapped(source, this.callback(inner, frame), inner);
|
|
572
|
+
case "filter":
|
|
573
|
+
return this.filtered(source, this.callback(inner, frame), inner);
|
|
574
|
+
case "take":
|
|
575
|
+
return this.taken(source, this.amount(inner, frame));
|
|
576
|
+
case "drop":
|
|
577
|
+
return this.dropped(source, this.amount(inner, frame));
|
|
578
|
+
default:
|
|
579
|
+
throw new SpecializeError(
|
|
580
|
+
inner,
|
|
581
|
+
`${helper.name} gives no iterator the PLC can run in place; use map, filter, take or drop.`,
|
|
582
|
+
);
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
private generated(generator: GeneratorCall, at: ts.Node): Traversal {
|
|
587
|
+
return {
|
|
588
|
+
run: (frame, visit) => {
|
|
589
|
+
const depth = this.loops.length;
|
|
590
|
+
this.generators.run(generator, frame, at, (value, jumps) =>
|
|
591
|
+
visit({ ...jumps, value, repeats: this.repeats(depth) }),
|
|
592
|
+
);
|
|
593
|
+
},
|
|
594
|
+
};
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
/** How many times code written now can run, for the loops entered since `depth`. */
|
|
598
|
+
private repeats(depth: number): number | undefined {
|
|
599
|
+
return this.loops
|
|
600
|
+
.slice(depth)
|
|
601
|
+
.reduce<number | undefined>(
|
|
602
|
+
(product, runs) =>
|
|
603
|
+
product === undefined || runs === undefined
|
|
604
|
+
? undefined
|
|
605
|
+
: product * runs,
|
|
606
|
+
1,
|
|
607
|
+
);
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
private mapped(
|
|
611
|
+
source: Traversal,
|
|
612
|
+
callback: Value,
|
|
613
|
+
at: ts.CallExpression,
|
|
614
|
+
): Traversal {
|
|
615
|
+
return {
|
|
616
|
+
limit: source.limit,
|
|
617
|
+
run: (frame, visit) => {
|
|
618
|
+
const index = this.indexer(source, callback, 1, frame);
|
|
619
|
+
source.run(frame, (element) =>
|
|
620
|
+
visit({
|
|
621
|
+
...element,
|
|
622
|
+
value: this.expressions.invoke(
|
|
623
|
+
callback,
|
|
624
|
+
[element.value, index(element)],
|
|
625
|
+
at,
|
|
626
|
+
frame,
|
|
627
|
+
),
|
|
628
|
+
index: undefined,
|
|
629
|
+
}),
|
|
630
|
+
);
|
|
631
|
+
},
|
|
632
|
+
};
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
private filtered(
|
|
636
|
+
source: Traversal,
|
|
637
|
+
callback: Value,
|
|
638
|
+
at: ts.CallExpression,
|
|
639
|
+
): Traversal {
|
|
640
|
+
return {
|
|
641
|
+
limit: source.limit,
|
|
642
|
+
run: (frame, visit) => {
|
|
643
|
+
const index = this.indexer(source, callback, 1, frame);
|
|
644
|
+
source.run(frame, (element) => {
|
|
645
|
+
// The test and whatever reads the element next both read it, so it is read once.
|
|
646
|
+
const value = this.once(element.value, frame);
|
|
647
|
+
const test = this.expressions.invoke(
|
|
648
|
+
callback,
|
|
649
|
+
[value, index(element)],
|
|
650
|
+
at,
|
|
651
|
+
frame,
|
|
652
|
+
);
|
|
653
|
+
const passed = truth(test);
|
|
654
|
+
if (passed === false) {
|
|
655
|
+
return;
|
|
656
|
+
}
|
|
657
|
+
if (passed === undefined) {
|
|
658
|
+
frame.emitter.open(mapped`if (${this.condition(test, at)}) {`);
|
|
659
|
+
}
|
|
660
|
+
visit({ ...element, value, index: undefined });
|
|
661
|
+
if (passed === undefined) {
|
|
662
|
+
frame.emitter.close();
|
|
663
|
+
}
|
|
664
|
+
});
|
|
665
|
+
},
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
/** `take(limit)` ends the generator once it has passed on `limit` elements, before the generator runs on to its next yield. */
|
|
670
|
+
private taken(source: Traversal, limit: Value): Traversal {
|
|
671
|
+
const fixed = known(limit);
|
|
672
|
+
return {
|
|
673
|
+
limit: fewest(source.limit, fixed),
|
|
674
|
+
run: (frame, visit) => {
|
|
675
|
+
if (fixed !== undefined && fixed <= 0) {
|
|
676
|
+
return;
|
|
677
|
+
}
|
|
678
|
+
const taken = frame.emitter.temporary();
|
|
679
|
+
frame.emitter.line(`let ${taken}: number = 0;`);
|
|
680
|
+
if (fixed === undefined) {
|
|
681
|
+
frame.emitter.open(mapped`if (${this.text(limit)} > 0) {`);
|
|
682
|
+
}
|
|
683
|
+
source.run(frame, (element) => {
|
|
684
|
+
const label = frame.emitter.local("tsplcStep");
|
|
685
|
+
frame.emitter.line(`${taken} = ${taken} + 1;`);
|
|
686
|
+
// A continue in the code reading the element must still reach the count below.
|
|
687
|
+
frame.emitter.open(`${label}: {`);
|
|
688
|
+
visit({ ...element, label });
|
|
689
|
+
frame.emitter.close();
|
|
690
|
+
frame.emitter.line(
|
|
691
|
+
mapped`if (${taken} >= ${this.text(limit)}) { break ${element.whole}; }`,
|
|
692
|
+
);
|
|
693
|
+
});
|
|
694
|
+
if (fixed === undefined) {
|
|
695
|
+
frame.emitter.close();
|
|
696
|
+
}
|
|
697
|
+
},
|
|
698
|
+
};
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
private dropped(source: Traversal, limit: Value): Traversal {
|
|
702
|
+
const fixed = known(limit);
|
|
703
|
+
if (fixed !== undefined && fixed <= 0) {
|
|
704
|
+
return source;
|
|
705
|
+
}
|
|
706
|
+
return {
|
|
707
|
+
limit: source.limit,
|
|
708
|
+
run: (frame, visit) => {
|
|
709
|
+
const dropped = frame.emitter.temporary();
|
|
710
|
+
frame.emitter.line(`let ${dropped}: number = 0;`);
|
|
711
|
+
source.run(frame, (element) => {
|
|
712
|
+
frame.emitter.line(
|
|
713
|
+
mapped`if (${dropped} < ${this.text(limit)}) { ${dropped} = ${dropped} + 1; break ${element.label}; }`,
|
|
714
|
+
);
|
|
715
|
+
visit({ ...element, index: undefined });
|
|
716
|
+
});
|
|
717
|
+
},
|
|
718
|
+
};
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
/** A helper or array method that reads a traversal to its result. */
|
|
722
|
+
private terminal(
|
|
723
|
+
name: string,
|
|
724
|
+
traversal: Traversal,
|
|
725
|
+
node: ts.CallExpression,
|
|
726
|
+
frame: Frame,
|
|
727
|
+
): Value {
|
|
728
|
+
switch (name) {
|
|
729
|
+
case "some":
|
|
730
|
+
case "every": {
|
|
731
|
+
const callback = this.callback(node, frame);
|
|
732
|
+
const index = this.indexer(traversal, callback, 1, frame);
|
|
733
|
+
return this.decided(
|
|
734
|
+
traversal,
|
|
735
|
+
node,
|
|
736
|
+
frame,
|
|
737
|
+
{ some: name === "some" },
|
|
738
|
+
(element) =>
|
|
739
|
+
this.expressions.invoke(
|
|
740
|
+
callback,
|
|
741
|
+
[element.value, index(element)],
|
|
742
|
+
node,
|
|
743
|
+
frame,
|
|
744
|
+
),
|
|
745
|
+
);
|
|
746
|
+
}
|
|
747
|
+
case "includes": {
|
|
748
|
+
const target = this.target(node, frame);
|
|
749
|
+
return this.decided(traversal, node, frame, { some: true }, (element) =>
|
|
750
|
+
this.expressions.equality(element.value, target, { negate: false }),
|
|
751
|
+
);
|
|
752
|
+
}
|
|
753
|
+
case "find":
|
|
754
|
+
return this.find(traversal, node, frame);
|
|
755
|
+
case "findIndex": {
|
|
756
|
+
const callback = this.callback(node, frame);
|
|
757
|
+
return this.position(traversal, node, frame, (element) =>
|
|
758
|
+
this.expressions.invoke(
|
|
759
|
+
callback,
|
|
760
|
+
[element.value, element.index ?? constant(undefined)],
|
|
761
|
+
node,
|
|
762
|
+
frame,
|
|
763
|
+
),
|
|
764
|
+
);
|
|
765
|
+
}
|
|
766
|
+
case "indexOf": {
|
|
767
|
+
const target = this.target(node, frame);
|
|
768
|
+
return this.position(traversal, node, frame, (element) =>
|
|
769
|
+
this.expressions.equality(element.value, target, { negate: false }),
|
|
770
|
+
);
|
|
771
|
+
}
|
|
772
|
+
case "forEach": {
|
|
773
|
+
const callback = this.callback(node, frame);
|
|
774
|
+
const index = this.indexer(traversal, callback, 1, frame);
|
|
775
|
+
traversal.run(frame, (element) => {
|
|
776
|
+
const result = this.expressions.invoke(
|
|
777
|
+
callback,
|
|
778
|
+
[element.value, index(element)],
|
|
779
|
+
node,
|
|
780
|
+
frame,
|
|
781
|
+
);
|
|
782
|
+
if (result.kind === "code") {
|
|
783
|
+
frame.emitter.line(mapped`${result.text};`);
|
|
784
|
+
}
|
|
785
|
+
});
|
|
786
|
+
return constant(undefined);
|
|
787
|
+
}
|
|
788
|
+
case "reduce":
|
|
789
|
+
return this.reduce(traversal, node, frame);
|
|
790
|
+
case "toArray":
|
|
791
|
+
return this.snapshot(traversal, node, frame);
|
|
792
|
+
default:
|
|
793
|
+
throw new SpecializeError(
|
|
794
|
+
node,
|
|
795
|
+
`${name} is not supported on an iterator, or an array whose length is decided at run time.`,
|
|
796
|
+
);
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
/** `some` and `every`: the traversal ends at the first element whose test decides the result. */
|
|
801
|
+
private decided(
|
|
802
|
+
traversal: Traversal,
|
|
803
|
+
node: ts.CallExpression,
|
|
804
|
+
frame: Frame,
|
|
805
|
+
{ some }: { some: boolean },
|
|
806
|
+
test: (element: Visited) => Value,
|
|
807
|
+
): Value {
|
|
808
|
+
const result = frame.emitter.temporary();
|
|
809
|
+
frame.emitter.line(`let ${result}: boolean = ${!some};`);
|
|
810
|
+
traversal.run(frame, (element) => {
|
|
811
|
+
const tested = test(element);
|
|
812
|
+
const passed = truth(tested);
|
|
813
|
+
if (passed === undefined) {
|
|
814
|
+
const condition = this.condition(tested, node);
|
|
815
|
+
frame.emitter.line(
|
|
816
|
+
mapped`if (${some ? condition : mapped`!(${condition})`}) { ${result} = ${String(some)}; break ${element.whole}; }`,
|
|
817
|
+
);
|
|
818
|
+
return;
|
|
819
|
+
}
|
|
820
|
+
if (passed === some) {
|
|
821
|
+
frame.emitter.line(`${result} = ${some};`);
|
|
822
|
+
frame.emitter.line(`break ${element.whole};`);
|
|
823
|
+
}
|
|
824
|
+
});
|
|
825
|
+
return {
|
|
826
|
+
kind: "code",
|
|
827
|
+
text: result,
|
|
828
|
+
declared: this.checker.getBooleanType(),
|
|
829
|
+
place: true,
|
|
830
|
+
};
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
/**
|
|
834
|
+
* `find`: the first element whose test passes, or undefined; the traversal ends there. Among
|
|
835
|
+
* objects setup built it is a reference to the one that passed, and otherwise a copy of the value.
|
|
836
|
+
*/
|
|
837
|
+
private find(
|
|
838
|
+
traversal: Traversal,
|
|
839
|
+
node: ts.CallExpression,
|
|
840
|
+
frame: Frame,
|
|
841
|
+
): Value {
|
|
842
|
+
const callback = this.callback(node, frame);
|
|
843
|
+
const index = this.indexer(traversal, callback, 1, frame);
|
|
844
|
+
const declared = this.checker.getTypeAtLocation(node);
|
|
845
|
+
const values = this.trial(traversal, frame).map(({ value }) => value);
|
|
846
|
+
const referred = references(values);
|
|
847
|
+
const slot = referred
|
|
848
|
+
? this.referenceSlot({ ...referred, optional: true }, node)
|
|
849
|
+
: this.optionalSlot(values, declared, node);
|
|
850
|
+
const result = frame.emitter.temporary();
|
|
851
|
+
frame.emitter.line(mapped`let ${result}: ${slot.type} = ${slot.empty()};`);
|
|
852
|
+
traversal.run(frame, (visited) => {
|
|
853
|
+
const value = this.once(visited.value, frame);
|
|
854
|
+
const test = this.expressions.invoke(
|
|
855
|
+
callback,
|
|
856
|
+
[value, index(visited)],
|
|
857
|
+
node,
|
|
858
|
+
frame,
|
|
859
|
+
);
|
|
860
|
+
const passed = truth(test);
|
|
861
|
+
if (passed === false) {
|
|
862
|
+
return;
|
|
863
|
+
}
|
|
864
|
+
if (passed === undefined) {
|
|
865
|
+
frame.emitter.open(mapped`if (${this.condition(test, node)}) {`);
|
|
866
|
+
}
|
|
867
|
+
frame.emitter.line(mapped`${result} = ${slot.store(value)};`);
|
|
868
|
+
frame.emitter.line(`break ${visited.whole};`);
|
|
869
|
+
if (passed === undefined) {
|
|
870
|
+
frame.emitter.close();
|
|
871
|
+
}
|
|
872
|
+
});
|
|
873
|
+
return slot.read(result);
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
/** `findIndex` and `indexOf`: the index of the first element whose test passes, or -1. */
|
|
877
|
+
private position(
|
|
878
|
+
traversal: Traversal,
|
|
879
|
+
node: ts.CallExpression,
|
|
880
|
+
frame: Frame,
|
|
881
|
+
test: (element: Visited) => Value,
|
|
882
|
+
): Value {
|
|
883
|
+
const result = frame.emitter.temporary();
|
|
884
|
+
frame.emitter.line(`let ${result}: number = -1;`);
|
|
885
|
+
traversal.run(frame, (element) => {
|
|
886
|
+
if (!element.index) {
|
|
887
|
+
throw new SpecializeError(
|
|
888
|
+
node,
|
|
889
|
+
"Only an array's elements have indexes.",
|
|
890
|
+
);
|
|
891
|
+
}
|
|
892
|
+
const tested = test(element);
|
|
893
|
+
const passed = truth(tested);
|
|
894
|
+
if (passed === false) {
|
|
895
|
+
return;
|
|
896
|
+
}
|
|
897
|
+
const found = mapped`${result} = ${this.text(element.index)}; break ${element.whole};`;
|
|
898
|
+
frame.emitter.line(
|
|
899
|
+
passed === undefined
|
|
900
|
+
? mapped`if (${this.condition(tested, node)}) { ${found} }`
|
|
901
|
+
: found,
|
|
902
|
+
);
|
|
903
|
+
});
|
|
904
|
+
return {
|
|
905
|
+
kind: "code",
|
|
906
|
+
text: result,
|
|
907
|
+
declared: this.checker.getNumberType(),
|
|
908
|
+
place: true,
|
|
909
|
+
};
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
/** `reduce(step, initial)`: the result so far is a local each element's step stores into. */
|
|
913
|
+
private reduce(
|
|
914
|
+
traversal: Traversal,
|
|
915
|
+
node: ts.CallExpression,
|
|
916
|
+
frame: Frame,
|
|
917
|
+
): Value {
|
|
918
|
+
const callback = this.callback(node, frame);
|
|
919
|
+
const [, initialNode] = node.arguments;
|
|
920
|
+
if (!initialNode) {
|
|
921
|
+
throw new SpecializeError(
|
|
922
|
+
node,
|
|
923
|
+
"reduce needs an initial value here: whether there is a first element is decided at run time.",
|
|
924
|
+
);
|
|
925
|
+
}
|
|
926
|
+
const declared = this.checker.getTypeAtLocation(node);
|
|
927
|
+
const initial = this.expressions.expression(initialNode, frame, declared);
|
|
928
|
+
const total = frame.emitter.temporary();
|
|
929
|
+
frame.emitter.line(
|
|
930
|
+
mapped`let ${total}: ${this.expressions.localType(declared)} = ${this.dialect.assignmentText(initial, declared)};`,
|
|
931
|
+
);
|
|
932
|
+
const accumulated: Value = {
|
|
933
|
+
kind: "code",
|
|
934
|
+
text: total,
|
|
935
|
+
declared,
|
|
936
|
+
place: true,
|
|
937
|
+
};
|
|
938
|
+
const index = this.indexer(traversal, callback, 2, frame);
|
|
939
|
+
traversal.run(frame, (element) => {
|
|
940
|
+
const next = this.expressions.invoke(
|
|
941
|
+
callback,
|
|
942
|
+
[accumulated, element.value, index(element)],
|
|
943
|
+
node,
|
|
944
|
+
frame,
|
|
945
|
+
);
|
|
946
|
+
frame.emitter.line(
|
|
947
|
+
mapped`${total} = ${this.dialect.assignmentText(next, declared)};`,
|
|
948
|
+
);
|
|
949
|
+
});
|
|
950
|
+
return accumulated;
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
/**
|
|
954
|
+
* `toArray()`: a local array filled with what the traversal passes on, and how many it did. The
|
|
955
|
+
* traversal is written out once without keeping it, to learn what it yields and how often, since
|
|
956
|
+
* the array is declared before the code that fills it.
|
|
957
|
+
*/
|
|
958
|
+
private snapshot(
|
|
959
|
+
traversal: Traversal,
|
|
960
|
+
node: ts.CallExpression,
|
|
961
|
+
frame: Frame,
|
|
962
|
+
): Value {
|
|
963
|
+
const trial = this.trial(traversal, frame);
|
|
964
|
+
const unbounded = trial.some(({ repeats }) => repeats === undefined);
|
|
965
|
+
if (unbounded && traversal.limit === undefined) {
|
|
966
|
+
throw new SpecializeError(
|
|
967
|
+
node,
|
|
968
|
+
"toArray needs the most the generator can yield, to size its array: a yield here is in a loop with no counted bound. Yield from a counted for loop, or from a loop over what setup built.",
|
|
969
|
+
);
|
|
970
|
+
}
|
|
971
|
+
const yielded = unbounded
|
|
972
|
+
? Number.POSITIVE_INFINITY
|
|
973
|
+
: trial.reduce((total, { repeats }) => total + (repeats ?? 0), 0);
|
|
974
|
+
const bound = Math.min(yielded, traversal.limit ?? yielded);
|
|
975
|
+
const size = Math.max(bound, 1);
|
|
976
|
+
const element = this.model.elementType(
|
|
977
|
+
this.checker.getTypeAtLocation(node),
|
|
978
|
+
);
|
|
979
|
+
const values = trial.map(({ value }) => value);
|
|
980
|
+
const referred = references(values);
|
|
981
|
+
const slot = referred
|
|
982
|
+
? this.referenceSlot(referred, node)
|
|
983
|
+
: this.valueSlot(values, element, node);
|
|
984
|
+
const array = frame.emitter.temporary();
|
|
985
|
+
const count = frame.emitter.temporary();
|
|
986
|
+
const layout = `FixedArray<${slot.type}, ${size}>`;
|
|
987
|
+
frame.emitter.line(`let ${array}: ${layout} = defaultValue<${layout}>();`);
|
|
988
|
+
// Unsigned, so its remainder is proved an index of the array; the count itself never reaches the bound.
|
|
989
|
+
frame.emitter.line(`let ${count}: UDINT = 0;`);
|
|
990
|
+
traversal.run(frame, ({ value }) => {
|
|
991
|
+
frame.emitter.line(
|
|
992
|
+
mapped`${array}[${count} % ${size}] = ${slot.store(value)};`,
|
|
993
|
+
);
|
|
994
|
+
frame.emitter.line(`${count} = ${count} + 1;`);
|
|
995
|
+
});
|
|
996
|
+
const length = frame.emitter.temporary();
|
|
997
|
+
frame.emitter.line(
|
|
998
|
+
mapped`const ${length}: number = ${this.dialect.assignmentText({ kind: "code", text: count, iec: "UDINT" }, this.checker.getNumberType())};`,
|
|
999
|
+
);
|
|
1000
|
+
return {
|
|
1001
|
+
kind: "counted",
|
|
1002
|
+
source: {
|
|
1003
|
+
kind: "array",
|
|
1004
|
+
text: array,
|
|
1005
|
+
layout,
|
|
1006
|
+
bound,
|
|
1007
|
+
snapshot: true,
|
|
1008
|
+
filled: this.number(length),
|
|
1009
|
+
element: (index) => slot.read(mapped`${array}[${index}]`),
|
|
1010
|
+
},
|
|
1011
|
+
start: constant(0),
|
|
1012
|
+
end: this.number(length),
|
|
1013
|
+
};
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
/** What a traversal passes on, each with how often, from writing it out without keeping the code. */
|
|
1017
|
+
private trial(traversal: Traversal, frame: Frame): Visited[] {
|
|
1018
|
+
const visits: Visited[] = [];
|
|
1019
|
+
traversal.run(
|
|
1020
|
+
{ ...frame, emitter: new Emitter(frame.emitter.origin) },
|
|
1021
|
+
(element) => {
|
|
1022
|
+
visits.push(element);
|
|
1023
|
+
},
|
|
1024
|
+
);
|
|
1025
|
+
return visits;
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
/** A local that keeps a reference to one of the objects setup built: the object's id, so it is still that object. */
|
|
1029
|
+
private referenceSlot(
|
|
1030
|
+
{ options, optional }: { options: readonly ModelNode[]; optional: boolean },
|
|
1031
|
+
node: ts.CallExpression,
|
|
1032
|
+
): Slot {
|
|
1033
|
+
return {
|
|
1034
|
+
type: referenceLayout,
|
|
1035
|
+
empty: () => "-1",
|
|
1036
|
+
store: (value) => {
|
|
1037
|
+
const index = referenceIndex(value);
|
|
1038
|
+
if (index === undefined) {
|
|
1039
|
+
throw new SpecializeError(
|
|
1040
|
+
node,
|
|
1041
|
+
"This keeps references to objects setup built, and one of its values is none.",
|
|
1042
|
+
);
|
|
1043
|
+
}
|
|
1044
|
+
return index;
|
|
1045
|
+
},
|
|
1046
|
+
read: (place) => ({ kind: "choice", options, index: place, optional }),
|
|
1047
|
+
};
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
/** A local that keeps a copy of a value, as JavaScript copies a number and the PLC copies a record. */
|
|
1051
|
+
private valueSlot(
|
|
1052
|
+
values: readonly Value[],
|
|
1053
|
+
element: ts.Type | undefined,
|
|
1054
|
+
node: ts.CallExpression,
|
|
1055
|
+
): Slot {
|
|
1056
|
+
if (!element) {
|
|
1057
|
+
throw new SpecializeError(node, "toArray needs an element type.");
|
|
1058
|
+
}
|
|
1059
|
+
return {
|
|
1060
|
+
type: this.expressions.localType(element),
|
|
1061
|
+
empty: () => `defaultValue<${this.expressions.localType(element)}>()`,
|
|
1062
|
+
store: (value) =>
|
|
1063
|
+
this.dialect.assignmentText(copyable(value, node), element),
|
|
1064
|
+
read: (place) => ({
|
|
1065
|
+
kind: "code",
|
|
1066
|
+
text: place,
|
|
1067
|
+
declared: element,
|
|
1068
|
+
place: true,
|
|
1069
|
+
copyOf: copiedFrom(values, "toArray"),
|
|
1070
|
+
}),
|
|
1071
|
+
};
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
/** A local that keeps a copy of a value or undefined, as `find`'s result is. */
|
|
1075
|
+
private optionalSlot(
|
|
1076
|
+
values: readonly Value[],
|
|
1077
|
+
declared: ts.Type,
|
|
1078
|
+
node: ts.CallExpression,
|
|
1079
|
+
): Slot {
|
|
1080
|
+
const element = this.checker.getNonNullableType(declared);
|
|
1081
|
+
return {
|
|
1082
|
+
type: this.expressions.localType(declared),
|
|
1083
|
+
empty: () => this.dialect.assignmentText(constant(undefined), declared),
|
|
1084
|
+
store: (value) =>
|
|
1085
|
+
this.dialect.wrapDefined(
|
|
1086
|
+
this.dialect.code(copyable(value, node), element),
|
|
1087
|
+
declared,
|
|
1088
|
+
),
|
|
1089
|
+
read: (place) => ({
|
|
1090
|
+
kind: "code",
|
|
1091
|
+
text: place,
|
|
1092
|
+
declared,
|
|
1093
|
+
place: true,
|
|
1094
|
+
copyOf: copiedFrom(values, "find"),
|
|
1095
|
+
}),
|
|
1096
|
+
};
|
|
1097
|
+
}
|
|
1098
|
+
|
|
1099
|
+
/** Elements setup fixed, each read only if its index is in the slice's range. */
|
|
1100
|
+
private overItems(counted: Counted, items: readonly Value[]): Traversal {
|
|
1101
|
+
return {
|
|
1102
|
+
indexed: true,
|
|
1103
|
+
run: (frame, visit) => {
|
|
1104
|
+
const whole = frame.emitter.local("tsplcEach");
|
|
1105
|
+
frame.emitter.open(`${whole}: {`);
|
|
1106
|
+
items.forEach((item, position) => {
|
|
1107
|
+
const inside = this.has(counted, position);
|
|
1108
|
+
if (inside === false) {
|
|
1109
|
+
return;
|
|
1110
|
+
}
|
|
1111
|
+
if (inside !== true) {
|
|
1112
|
+
frame.emitter.open(mapped`if (${inside}) {`);
|
|
1113
|
+
}
|
|
1114
|
+
const label = frame.emitter.local("tsplcStep");
|
|
1115
|
+
frame.emitter.open(`${label}: {`);
|
|
1116
|
+
visit({
|
|
1117
|
+
value: item,
|
|
1118
|
+
index: this.difference(constant(position), counted.start),
|
|
1119
|
+
whole,
|
|
1120
|
+
label,
|
|
1121
|
+
repeats: 1,
|
|
1122
|
+
});
|
|
1123
|
+
frame.emitter.close();
|
|
1124
|
+
if (inside !== true) {
|
|
1125
|
+
frame.emitter.close();
|
|
1126
|
+
}
|
|
1127
|
+
});
|
|
1128
|
+
frame.emitter.close();
|
|
1129
|
+
},
|
|
1130
|
+
};
|
|
1131
|
+
}
|
|
1132
|
+
|
|
1133
|
+
/**
|
|
1134
|
+
* `some`, `every` and `includes` over elements setup fixed, as one expression: each element's
|
|
1135
|
+
* test counts only when its index is in range. An expression needs no statements, so `&&` and
|
|
1136
|
+
* `||` around it skip it as JavaScript does.
|
|
1137
|
+
*/
|
|
1138
|
+
private tested(
|
|
1139
|
+
name: "some" | "every" | "includes",
|
|
1140
|
+
counted: Counted,
|
|
1141
|
+
items: readonly Value[],
|
|
1142
|
+
node: ts.CallExpression,
|
|
1143
|
+
frame: Frame,
|
|
1144
|
+
): Value {
|
|
1145
|
+
const some = name !== "every";
|
|
1146
|
+
const test = this.elementTest(name, node, frame);
|
|
1147
|
+
const terms: (string | Mapped)[] = [];
|
|
1148
|
+
for (const [position, item] of items.entries()) {
|
|
1149
|
+
const inside = this.has(counted, position);
|
|
1150
|
+
if (inside === false) {
|
|
1151
|
+
continue;
|
|
1152
|
+
}
|
|
1153
|
+
const tested = test(
|
|
1154
|
+
item,
|
|
1155
|
+
this.difference(constant(position), counted.start),
|
|
1156
|
+
);
|
|
1157
|
+
const passed = truth(tested);
|
|
1158
|
+
if (passed === !some) {
|
|
1159
|
+
continue;
|
|
1160
|
+
}
|
|
1161
|
+
if (passed === some && inside === true) {
|
|
1162
|
+
return constant(some);
|
|
1163
|
+
}
|
|
1164
|
+
const condition =
|
|
1165
|
+
passed === undefined ? this.condition(tested, node) : undefined;
|
|
1166
|
+
terms.push(this.term(inside, condition, { some }));
|
|
1167
|
+
}
|
|
1168
|
+
if (!terms.length) {
|
|
1169
|
+
return constant(!some);
|
|
1170
|
+
}
|
|
1171
|
+
return {
|
|
1172
|
+
kind: "code",
|
|
1173
|
+
text: mapped`(${joined(terms, some ? " || " : " && ")})`,
|
|
1174
|
+
declared: this.checker.getBooleanType(),
|
|
1175
|
+
};
|
|
1176
|
+
}
|
|
1177
|
+
|
|
1178
|
+
/** One element's part of a `some` or `every`: for `some` in range and passing, for `every` out of range or passing. */
|
|
1179
|
+
private term(
|
|
1180
|
+
inside: true | Mapped,
|
|
1181
|
+
condition: string | Mapped | undefined,
|
|
1182
|
+
{ some }: { some: boolean },
|
|
1183
|
+
): string | Mapped {
|
|
1184
|
+
if (inside === true) {
|
|
1185
|
+
return condition ?? String(some);
|
|
1186
|
+
}
|
|
1187
|
+
if (condition === undefined) {
|
|
1188
|
+
return some ? mapped`(${inside})` : mapped`!(${inside})`;
|
|
1189
|
+
}
|
|
1190
|
+
return some
|
|
1191
|
+
? mapped`(${inside} && ${condition})`
|
|
1192
|
+
: mapped`(!(${inside}) || ${condition})`;
|
|
1193
|
+
}
|
|
1194
|
+
|
|
1195
|
+
private elementTest(
|
|
1196
|
+
name: "some" | "every" | "includes",
|
|
1197
|
+
node: ts.CallExpression,
|
|
1198
|
+
frame: Frame,
|
|
1199
|
+
): (item: Value, index: Value) => Value {
|
|
1200
|
+
if (name === "includes") {
|
|
1201
|
+
const target = this.target(node, frame);
|
|
1202
|
+
return (item) =>
|
|
1203
|
+
this.expressions.equality(item, target, { negate: false });
|
|
1204
|
+
}
|
|
1205
|
+
const callback = this.callback(node, frame);
|
|
1206
|
+
return (item, index) =>
|
|
1207
|
+
this.expressions.invoke(callback, [item, index], node, frame);
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
/** Whether a counted array has the element at a storage index: known now, or a test of its bounds. */
|
|
1211
|
+
private has(counted: Counted, position: number): boolean | Mapped {
|
|
1212
|
+
return all([
|
|
1213
|
+
this.compare(counted.start, "<=", constant(position)),
|
|
1214
|
+
this.compare(constant(position), "<", counted.end),
|
|
1215
|
+
]);
|
|
1216
|
+
}
|
|
1217
|
+
|
|
1218
|
+
/** The element a counted array keeps at a storage index; undefined when the storage ends before it. */
|
|
1219
|
+
private stored(
|
|
1220
|
+
source: Counted["source"],
|
|
1221
|
+
position: Value,
|
|
1222
|
+
fixed: number | undefined,
|
|
1223
|
+
at: ts.Node,
|
|
1224
|
+
): Value | undefined {
|
|
1225
|
+
if (source.kind === "array") {
|
|
1226
|
+
return fixed !== undefined && fixed >= source.bound
|
|
1227
|
+
? undefined
|
|
1228
|
+
: source.element(this.text(position));
|
|
1229
|
+
}
|
|
1230
|
+
if (fixed === undefined) {
|
|
1231
|
+
throw new SpecializeError(
|
|
1232
|
+
at,
|
|
1233
|
+
"Index the array the slice was taken from, or the slice with an index setup fixed.",
|
|
1234
|
+
);
|
|
1235
|
+
}
|
|
1236
|
+
return source.items[fixed];
|
|
1237
|
+
}
|
|
1238
|
+
|
|
1239
|
+
/** The slice of a counted array from `start` to `end`, each counting back from the end when negative, as JavaScript reads them. */
|
|
1240
|
+
private slice(
|
|
1241
|
+
target: Counted,
|
|
1242
|
+
bounds: { start: Value | undefined; end: Value | undefined },
|
|
1243
|
+
node: ts.CallExpression,
|
|
1244
|
+
frame: Frame,
|
|
1245
|
+
): Value {
|
|
1246
|
+
const length = this.kept(this.difference(target.end, target.start), frame);
|
|
1247
|
+
const start = this.bound(bounds.start, node, frame);
|
|
1248
|
+
const end = this.bound(bounds.end, node, frame);
|
|
1249
|
+
const from = this.kept(
|
|
1250
|
+
start ? this.relative(start, length) : constant(0),
|
|
1251
|
+
frame,
|
|
1252
|
+
);
|
|
1253
|
+
const to = this.kept(end ? this.relative(end, length) : length, frame);
|
|
1254
|
+
return {
|
|
1255
|
+
kind: "counted",
|
|
1256
|
+
source: target.source,
|
|
1257
|
+
start: this.kept(this.sum(target.start, from), frame),
|
|
1258
|
+
// A slice that ends before it starts is empty, which an end at its start says.
|
|
1259
|
+
end: this.kept(
|
|
1260
|
+
this.sum(target.start, known(from) === 0 ? to : this.most(to, from)),
|
|
1261
|
+
frame,
|
|
1262
|
+
),
|
|
1263
|
+
};
|
|
1264
|
+
}
|
|
1265
|
+
|
|
1266
|
+
/** A slice bound as a number: known now, or held in a const where the slice is made. */
|
|
1267
|
+
private bound(
|
|
1268
|
+
value: Value | undefined,
|
|
1269
|
+
node: ts.CallExpression,
|
|
1270
|
+
frame: Frame,
|
|
1271
|
+
): Value | undefined {
|
|
1272
|
+
if (!value || (value.kind === "const" && value.value === undefined)) {
|
|
1273
|
+
return undefined;
|
|
1274
|
+
}
|
|
1275
|
+
const fixed = known(value);
|
|
1276
|
+
if (fixed !== undefined) {
|
|
1277
|
+
return constant(Math.trunc(fixed));
|
|
1278
|
+
}
|
|
1279
|
+
if (value.kind !== "code") {
|
|
1280
|
+
throw new SpecializeError(node, "slice needs numbers for its bounds.");
|
|
1281
|
+
}
|
|
1282
|
+
const local = frame.emitter.temporary();
|
|
1283
|
+
frame.emitter.line(
|
|
1284
|
+
mapped`const ${local}: number = ${this.dialect.assignmentText(value, this.checker.getNumberType())};`,
|
|
1285
|
+
);
|
|
1286
|
+
return this.number(local);
|
|
1287
|
+
}
|
|
1288
|
+
|
|
1289
|
+
/** A slice bound as an index from 0 to the length. */
|
|
1290
|
+
private relative(bound: Value, length: Value): Value {
|
|
1291
|
+
const fixed = known(bound);
|
|
1292
|
+
if (fixed === 0) {
|
|
1293
|
+
return bound;
|
|
1294
|
+
}
|
|
1295
|
+
if (fixed !== undefined && fixed > 0) {
|
|
1296
|
+
return this.least(bound, length);
|
|
1297
|
+
}
|
|
1298
|
+
if (fixed !== undefined) {
|
|
1299
|
+
return this.most(this.difference(length, constant(-fixed)), constant(0));
|
|
1300
|
+
}
|
|
1301
|
+
const index = this.text(bound);
|
|
1302
|
+
const size = this.text(length);
|
|
1303
|
+
return this.number(
|
|
1304
|
+
mapped`(${index} < 0 ? (${size} + ${index} > 0 ? ${size} + ${index} : 0) : (${index} < ${size} ? ${index} : ${size}))`,
|
|
1305
|
+
);
|
|
1306
|
+
}
|
|
1307
|
+
|
|
1308
|
+
/** The position a callback is given, counted at run time only if the callback takes it. */
|
|
1309
|
+
private indexer(
|
|
1310
|
+
traversal: Traversal,
|
|
1311
|
+
callback: Value,
|
|
1312
|
+
parameter: number,
|
|
1313
|
+
frame: Frame,
|
|
1314
|
+
): (element: Visited) => Value {
|
|
1315
|
+
if (!takes(callback, parameter) || traversal.indexed) {
|
|
1316
|
+
return (element) => element.index ?? constant(undefined);
|
|
1317
|
+
}
|
|
1318
|
+
const total = frame.emitter.temporary();
|
|
1319
|
+
frame.emitter.line(`let ${total}: number = 0;`);
|
|
1320
|
+
return () => {
|
|
1321
|
+
const index = frame.emitter.temporary();
|
|
1322
|
+
// Held before the count moves on, which a continue in the code after this would skip.
|
|
1323
|
+
frame.emitter.line(`const ${index}: number = ${total};`);
|
|
1324
|
+
frame.emitter.line(`${total} = ${total} + 1;`);
|
|
1325
|
+
return this.number(index);
|
|
1326
|
+
};
|
|
1327
|
+
}
|
|
1328
|
+
|
|
1329
|
+
private callback(node: ts.CallExpression, frame: Frame): Value {
|
|
1330
|
+
const [argument] = node.arguments;
|
|
1331
|
+
if (!argument) {
|
|
1332
|
+
throw new SpecializeError(node, "Pass a callback.");
|
|
1333
|
+
}
|
|
1334
|
+
return this.expressions.expression(argument, frame);
|
|
1335
|
+
}
|
|
1336
|
+
|
|
1337
|
+
private target(node: ts.CallExpression, frame: Frame): Value {
|
|
1338
|
+
const [argument] = node.arguments;
|
|
1339
|
+
if (!argument) {
|
|
1340
|
+
throw new SpecializeError(node, "Pass the value to look for.");
|
|
1341
|
+
}
|
|
1342
|
+
return this.expressions.held(
|
|
1343
|
+
this.expressions.expression(argument, frame),
|
|
1344
|
+
frame,
|
|
1345
|
+
);
|
|
1346
|
+
}
|
|
1347
|
+
|
|
1348
|
+
/** `take` and `drop`'s count: known now, or held in a const before the generator runs. */
|
|
1349
|
+
private amount(node: ts.CallExpression, frame: Frame): Value {
|
|
1350
|
+
const [argument] = node.arguments;
|
|
1351
|
+
const value = argument && this.expressions.expression(argument, frame);
|
|
1352
|
+
const count = value && this.bound(value, node, frame);
|
|
1353
|
+
if (!count) {
|
|
1354
|
+
throw new SpecializeError(node, "Pass how many elements.");
|
|
1355
|
+
}
|
|
1356
|
+
return count;
|
|
1357
|
+
}
|
|
1358
|
+
|
|
1359
|
+
/**
|
|
1360
|
+
* A computed value read once, into a const, where the code after reads it more than once. A place
|
|
1361
|
+
* is read where it is: a const naming one would be an alias of it, not a copy.
|
|
1362
|
+
*/
|
|
1363
|
+
private once(value: Value, frame: Frame): Value {
|
|
1364
|
+
return value.kind === "code" && !value.place
|
|
1365
|
+
? this.expressions.temporaryOf(value, frame)
|
|
1366
|
+
: value;
|
|
1367
|
+
}
|
|
1368
|
+
|
|
1369
|
+
/** A number computed at run time in a const of its own, so the bounds that use it read it rather than repeat it. */
|
|
1370
|
+
private kept(value: Value, frame: Frame): Value {
|
|
1371
|
+
if (value.kind !== "code" || repeatable(value.text)) {
|
|
1372
|
+
return value;
|
|
1373
|
+
}
|
|
1374
|
+
const local = frame.emitter.temporary();
|
|
1375
|
+
frame.emitter.line(mapped`const ${local}: number = ${value.text};`);
|
|
1376
|
+
return this.number(local);
|
|
1377
|
+
}
|
|
1378
|
+
|
|
1379
|
+
private condition(value: Value, at: ts.CallExpression): string | Mapped {
|
|
1380
|
+
return this.dialect.condition(value, at.arguments[0] ?? at);
|
|
1381
|
+
}
|
|
1382
|
+
|
|
1383
|
+
private number(text: string | Mapped): Value {
|
|
1384
|
+
return {
|
|
1385
|
+
kind: "code",
|
|
1386
|
+
text,
|
|
1387
|
+
declared: this.checker.getNumberType(),
|
|
1388
|
+
place: true,
|
|
1389
|
+
};
|
|
1390
|
+
}
|
|
1391
|
+
|
|
1392
|
+
private text(value: Value): string | Mapped {
|
|
1393
|
+
return this.dialect.code(value, undefined);
|
|
1394
|
+
}
|
|
1395
|
+
|
|
1396
|
+
private sum(left: Value, right: Value): Value {
|
|
1397
|
+
const [first, second] = [known(left), known(right)];
|
|
1398
|
+
if (first !== undefined && second !== undefined) {
|
|
1399
|
+
return constant(first + second);
|
|
1400
|
+
}
|
|
1401
|
+
if (first === 0) {
|
|
1402
|
+
return right;
|
|
1403
|
+
}
|
|
1404
|
+
if (second === 0) {
|
|
1405
|
+
return left;
|
|
1406
|
+
}
|
|
1407
|
+
return this.number(mapped`(${this.text(left)} + ${this.text(right)})`);
|
|
1408
|
+
}
|
|
1409
|
+
|
|
1410
|
+
private difference(left: Value, right: Value): Value {
|
|
1411
|
+
const [first, second] = [known(left), known(right)];
|
|
1412
|
+
if (first !== undefined && second !== undefined) {
|
|
1413
|
+
return constant(first - second);
|
|
1414
|
+
}
|
|
1415
|
+
if (second === 0) {
|
|
1416
|
+
return left;
|
|
1417
|
+
}
|
|
1418
|
+
return this.number(mapped`(${this.text(left)} - ${this.text(right)})`);
|
|
1419
|
+
}
|
|
1420
|
+
|
|
1421
|
+
private least(left: Value, right: Value): Value {
|
|
1422
|
+
const [first, second] = [known(left), known(right)];
|
|
1423
|
+
if (first !== undefined && second !== undefined) {
|
|
1424
|
+
return constant(Math.min(first, second));
|
|
1425
|
+
}
|
|
1426
|
+
const [low, other] = [this.text(left), this.text(right)];
|
|
1427
|
+
return this.number(mapped`(${low} < ${other} ? ${low} : ${other})`);
|
|
1428
|
+
}
|
|
1429
|
+
|
|
1430
|
+
private most(left: Value, right: Value): Value {
|
|
1431
|
+
const [first, second] = [known(left), known(right)];
|
|
1432
|
+
if (first !== undefined && second !== undefined) {
|
|
1433
|
+
return constant(Math.max(first, second));
|
|
1434
|
+
}
|
|
1435
|
+
const [high, other] = [this.text(left), this.text(right)];
|
|
1436
|
+
return this.number(mapped`(${high} > ${other} ? ${high} : ${other})`);
|
|
1437
|
+
}
|
|
1438
|
+
|
|
1439
|
+
private compare(
|
|
1440
|
+
left: Value,
|
|
1441
|
+
operator: "<" | "<=",
|
|
1442
|
+
right: Value,
|
|
1443
|
+
): boolean | Mapped {
|
|
1444
|
+
const [first, second] = [known(left), known(right)];
|
|
1445
|
+
if (first !== undefined && second !== undefined) {
|
|
1446
|
+
return operator === "<" ? first < second : first <= second;
|
|
1447
|
+
}
|
|
1448
|
+
return mapped`${this.text(left)} ${operator} ${this.text(right)}`;
|
|
1449
|
+
}
|
|
1450
|
+
}
|
|
1451
|
+
|
|
1452
|
+
/**
|
|
1453
|
+
* How many times a counted loop's body can run: from its start, the bound its counter is compared
|
|
1454
|
+
* with and its step, when setup fixed them all. Undefined for a header that doesn't say.
|
|
1455
|
+
*/
|
|
1456
|
+
export const iterationCount = (
|
|
1457
|
+
start: Value,
|
|
1458
|
+
comparison: ts.SyntaxKind,
|
|
1459
|
+
limit: Value,
|
|
1460
|
+
incrementor: ts.Expression,
|
|
1461
|
+
): number | undefined => {
|
|
1462
|
+
const first = known(start);
|
|
1463
|
+
const last = known(limit);
|
|
1464
|
+
const step = stepOf(incrementor);
|
|
1465
|
+
if (first === undefined || last === undefined || step === undefined) {
|
|
1466
|
+
return undefined;
|
|
1467
|
+
}
|
|
1468
|
+
const span = step > 0 ? last - first : first - last;
|
|
1469
|
+
const size = Math.abs(step);
|
|
1470
|
+
const rising = step > 0;
|
|
1471
|
+
switch (comparison) {
|
|
1472
|
+
case rising ? ts.SyntaxKind.LessThanToken : ts.SyntaxKind.GreaterThanToken:
|
|
1473
|
+
return Math.max(0, Math.ceil(span / size));
|
|
1474
|
+
case rising
|
|
1475
|
+
? ts.SyntaxKind.LessThanEqualsToken
|
|
1476
|
+
: ts.SyntaxKind.GreaterThanEqualsToken:
|
|
1477
|
+
return Math.max(0, Math.floor(span / size) + 1);
|
|
1478
|
+
default:
|
|
1479
|
+
return undefined;
|
|
1480
|
+
}
|
|
1481
|
+
};
|
|
1482
|
+
|
|
1483
|
+
const iecNames = new Set(primitiveTypes.map((type) => type.id));
|
|
1484
|
+
|
|
1485
|
+
/**
|
|
1486
|
+
* What a stored array's layout says of it, as `FixedArray<BYTE, 32>` does: how many elements it
|
|
1487
|
+
* has, and the IEC width of each when the layout names one. An array a routine was passed has
|
|
1488
|
+
* only its layout to say so.
|
|
1489
|
+
*/
|
|
1490
|
+
const storedArray = (
|
|
1491
|
+
layout: string,
|
|
1492
|
+
): { bound: number; iec: string | undefined } | undefined => {
|
|
1493
|
+
const [, element, size] = /^FixedArray<(.*), (\d+)>$/.exec(layout) ?? [];
|
|
1494
|
+
if (element === undefined || size === undefined) {
|
|
1495
|
+
return undefined;
|
|
1496
|
+
}
|
|
1497
|
+
return {
|
|
1498
|
+
bound: Number(size),
|
|
1499
|
+
iec: iecNames.has(element) ? element : undefined,
|
|
1500
|
+
};
|
|
1501
|
+
};
|
|
1502
|
+
|
|
1503
|
+
/** What tells two counted arguments apart to the routine specialized for them. */
|
|
1504
|
+
export const countedKey = (
|
|
1505
|
+
counted: Counted,
|
|
1506
|
+
valueKey: (value: Value) => string,
|
|
1507
|
+
): string => {
|
|
1508
|
+
const { source } = counted;
|
|
1509
|
+
const bounds = `${valueKey(counted.start)}..${valueKey(counted.end)}`;
|
|
1510
|
+
return source.kind === "items"
|
|
1511
|
+
? `counted[${source.items.map(valueKey).join(",")}]${bounds}`
|
|
1512
|
+
: `counted:${source.layout}:${valueKey(source.element("0"))}:${bounds}`;
|
|
1513
|
+
};
|
|
1514
|
+
|
|
1515
|
+
/** An element as a routine reads it from the array it was passed: the same slot of its own parameter. */
|
|
1516
|
+
const reread = (
|
|
1517
|
+
sample: Value,
|
|
1518
|
+
array: string,
|
|
1519
|
+
index: string | Mapped,
|
|
1520
|
+
): Value => {
|
|
1521
|
+
const place = mapped`${array}[${index}]`;
|
|
1522
|
+
if (sample.kind === "choice") {
|
|
1523
|
+
return { ...sample, index: place };
|
|
1524
|
+
}
|
|
1525
|
+
return sample.kind === "code" ? { ...sample, text: place } : sample;
|
|
1526
|
+
};
|
|
1527
|
+
|
|
1528
|
+
/** A counted loop's step, as `i++`, `i--`, `i += 2` or `i -= 2` writes it. */
|
|
1529
|
+
const stepOf = (incrementor: ts.Expression): number | undefined => {
|
|
1530
|
+
if (
|
|
1531
|
+
ts.isPrefixUnaryExpression(incrementor) ||
|
|
1532
|
+
ts.isPostfixUnaryExpression(incrementor)
|
|
1533
|
+
) {
|
|
1534
|
+
return incrementor.operator === ts.SyntaxKind.PlusPlusToken ? 1 : -1;
|
|
1535
|
+
}
|
|
1536
|
+
if (
|
|
1537
|
+
!ts.isBinaryExpression(incrementor) ||
|
|
1538
|
+
!ts.isNumericLiteral(incrementor.right)
|
|
1539
|
+
) {
|
|
1540
|
+
return undefined;
|
|
1541
|
+
}
|
|
1542
|
+
const size = Number(incrementor.right.text);
|
|
1543
|
+
switch (incrementor.operatorToken.kind) {
|
|
1544
|
+
case ts.SyntaxKind.PlusEqualsToken:
|
|
1545
|
+
return size > 0 ? size : undefined;
|
|
1546
|
+
case ts.SyntaxKind.MinusEqualsToken:
|
|
1547
|
+
return size > 0 ? -size : undefined;
|
|
1548
|
+
default:
|
|
1549
|
+
return undefined;
|
|
1550
|
+
}
|
|
1551
|
+
};
|
|
1552
|
+
|
|
1553
|
+
/**
|
|
1554
|
+
* The objects references among the values can be, and whether one can be undefined; undefined
|
|
1555
|
+
* when none of the values is an object setup built.
|
|
1556
|
+
*/
|
|
1557
|
+
const references = (
|
|
1558
|
+
values: readonly Value[],
|
|
1559
|
+
): { options: readonly ModelNode[]; optional: boolean } | undefined => {
|
|
1560
|
+
const options = values.flatMap((value) => {
|
|
1561
|
+
if (value.kind === "choice") {
|
|
1562
|
+
return value.options;
|
|
1563
|
+
}
|
|
1564
|
+
return value.kind === "static" ? [value.node] : [];
|
|
1565
|
+
});
|
|
1566
|
+
if (!options.length) {
|
|
1567
|
+
return undefined;
|
|
1568
|
+
}
|
|
1569
|
+
return {
|
|
1570
|
+
// In the order setup built them, so the code over them is the same every build.
|
|
1571
|
+
options: [...new Set(options)].sort((left, right) => left.id - right.id),
|
|
1572
|
+
optional: values.some(
|
|
1573
|
+
(value) =>
|
|
1574
|
+
value.kind === "const" || (value.kind === "choice" && value.optional),
|
|
1575
|
+
),
|
|
1576
|
+
};
|
|
1577
|
+
};
|
|
1578
|
+
|
|
1579
|
+
/** A value a local can keep a copy of. */
|
|
1580
|
+
const copyable = (value: Value, at: ts.Node): Value => {
|
|
1581
|
+
if (value.kind === "function" || value.kind === "counted") {
|
|
1582
|
+
throw new SpecializeError(
|
|
1583
|
+
at,
|
|
1584
|
+
"This copies each value, and a function or an array whose length is decided at run time has no PLC value to copy.",
|
|
1585
|
+
);
|
|
1586
|
+
}
|
|
1587
|
+
return value;
|
|
1588
|
+
};
|
|
1589
|
+
|
|
1590
|
+
/**
|
|
1591
|
+
* `method` when one of the values it copies is stored state: a record or array the PLC keeps,
|
|
1592
|
+
* or a copy of one. TypeScript would hand back the stored object itself, so writing the copy is
|
|
1593
|
+
* reported rather than lost.
|
|
1594
|
+
*/
|
|
1595
|
+
const copiedFrom = (
|
|
1596
|
+
values: readonly Value[],
|
|
1597
|
+
method: string,
|
|
1598
|
+
): string | undefined =>
|
|
1599
|
+
values.some(
|
|
1600
|
+
(value) =>
|
|
1601
|
+
value.kind === "code" &&
|
|
1602
|
+
(value.copyOf !== undefined ||
|
|
1603
|
+
(value.place === true &&
|
|
1604
|
+
value.declared !== undefined &&
|
|
1605
|
+
Boolean(value.declared.flags & ts.TypeFlags.Object))),
|
|
1606
|
+
)
|
|
1607
|
+
? method
|
|
1608
|
+
: undefined;
|
|
1609
|
+
|
|
1610
|
+
/** The smaller of two limits, either of which may be unknown. */
|
|
1611
|
+
const fewest = (
|
|
1612
|
+
left: number | undefined,
|
|
1613
|
+
right: number | undefined,
|
|
1614
|
+
): number | undefined => {
|
|
1615
|
+
if (left === undefined || right === undefined) {
|
|
1616
|
+
return left ?? right;
|
|
1617
|
+
}
|
|
1618
|
+
return Math.min(left, right);
|
|
1619
|
+
};
|
|
1620
|
+
|
|
1621
|
+
const known = (value: Value): number | undefined =>
|
|
1622
|
+
value.kind === "const" && typeof value.value === "number"
|
|
1623
|
+
? value.value
|
|
1624
|
+
: undefined;
|
|
1625
|
+
|
|
1626
|
+
/** Whether two numbers are the same one: equal constants, or the same local. */
|
|
1627
|
+
const sameNumber = (left: Value, right: Value): boolean => {
|
|
1628
|
+
if (left.kind === "code" && right.kind === "code") {
|
|
1629
|
+
return String(left.text) === String(right.text);
|
|
1630
|
+
}
|
|
1631
|
+
const fixed = known(left);
|
|
1632
|
+
return fixed !== undefined && fixed === known(right);
|
|
1633
|
+
};
|
|
1634
|
+
|
|
1635
|
+
/** A test's result when it is known now: a value setup fixed, or an object, which is always truthy. */
|
|
1636
|
+
const truth = (value: Value): boolean | undefined => {
|
|
1637
|
+
if (value.kind === "const") {
|
|
1638
|
+
return Boolean(value.value);
|
|
1639
|
+
}
|
|
1640
|
+
return value.kind === "code" ? undefined : true;
|
|
1641
|
+
};
|
|
1642
|
+
|
|
1643
|
+
/** Every condition at once: false if one is known false, true if all are known true, otherwise the rest as one test. */
|
|
1644
|
+
const all = (conditions: readonly (boolean | Mapped)[]): boolean | Mapped => {
|
|
1645
|
+
if (conditions.includes(false)) {
|
|
1646
|
+
return false;
|
|
1647
|
+
}
|
|
1648
|
+
const tests = conditions.filter(
|
|
1649
|
+
(condition): condition is Mapped => condition instanceof Mapped,
|
|
1650
|
+
);
|
|
1651
|
+
return tests.length ? joined(tests, " && ") : true;
|
|
1652
|
+
};
|
|
1653
|
+
|
|
1654
|
+
/** Whether a callback declares the parameter at a position, so it reads what is passed there. */
|
|
1655
|
+
const takes = (callback: Value, parameter: number): boolean =>
|
|
1656
|
+
callback.kind === "function" &&
|
|
1657
|
+
!ts.isGetAccessorDeclaration(callback.declaration) &&
|
|
1658
|
+
callback.declaration.parameters.some(
|
|
1659
|
+
(declared, position) =>
|
|
1660
|
+
position === parameter ||
|
|
1661
|
+
(declared.dotDotDotToken !== undefined && position < parameter),
|
|
1662
|
+
);
|
|
1663
|
+
|
|
1664
|
+
const unwrapped = (node: ts.Expression): ts.Expression =>
|
|
1665
|
+
ts.isParenthesizedExpression(node) ||
|
|
1666
|
+
ts.isNonNullExpression(node) ||
|
|
1667
|
+
ts.isAsExpression(node) ||
|
|
1668
|
+
ts.isSatisfiesExpression(node)
|
|
1669
|
+
? unwrapped(node.expression)
|
|
1670
|
+
: node;
|
|
1671
|
+
|
|
1672
|
+
/** What reads an expression, outside the parentheses around it. */
|
|
1673
|
+
const outside = (node: ts.Node): ts.Node =>
|
|
1674
|
+
ts.isParenthesizedExpression(node.parent) ||
|
|
1675
|
+
ts.isNonNullExpression(node.parent)
|
|
1676
|
+
? outside(node.parent)
|
|
1677
|
+
: node.parent;
|