@tsplc/compiler 0.5.7 → 0.5.8

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.
@@ -0,0 +1,895 @@
1
+ import type { BinaryOperator, UnaryOperator } from "@tsplc/iec/arithmetic";
2
+ import {
3
+ type CoreExpression,
4
+ type CoreFunction,
5
+ type CoreFunctionBlock,
6
+ type CorePath,
7
+ type CoreStatement,
8
+ nestedBodies,
9
+ } from "./core-model";
10
+ import type { SourceSpan } from "./diagnostics";
11
+ import type { Constant, Variable } from "./model";
12
+ import { isTemporary } from "./routine";
13
+
14
+ type Routine = CoreFunction | CoreFunctionBlock;
15
+ type Assign = Extract<CoreStatement, { kind: "assign" }>;
16
+ type If = Extract<CoreStatement, { kind: "if" }>;
17
+ type For = Extract<CoreStatement, { kind: "for" }>;
18
+ type Invoke = Extract<CoreStatement, { kind: "invoke" }>;
19
+
20
+ export type ReconstructedSegment =
21
+ | { readonly kind: "field"; readonly name: string }
22
+ | { readonly kind: "index"; readonly value: Reconstruction };
23
+
24
+ /**
25
+ * A core expression as its source wrote it: the temporaries lowering made for captures, `&&`,
26
+ * `||`, `?:`, record literals and call results inlined back into the expression they stand for.
27
+ * Positions are pre-order statement indexes within the routine.
28
+ */
29
+ export type Reconstruction = {
30
+ readonly type: string;
31
+ readonly span: SourceSpan;
32
+ } & (
33
+ | {
34
+ /** Storage the routine doesn't own: module storage, or a field of the block it runs on. */
35
+ readonly kind: "read";
36
+ readonly root: string;
37
+ readonly path: readonly ReconstructedSegment[];
38
+ /** Where the value was captured. */
39
+ readonly capturedAt: number;
40
+ /** Whether a call runs between the capture and the use, and may have changed it. */
41
+ readonly interleaved: boolean;
42
+ }
43
+ | { readonly kind: "constant"; readonly value: Constant }
44
+ | {
45
+ readonly kind: "record";
46
+ readonly fields: Readonly<Record<string, Reconstruction>>;
47
+ }
48
+ | {
49
+ readonly kind: "array";
50
+ /** The index of the first item. */
51
+ readonly lower: number;
52
+ readonly items: readonly Reconstruction[];
53
+ }
54
+ | {
55
+ /** A local the source declares, read at `at`. */
56
+ readonly kind: "local";
57
+ readonly root: string;
58
+ readonly path: readonly ReconstructedSegment[];
59
+ readonly at: number;
60
+ }
61
+ | {
62
+ readonly kind: "parameter";
63
+ readonly parameter: number;
64
+ readonly root: string;
65
+ readonly path: readonly ReconstructedSegment[];
66
+ readonly at: number;
67
+ }
68
+ | {
69
+ /** A call's result, or one of its fields. */
70
+ readonly kind: "call";
71
+ readonly call: Invoke;
72
+ readonly path: readonly string[];
73
+ }
74
+ | { readonly kind: "clock" }
75
+ | {
76
+ readonly kind: "unary";
77
+ readonly operator: Exclude<UnaryOperator, "clock">;
78
+ readonly operand: Reconstruction;
79
+ }
80
+ | {
81
+ readonly kind: "binary";
82
+ readonly operator: Exclude<BinaryOperator, "and" | "or">;
83
+ readonly policy?: "wrap" | "saturate";
84
+ readonly left: Reconstruction;
85
+ readonly right: Reconstruction;
86
+ }
87
+ | {
88
+ readonly kind: "convert";
89
+ readonly policy: "exact" | "wrap" | "saturate";
90
+ readonly operand: Reconstruction;
91
+ }
92
+ | {
93
+ /** `&&` or `||`: `right` is evaluated only when `left` doesn't decide. */
94
+ readonly kind: "logical";
95
+ readonly operator: "and" | "or";
96
+ readonly left: Reconstruction;
97
+ readonly right: Reconstruction;
98
+ }
99
+ | {
100
+ readonly kind: "select";
101
+ readonly condition: Reconstruction;
102
+ readonly then: Reconstruction;
103
+ readonly else: Reconstruction;
104
+ }
105
+ | {
106
+ readonly kind: "opaque";
107
+ readonly reason: string;
108
+ readonly reads: readonly Reconstruction[];
109
+ }
110
+ );
111
+
112
+ /** A condition a statement runs under. Tests carry `at`, the position that evaluates them. */
113
+ export type PathCondition =
114
+ | {
115
+ readonly kind: "test";
116
+ readonly test: Reconstruction;
117
+ readonly holds: boolean;
118
+ readonly at: number;
119
+ readonly span: SourceSpan;
120
+ }
121
+ | {
122
+ readonly kind: "cases";
123
+ readonly test: Reconstruction;
124
+ readonly values: readonly Constant[];
125
+ readonly member: boolean;
126
+ readonly at: number;
127
+ readonly span: SourceSpan;
128
+ }
129
+ | {
130
+ /** Holds when none of the conjunctions holds: an earlier statement did not leave. */
131
+ readonly kind: "exits";
132
+ readonly any: readonly (readonly PathCondition[])[];
133
+ }
134
+ | { readonly kind: "loop"; readonly loop: number }
135
+ /** Holds when no iteration of the loop returned from the routine. */
136
+ | { readonly kind: "loopReturns"; readonly loop: number }
137
+ /** A job's step `step` is current. */
138
+ | { readonly kind: "job"; readonly step: number }
139
+ /** The job is busy: its dispatcher returns at once otherwise. */
140
+ | { readonly kind: "jobBusy" };
141
+
142
+ export interface StatementConditions {
143
+ readonly position: number;
144
+ /** Outermost first. */
145
+ readonly conditions: readonly PathCondition[];
146
+ /** The innermost loop the statement runs in, as an index into `loops`. */
147
+ readonly loop: number | null;
148
+ }
149
+
150
+ export interface LoopConditions {
151
+ readonly statement: For;
152
+ readonly position: number;
153
+ readonly counter: string;
154
+ readonly first: Reconstruction;
155
+ readonly limit: Reconstruction;
156
+ readonly exclusive: boolean;
157
+ readonly step: bigint;
158
+ readonly maxIterations: number;
159
+ /** The conjunctions, within one iteration, under which a `break` stops the loop. */
160
+ readonly breaks: readonly (readonly PathCondition[])[];
161
+ /** Whether an iteration can return from the routine. */
162
+ readonly returns: boolean;
163
+ readonly parent: number | null;
164
+ }
165
+
166
+ export interface RoutineConditions {
167
+ readonly statements: ReadonlyMap<CoreStatement, StatementConditions>;
168
+ readonly loops: readonly LoopConditions[];
169
+ /** `expression` as the source wrote it, used at position `at`. */
170
+ readonly reconstruct: (
171
+ expression: CoreExpression,
172
+ at: number,
173
+ ) => Reconstruction;
174
+ }
175
+
176
+ type Conjunction = readonly PathCondition[];
177
+ interface Exits {
178
+ readonly returns: readonly Conjunction[];
179
+ readonly breaks: readonly Conjunction[];
180
+ readonly continues: readonly Conjunction[];
181
+ }
182
+ const noExits: Exits = { returns: [], breaks: [], continues: [] };
183
+
184
+ const prefixed = (conditions: Conjunction, exits: Exits): Exits => ({
185
+ returns: exits.returns.map((item) => [...conditions, ...item]),
186
+ breaks: exits.breaks.map((item) => [...conditions, ...item]),
187
+ continues: exits.continues.map((item) => [...conditions, ...item]),
188
+ });
189
+
190
+ const merged = (...all: readonly Exits[]): Exits => ({
191
+ returns: all.flatMap((exits) => exits.returns),
192
+ breaks: all.flatMap((exits) => exits.breaks),
193
+ continues: all.flatMap((exits) => exits.continues),
194
+ });
195
+
196
+ const wholeAssign = (
197
+ item: CoreStatement | undefined,
198
+ root: string,
199
+ ): item is Assign =>
200
+ item?.kind === "assign" && item.root === root && !item.path?.length;
201
+
202
+ const loadedRoot = (value: CoreExpression): string | undefined =>
203
+ value.kind === "load" && !value.path?.length ? value.root : undefined;
204
+
205
+ const constantIndex = (value: CoreExpression): number | undefined =>
206
+ value.kind === "constant" && value.value.kind === "integer"
207
+ ? Number(value.value.value)
208
+ : undefined;
209
+
210
+ /** A constant's field or element, when it has one. */
211
+ const constantPart = (
212
+ value: Constant,
213
+ segment: ReconstructedSegment,
214
+ lower: number,
215
+ ): Constant | undefined => {
216
+ if (segment.kind === "field") {
217
+ return value.kind === "record" ? value.fields[segment.name] : undefined;
218
+ }
219
+ const index =
220
+ segment.value.kind === "constant" && segment.value.value.kind === "integer"
221
+ ? Number(segment.value.value.value)
222
+ : undefined;
223
+ return value.kind === "array" && index !== undefined
224
+ ? value.items[index - lower]
225
+ : undefined;
226
+ };
227
+
228
+ /** The names along a path of fields and constant indexes, or nothing when an index is dynamic. */
229
+ const staticNames = (
230
+ path: readonly ReconstructedSegment[],
231
+ ): string[] | undefined => {
232
+ const names: string[] = [];
233
+ for (const segment of path) {
234
+ if (segment.kind === "field") {
235
+ names.push(segment.name);
236
+ continue;
237
+ }
238
+ if (
239
+ segment.value.kind !== "constant" ||
240
+ segment.value.value.kind !== "integer"
241
+ ) {
242
+ return undefined;
243
+ }
244
+ names.push(segment.value.value.value);
245
+ }
246
+ return names;
247
+ };
248
+
249
+ const opaque = (
250
+ reason: string,
251
+ type: string,
252
+ span: SourceSpan,
253
+ reads: readonly Reconstruction[] = [],
254
+ ): Reconstruction => ({ kind: "opaque", reason, reads, type, span });
255
+
256
+ /** A part of a reconstructed value: a field or element of a record, array, constant or place. */
257
+ export const projectReconstruction = (
258
+ node: Reconstruction,
259
+ path: readonly ReconstructedSegment[],
260
+ type: string,
261
+ ): Reconstruction => {
262
+ const [segment, ...rest] = path;
263
+ if (!segment) {
264
+ return node;
265
+ }
266
+ switch (node.kind) {
267
+ case "read":
268
+ case "local":
269
+ case "parameter":
270
+ return { ...node, path: [...node.path, ...path], type };
271
+ case "call": {
272
+ const names = staticNames(path);
273
+ return names
274
+ ? { ...node, path: [...node.path, ...names], type }
275
+ : opaque("a call result at a dynamic index", type, node.span);
276
+ }
277
+ case "record": {
278
+ const field =
279
+ segment.kind === "field" ? node.fields[segment.name] : undefined;
280
+ return field
281
+ ? projectReconstruction(field, rest, type)
282
+ : opaque("a field the record doesn't set", type, node.span);
283
+ }
284
+ case "array": {
285
+ const index =
286
+ segment.kind === "index" &&
287
+ segment.value.kind === "constant" &&
288
+ segment.value.value.kind === "integer"
289
+ ? Number(segment.value.value.value)
290
+ : undefined;
291
+ const item =
292
+ index === undefined ? undefined : node.items[index - node.lower];
293
+ return item
294
+ ? projectReconstruction(item, rest, type)
295
+ : opaque("an element at a dynamic index", type, node.span);
296
+ }
297
+ case "constant": {
298
+ const part = constantPart(node.value, segment, 0);
299
+ return part
300
+ ? projectReconstruction(
301
+ { kind: "constant", value: part, type, span: node.span },
302
+ rest,
303
+ type,
304
+ )
305
+ : opaque("a part of a constant", type, node.span);
306
+ }
307
+ case "select":
308
+ return {
309
+ ...node,
310
+ type,
311
+ // biome-ignore lint/suspicious/noThenProperty: a reconstructed `?:` is data, not a thenable.
312
+ then: projectReconstruction(node.then, path, type),
313
+ else: projectReconstruction(node.else, path, type),
314
+ };
315
+ default:
316
+ return opaque("a part of a computed value", type, node.span, [node]);
317
+ }
318
+ };
319
+
320
+ /**
321
+ * Each statement's conditions from routine entry, and the inverse of `routine.ts`'s lowering
322
+ * for the expressions it evaluates. `variables` resolves the types of storage the routine
323
+ * doesn't declare, such as a stored loop counter.
324
+ */
325
+ export function pathConditions(
326
+ routine: Routine,
327
+ variables: ReadonlyMap<string, Pick<Variable, "type">>,
328
+ ): RoutineConditions {
329
+ const temporaries = new Set(
330
+ routine.locals
331
+ .filter((local) => isTemporary(routine.id, local))
332
+ .map((local) => local.id),
333
+ );
334
+ const locals = new Map(
335
+ routine.locals
336
+ .filter((local) => !temporaries.has(local.id))
337
+ .map((local) => [local.id, local]),
338
+ );
339
+ const parameters = new Map(
340
+ "parameters" in routine
341
+ ? routine.parameters.map((parameter, index) => [parameter.id, index])
342
+ : [],
343
+ );
344
+ const typeOf = (root: string): string | undefined =>
345
+ locals.get(root)?.type ??
346
+ ("parameters" in routine
347
+ ? routine.parameters.find((parameter) => parameter.id === root)?.type
348
+ : undefined) ??
349
+ variables.get(root)?.type;
350
+
351
+ const positions = new Map<CoreStatement, number>();
352
+ const calls: number[] = [];
353
+ const definitions = new Map<string, CoreStatement[]>();
354
+ const logicals = new Map<
355
+ string,
356
+ { operator: "and" | "or"; left: Assign; right: Assign }
357
+ >();
358
+ const synthetic = new Map<If, { operator: "and" | "or"; left: Assign }>();
359
+ const selects = new Map<string, { test: If; then: Assign; else: Assign }>();
360
+ const sequences: (readonly CoreStatement[])[] = [];
361
+ const number = (items: readonly CoreStatement[]): void => {
362
+ sequences.push(items);
363
+ for (const item of items) {
364
+ positions.set(item, positions.size);
365
+ if (item.kind === "invoke" || item.kind === "blockUpdate") {
366
+ calls.push(positions.size - 1);
367
+ }
368
+ const defined =
369
+ item.kind === "assign"
370
+ ? item.root
371
+ : (item.kind === "invoke" && item.destination) || undefined;
372
+ if (defined && temporaries.has(defined)) {
373
+ definitions.set(defined, [...(definitions.get(defined) ?? []), item]);
374
+ }
375
+ nestedBodies(item).forEach(number);
376
+ }
377
+ };
378
+ number(routine.body);
379
+ const position = (item: CoreStatement): number => positions.get(item) ?? 0;
380
+ // `a && b` lowers to `t := a; if t { …; t := b }`, `||` the same under `if NOT t`, and
381
+ // `c ? x : y` to `if c { …; t := x } else { …; t := y }`.
382
+ for (const items of sequences) {
383
+ items.forEach((item, index) => {
384
+ const next = items[index + 1];
385
+ if (
386
+ item.kind === "assign" &&
387
+ !item.path?.length &&
388
+ temporaries.has(item.root) &&
389
+ next?.kind === "if" &&
390
+ !next.else.length
391
+ ) {
392
+ const negated =
393
+ next.condition.kind === "unary" && next.condition.operator === "not";
394
+ const tested = loadedRoot(
395
+ next.condition.kind === "unary" && next.condition.operator === "not"
396
+ ? next.condition.operand
397
+ : next.condition,
398
+ );
399
+ const right = next.then.at(-1);
400
+ if (
401
+ tested === item.root &&
402
+ wholeAssign(right, item.root) &&
403
+ definitions.get(item.root)?.length === 2
404
+ ) {
405
+ const operator = negated ? "or" : "and";
406
+ logicals.set(item.root, { operator, left: item, right });
407
+ synthetic.set(next, { operator, left: item });
408
+ }
409
+ }
410
+ if (item.kind === "if") {
411
+ const then = item.then.at(-1);
412
+ const otherwise = item.else.at(-1);
413
+ if (
414
+ then?.kind === "assign" &&
415
+ temporaries.has(then.root) &&
416
+ wholeAssign(then, then.root) &&
417
+ wholeAssign(otherwise, then.root) &&
418
+ definitions.get(then.root)?.length === 2
419
+ ) {
420
+ selects.set(then.root, { test: item, then, else: otherwise });
421
+ }
422
+ }
423
+ });
424
+ }
425
+
426
+ const interleaved = (capturedAt: number, at: number): boolean =>
427
+ calls.some((call) => call > capturedAt && call < at);
428
+
429
+ const segments = (path: CorePath, at: number): ReconstructedSegment[] =>
430
+ path.map((segment) =>
431
+ segment.kind === "field"
432
+ ? segment
433
+ : { kind: "index", value: reconstruct(segment.value, at) },
434
+ );
435
+
436
+ /** A stored, local or parameter place, read where it was captured. */
437
+ const place = (
438
+ root: string,
439
+ path: readonly ReconstructedSegment[],
440
+ capturedAt: number,
441
+ at: number,
442
+ type: string,
443
+ span: SourceSpan,
444
+ ): Reconstruction => {
445
+ if (temporaries.has(root)) {
446
+ return temporary(root, path, at, type, span);
447
+ }
448
+ if (locals.has(root)) {
449
+ return { kind: "local", root, path, at: capturedAt, type, span };
450
+ }
451
+ const parameter = parameters.get(root);
452
+ if (parameter !== undefined) {
453
+ return {
454
+ kind: "parameter",
455
+ parameter,
456
+ root,
457
+ path,
458
+ at: capturedAt,
459
+ type,
460
+ span,
461
+ };
462
+ }
463
+ return {
464
+ kind: "read",
465
+ root,
466
+ path,
467
+ capturedAt,
468
+ interleaved: interleaved(capturedAt, at),
469
+ type,
470
+ span,
471
+ };
472
+ };
473
+
474
+ const temporary = (
475
+ root: string,
476
+ path: readonly ReconstructedSegment[],
477
+ at: number,
478
+ type: string,
479
+ span: SourceSpan,
480
+ ): Reconstruction => {
481
+ const logical = logicals.get(root);
482
+ if (logical) {
483
+ return projectReconstruction(
484
+ {
485
+ kind: "logical",
486
+ operator: logical.operator,
487
+ left: reconstruct(logical.left.value, position(logical.left)),
488
+ right: reconstruct(logical.right.value, position(logical.right)),
489
+ type: "BOOL",
490
+ span,
491
+ },
492
+ path,
493
+ type,
494
+ );
495
+ }
496
+ const select = selects.get(root);
497
+ if (select) {
498
+ const branch = (item: Assign) => reconstruct(item.value, position(item));
499
+ return projectReconstruction(
500
+ {
501
+ kind: "select",
502
+ condition: reconstruct(select.test.condition, position(select.test)),
503
+ // biome-ignore lint/suspicious/noThenProperty: a reconstructed `?:` is data, not a thenable.
504
+ then: branch(select.then),
505
+ else: branch(select.else),
506
+ type: select.then.value.type,
507
+ span,
508
+ },
509
+ path,
510
+ type,
511
+ );
512
+ }
513
+ const defined = definitions.get(root) ?? [];
514
+ const [only] = defined;
515
+ if (defined.length === 1 && only?.kind === "invoke") {
516
+ return projectReconstruction(
517
+ {
518
+ kind: "call",
519
+ call: only,
520
+ path: [],
521
+ type: typeOf(root) ?? type,
522
+ span: only.span,
523
+ },
524
+ path,
525
+ type,
526
+ );
527
+ }
528
+ if (defined.length === 1 && only && wholeAssign(only, root)) {
529
+ const value = only.value;
530
+ if (value.kind === "load") {
531
+ return place(
532
+ value.root,
533
+ [...segments(value.path ?? [], position(only)), ...path],
534
+ position(only),
535
+ at,
536
+ type,
537
+ value.span,
538
+ );
539
+ }
540
+ return projectReconstruction(
541
+ reconstruct(value, position(only)),
542
+ path,
543
+ type,
544
+ );
545
+ }
546
+ return parts(root, defined, path, type, span);
547
+ };
548
+
549
+ /** A temporary built field by field or element by element: a record or array literal, or an `.out` snapshot. */
550
+ const parts = (
551
+ root: string,
552
+ defined: readonly CoreStatement[],
553
+ path: readonly ReconstructedSegment[],
554
+ type: string,
555
+ span: SourceSpan,
556
+ ): Reconstruction => {
557
+ const fields = new Map<string, Assign>();
558
+ const items = new Map<number, Assign>();
559
+ for (const item of defined) {
560
+ const [segment, ...rest] =
561
+ item.kind === "assign" ? (item.path ?? []) : [];
562
+ const index =
563
+ segment?.kind === "index" ? constantIndex(segment.value) : undefined;
564
+ if (item.kind !== "assign" || !segment || rest.length) {
565
+ return opaque("a value set in several places", type, span);
566
+ }
567
+ if (segment.kind === "field" && !fields.has(segment.name)) {
568
+ fields.set(segment.name, item);
569
+ } else if (index !== undefined && !items.has(index) && !fields.size) {
570
+ items.set(index, item);
571
+ } else {
572
+ return opaque("a value set in several places", type, span);
573
+ }
574
+ }
575
+ const value = (item: Assign) => reconstruct(item.value, position(item));
576
+ if (items.size) {
577
+ const indexes = [...items.keys()].sort((a, b) => a - b);
578
+ const lower = indexes[0] ?? 0;
579
+ const contiguous = indexes.every(
580
+ (index, offset) => index === lower + offset,
581
+ );
582
+ if (!contiguous) {
583
+ return opaque("an array with gaps", type, span);
584
+ }
585
+ return projectReconstruction(
586
+ {
587
+ kind: "array",
588
+ lower,
589
+ items: indexes.flatMap((index) => {
590
+ const item = items.get(index);
591
+ return item ? [value(item)] : [];
592
+ }),
593
+ type: typeOf(root) ?? type,
594
+ span,
595
+ },
596
+ path,
597
+ type,
598
+ );
599
+ }
600
+ if (!fields.size) {
601
+ return opaque("a value with no definition", type, span);
602
+ }
603
+ return projectReconstruction(
604
+ {
605
+ kind: "record",
606
+ fields: Object.fromEntries(
607
+ [...fields].map(([name, item]) => [name, value(item)]),
608
+ ),
609
+ type: typeOf(root) ?? type,
610
+ span,
611
+ },
612
+ path,
613
+ type,
614
+ );
615
+ };
616
+
617
+ const reconstruct = (
618
+ expression: CoreExpression,
619
+ at: number,
620
+ ): Reconstruction => {
621
+ const { type, span } = expression;
622
+ switch (expression.kind) {
623
+ case "constant":
624
+ return { kind: "constant", value: expression.value, type, span };
625
+ case "borrow":
626
+ return place(
627
+ expression.place.root,
628
+ segments(expression.place.path, at),
629
+ at,
630
+ at,
631
+ type,
632
+ span,
633
+ );
634
+ case "load":
635
+ return place(
636
+ expression.root,
637
+ segments(expression.path ?? [], at),
638
+ at,
639
+ at,
640
+ type,
641
+ span,
642
+ );
643
+ case "unary":
644
+ if (expression.operator === "clock") {
645
+ return { kind: "clock", type, span };
646
+ }
647
+ return {
648
+ kind: "unary",
649
+ operator: expression.operator,
650
+ operand: reconstruct(expression.operand, at),
651
+ type,
652
+ span,
653
+ };
654
+ case "convert":
655
+ return {
656
+ kind: "convert",
657
+ policy: expression.policy,
658
+ operand: reconstruct(expression.operand, at),
659
+ type,
660
+ span,
661
+ };
662
+ case "binary": {
663
+ const left = reconstruct(expression.left, at);
664
+ const right = reconstruct(expression.right, at);
665
+ if (expression.operator === "and" || expression.operator === "or") {
666
+ return {
667
+ kind: "logical",
668
+ operator: expression.operator,
669
+ left,
670
+ right,
671
+ type,
672
+ span,
673
+ };
674
+ }
675
+ return {
676
+ kind: "binary",
677
+ operator: expression.operator,
678
+ ...(expression.policy && { policy: expression.policy }),
679
+ left,
680
+ right,
681
+ type,
682
+ span,
683
+ };
684
+ }
685
+ }
686
+ };
687
+
688
+ const job =
689
+ "inputs" in routine && routine.job
690
+ ? {
691
+ busy: routine.state.find((field) => field.name === "busy")?.id,
692
+ step: routine.state.find((field) => field.name === "step")?.id,
693
+ }
694
+ : undefined;
695
+ const isField = (node: Reconstruction, field: string | undefined): boolean =>
696
+ field !== undefined &&
697
+ node.kind === "read" &&
698
+ node.root === field &&
699
+ !node.path.length;
700
+ /** The job dispatcher's `IF NOT busy THEN RETURN`. */
701
+ const busyGuard = (item: CoreStatement): boolean => {
702
+ if (
703
+ item.kind !== "if" ||
704
+ item.else.length ||
705
+ item.then.length !== 1 ||
706
+ item.then[0]?.kind !== "return"
707
+ ) {
708
+ return false;
709
+ }
710
+ const test = reconstruct(item.condition, position(item));
711
+ return (
712
+ test.kind === "unary" &&
713
+ test.operator === "not" &&
714
+ isField(test.operand, job?.busy)
715
+ );
716
+ };
717
+ /** The dispatcher's `switch` on `step`. */
718
+ const stepSwitch = (item: CoreStatement): boolean =>
719
+ item.kind === "switch" &&
720
+ isField(reconstruct(item.value, position(item)), job?.step);
721
+
722
+ const statements = new Map<CoreStatement, StatementConditions>();
723
+ const loops: LoopConditions[] = [];
724
+ type Mode = "plain" | "jobDispatcher" | "jobTransitions";
725
+
726
+ const sequence = (
727
+ items: readonly CoreStatement[],
728
+ conditions: Conjunction,
729
+ loop: number | null,
730
+ mode: Mode,
731
+ ): Exits => {
732
+ const guards: PathCondition[] = [];
733
+ const exits: Exits[] = [];
734
+ for (const item of items) {
735
+ const here = [...conditions, ...guards];
736
+ statements.set(item, {
737
+ position: position(item),
738
+ conditions: here,
739
+ loop,
740
+ });
741
+ if (mode === "jobDispatcher" && busyGuard(item)) {
742
+ for (const branch of nestedBodies(item)) {
743
+ sequence(branch, here, loop, "plain");
744
+ }
745
+ guards.push({ kind: "jobBusy" });
746
+ continue;
747
+ }
748
+ if (
749
+ mode === "jobDispatcher" &&
750
+ item.kind === "for" &&
751
+ item.body.some(stepSwitch)
752
+ ) {
753
+ sequence(item.body, here, loop, "jobTransitions");
754
+ continue;
755
+ }
756
+ const own = statementExits(item, here, loop, mode);
757
+ exits.push(prefixed(guards, own));
758
+ const any = [...own.returns, ...own.breaks, ...own.continues];
759
+ if (any.length) {
760
+ guards.push({ kind: "exits", any });
761
+ }
762
+ }
763
+ return merged(...exits);
764
+ };
765
+
766
+ const statementExits = (
767
+ item: CoreStatement,
768
+ here: Conjunction,
769
+ loop: number | null,
770
+ mode: Mode,
771
+ ): Exits => {
772
+ const at = position(item);
773
+ switch (item.kind) {
774
+ case "return":
775
+ return { ...noExits, returns: [[]] };
776
+ case "break":
777
+ return { ...noExits, breaks: [[]] };
778
+ case "continue":
779
+ return { ...noExits, continues: [[]] };
780
+ case "if": {
781
+ const lowered = synthetic.get(item);
782
+ const tested = lowered ? lowered.left.value : item.condition;
783
+ const test = reconstruct(tested, lowered ? position(lowered.left) : at);
784
+ const holds = lowered?.operator !== "or";
785
+ const condition = (truth: boolean): PathCondition => ({
786
+ kind: "test",
787
+ test,
788
+ holds: truth === holds,
789
+ at,
790
+ span: tested.span,
791
+ });
792
+ const yes = condition(true);
793
+ const no = condition(false);
794
+ return merged(
795
+ prefixed([yes], sequence(item.then, [...here, yes], loop, "plain")),
796
+ prefixed([no], sequence(item.else, [...here, no], loop, "plain")),
797
+ );
798
+ }
799
+ case "switch": {
800
+ const test = reconstruct(item.value, at);
801
+ const steps = mode === "jobTransitions" && stepSwitch(item);
802
+ const inside = steps
803
+ ? here.filter((condition) => condition.kind !== "jobBusy")
804
+ : here;
805
+ const branch = (
806
+ condition: PathCondition,
807
+ body: readonly CoreStatement[],
808
+ ) =>
809
+ prefixed(
810
+ [condition],
811
+ sequence(body, [...inside, condition], loop, "plain"),
812
+ );
813
+ const cases = item.cases.map((entry) => {
814
+ const [value] = entry.values;
815
+ const step =
816
+ steps && value?.kind === "integer" && entry.values.length === 1
817
+ ? Number(value.value)
818
+ : undefined;
819
+ return branch(
820
+ step === undefined
821
+ ? {
822
+ kind: "cases",
823
+ test,
824
+ values: entry.values,
825
+ member: true,
826
+ at,
827
+ span: item.value.span,
828
+ }
829
+ : { kind: "job", step },
830
+ entry.body,
831
+ );
832
+ });
833
+ const fallback = branch(
834
+ {
835
+ kind: "cases",
836
+ test,
837
+ values: item.cases.flatMap((entry) => entry.values),
838
+ member: false,
839
+ at,
840
+ span: item.value.span,
841
+ },
842
+ item.fallback,
843
+ );
844
+ return merged(...cases, fallback);
845
+ }
846
+ case "for": {
847
+ const id = loops.length;
848
+ const counter = typeOf(item.counter) ?? "DINT";
849
+ const bound = (value: Constant): Reconstruction => ({
850
+ kind: "constant",
851
+ value,
852
+ type: counter,
853
+ span: item.span,
854
+ });
855
+ const slot: LoopConditions = {
856
+ statement: item,
857
+ position: at,
858
+ counter: item.counter,
859
+ first: item.dynamic
860
+ ? reconstruct(item.dynamic.start, at)
861
+ : bound(item.start),
862
+ limit: item.dynamic
863
+ ? reconstruct(item.dynamic.limit, at)
864
+ : bound(item.limit),
865
+ exclusive: item.dynamic?.exclusive === true,
866
+ step: BigInt(item.step),
867
+ maxIterations: item.maxIterations,
868
+ breaks: [],
869
+ returns: false,
870
+ parent: loop,
871
+ };
872
+ loops.push(slot);
873
+ const body = sequence(
874
+ item.body,
875
+ [...here, { kind: "loop", loop: id }],
876
+ id,
877
+ "plain",
878
+ );
879
+ loops[id] = {
880
+ ...slot,
881
+ breaks: body.breaks,
882
+ returns: body.returns.length > 0,
883
+ };
884
+ return body.returns.length
885
+ ? { ...noExits, returns: [[{ kind: "loopReturns", loop: id }]] }
886
+ : noExits;
887
+ }
888
+ default:
889
+ return noExits;
890
+ }
891
+ };
892
+
893
+ sequence(routine.body, [], null, job ? "jobDispatcher" : "plain");
894
+ return { statements, loops, reconstruct };
895
+ }