@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,1465 @@
1
+ import type {
2
+ Constant,
3
+ CoreExpression,
4
+ CoreFunction,
5
+ CoreFunctionBlock,
6
+ CorePath,
7
+ CoreStatement,
8
+ PathCondition,
9
+ PlcType,
10
+ ReconstructedSegment,
11
+ Reconstruction,
12
+ RoutineConditions,
13
+ SourceSpan,
14
+ } from "@tsplc/compiler/ir";
15
+ import {
16
+ instancedBlock,
17
+ nestedBodies,
18
+ pathConditions,
19
+ projectReconstruction,
20
+ standardBlocks,
21
+ } from "@tsplc/compiler/ir";
22
+ import { createExplainer } from "@tsplc/debug/explain";
23
+ import type {
24
+ ExplainAssignment,
25
+ ExplainCall,
26
+ ExplainCondition,
27
+ ExplainExpression,
28
+ ExplainFile,
29
+ ExplainFlags,
30
+ ExplainLocal,
31
+ } from "@tsplc/debug/explain-file";
32
+ import type { DebugManifest, SourceRange } from "@tsplc/debug/manifest";
33
+ import { createPaths } from "@tsplc/debug/paths";
34
+ import { serviceOfPath } from "@tsplc/server";
35
+ import { blockInstances, type InstancePath, storagePath } from "./debug";
36
+ import { publishedAccess } from "./global-lists";
37
+ import { serviceBlock } from "./http";
38
+ import { constantValue } from "./manifest";
39
+ import type { Sources } from "./sources";
40
+ import { moduleName } from "./storage";
41
+ import type { EmissionContext } from "./symbols";
42
+ import { variablesById } from "./task-access";
43
+
44
+ type Routine = CoreFunction | CoreFunctionBlock;
45
+ type Record = Pick<
46
+ ExplainAssignment,
47
+ "routine" | "position" | "conditions" | "site"
48
+ >;
49
+
50
+ /** One routine as one instance runs it: a function, or a block body or method on one block instance. */
51
+ interface Row {
52
+ readonly index: number;
53
+ readonly routine: Routine;
54
+ readonly conditions: RoutineConditions;
55
+ /** The block instance's storage path. */
56
+ readonly instance: string | null;
57
+ /** The variables of the block the routine runs on, which are fields of `instance`. */
58
+ readonly fields: ReadonlySet<string>;
59
+ /** The manifest job this row's block instance is. */
60
+ readonly job: number | null;
61
+ /**
62
+ * The paths, locals and calls its expressions name, each by its slot here: two instances of one
63
+ * routine then share their expressions and conditions, and differ only in these tables.
64
+ */
65
+ readonly slots: { paths: Slots; locals: Slots; calls: Slots };
66
+ }
67
+
68
+ /** A row's table of global indexes; an expression names an entry by its position here. */
69
+ class Slots {
70
+ readonly items: number[] = [];
71
+ private readonly positions = new Map<number, number>();
72
+
73
+ of(global: number): number {
74
+ const known = this.positions.get(global);
75
+ if (known !== undefined) {
76
+ return known;
77
+ }
78
+ this.positions.set(global, this.items.length);
79
+ this.items.push(global);
80
+ return this.items.length - 1;
81
+ }
82
+ }
83
+
84
+ /** A place as the debugger names it: a storage path, with a `[*]` for each dynamic index. */
85
+ interface Spelled {
86
+ readonly text: string;
87
+ readonly indexes: readonly number[];
88
+ readonly type: PlcType | undefined;
89
+ }
90
+
91
+ const aggregateKinds: ReadonlySet<PlcType["kind"]> = new Set([
92
+ "record",
93
+ "array",
94
+ "block",
95
+ ]);
96
+
97
+ /** The most source lines a statement's snippet shows; longer spans are shown by their range alone. */
98
+ const maxSnippetLines = 8;
99
+
100
+ /** The names along a path of fields and constant indexes, or nothing when an index is dynamic. */
101
+ const staticNames = (
102
+ path: readonly ReconstructedSegment[],
103
+ ): string[] | undefined => {
104
+ const names: string[] = [];
105
+ for (const segment of path) {
106
+ if (segment.kind === "field") {
107
+ names.push(segment.name);
108
+ } else if (
109
+ segment.value.kind === "constant" &&
110
+ segment.value.value.kind === "integer"
111
+ ) {
112
+ names.push(segment.value.value.value);
113
+ } else {
114
+ return undefined;
115
+ }
116
+ }
117
+ return names;
118
+ };
119
+
120
+ /** The part of a constant at a path of record fields; an element of an array stays a read of the table. */
121
+ const constantAt = (
122
+ value: Constant,
123
+ names: readonly string[],
124
+ ): Constant | undefined => {
125
+ const [name, ...rest] = names;
126
+ if (name === undefined) {
127
+ return value;
128
+ }
129
+ if (value.kind === "record") {
130
+ const field = value.fields[name];
131
+ return field && constantAt(field, rest);
132
+ }
133
+ return undefined;
134
+ };
135
+
136
+ /** A path with every index as `[*]`, so a pattern and each of its elements compare equal. */
137
+ const anyIndex = (path: string): string => path.replace(/\[-?\d+\]/g, "[*]");
138
+
139
+ /** An interning table: each distinct value once, by its JSON text. */
140
+ class Table<Value> {
141
+ readonly items: Value[] = [];
142
+ private readonly keys = new Map<string, number>();
143
+
144
+ add(value: Value): number {
145
+ const key = JSON.stringify(value);
146
+ const known = this.keys.get(key);
147
+ if (known !== undefined) {
148
+ return known;
149
+ }
150
+ this.keys.set(key, this.items.length);
151
+ this.items.push(value);
152
+ return this.items.length - 1;
153
+ }
154
+ }
155
+
156
+ /**
157
+ * Every statement of the specialized program that writes stored state, per routine instance, with
158
+ * the conditions it runs under and the expressions it evaluates, as `explain.json` holds them.
159
+ * `functionIds` are the manifest's function ids by routine; `sources` is the manifest's, so source
160
+ * ranges index the same files.
161
+ */
162
+ export function explanations(
163
+ context: EmissionContext,
164
+ manifest: DebugManifest,
165
+ sources: Sources,
166
+ functionIds: ReadonlyMap<string, number>,
167
+ ): Explanations {
168
+ const { plan, instrumentation } = context;
169
+ const program = plan.specialized;
170
+ const types = new Map(program.types.map((type) => [type.id, type]));
171
+ const variables = variablesById(program);
172
+ const blocks = new Map(program.blocks.map((block) => [block.id, block]));
173
+ const functions = new Map(program.functions.map((fn) => [fn.id, fn]));
174
+ const instances = blockInstances(program);
175
+ const access = publishedAccess(plan);
176
+
177
+ const paths = new Table<string>();
178
+ const texts = new Table<string>();
179
+ const expressions = new Table<ExplainExpression>();
180
+ const conditionTree = new Table<ExplainFile["conditions"][number]>();
181
+ /** The tree entry for a list of conditions, outermost first. */
182
+ const conditionsIndex = (list: readonly ExplainCondition[]): number | null =>
183
+ list.reduce<number | null>(
184
+ (parent, condition) => conditionTree.add({ parent, condition }),
185
+ null,
186
+ );
187
+ const sites = new Table<ExplainFile["sites"][number]>();
188
+ const rows: Row[] = [];
189
+ const routineRows: Omit<
190
+ ExplainFile["routines"][number],
191
+ "job" | "paths" | "locals" | "calls" | "loops"
192
+ >[] = [];
193
+ const loops: ExplainFile["loops"] = [];
194
+ const assignments: ExplainAssignment[] = [];
195
+ const locals: ExplainLocal[] = [];
196
+ const returns: ExplainFile["returns"] = [];
197
+ const calls: ExplainCall[] = [];
198
+ const callIndexes = new Map<Row, Map<CoreStatement, number>>();
199
+ /** The assignments each statement makes itself, in every instance that runs it. */
200
+ const recorded = new Map<CoreStatement, number[]>();
201
+ const localIndexes = new Map<string, number>();
202
+ const loopBases = new Map<Row, number>();
203
+ /** Fields that hold an object reference, with every index as `[*]`. */
204
+ const referenceFields = new Set(
205
+ (program.references?.fields ?? []).map(anyIndex),
206
+ );
207
+ /** Rows that read each path, for `writerTasks`. */
208
+ const readers = new Map<string, Set<number>>();
209
+
210
+ const range = (span: SourceSpan): SourceRange | null =>
211
+ sources.range(span) ?? null;
212
+ const text = (span: SourceSpan): number | null => {
213
+ const source = sources.range(span) && sources.text(span);
214
+ return source ? texts.add(source) : null;
215
+ };
216
+ const site = (span: SourceSpan): number | null => {
217
+ const found = range(span);
218
+ if (!found) {
219
+ return null;
220
+ }
221
+ // Generated code is mapped to the whole declaration it came from, which is no snippet.
222
+ const snippet =
223
+ found.endLine - found.line < maxSnippetLines ? text(span) : null;
224
+ return sites.add({ range: found, text: snippet });
225
+ };
226
+ const instanceText = (path: InstancePath): string =>
227
+ path
228
+ .map(({ variable, index }, position) => {
229
+ const name =
230
+ position === 0
231
+ ? (storagePath(variable) ?? variable.name)
232
+ : `.${variable.name}`;
233
+ return index === undefined ? name : `${name}[${index}]`;
234
+ })
235
+ .join("");
236
+ const jobInstances = instrumentation.jobs.map(({ block, path }) => ({
237
+ block: block.id,
238
+ instance: instanceText(path),
239
+ }));
240
+
241
+ // Routine instances: a function once, a block body or method once per block instance.
242
+ const conditionsByRoutine = new Map<string, RoutineConditions>();
243
+ const conditionsOf = (routine: Routine) => {
244
+ const known = conditionsByRoutine.get(routine.id);
245
+ if (known) {
246
+ return known;
247
+ }
248
+ const analysed = pathConditions(routine, variables);
249
+ conditionsByRoutine.set(routine.id, analysed);
250
+ return analysed;
251
+ };
252
+ const addRow = (routine: Routine, path: InstancePath | null): void => {
253
+ const block =
254
+ "inputs" in routine ? routine : blocks.get(routine.owner?.block ?? "");
255
+ const instance = path ? instanceText(path) : null;
256
+ const job = jobInstances.findIndex(
257
+ (item) => item.block === routine.id && item.instance === instance,
258
+ );
259
+ const row: Row = {
260
+ index: rows.length,
261
+ routine,
262
+ conditions: conditionsOf(routine),
263
+ instance,
264
+ fields: new Set(
265
+ block
266
+ ? [...block.inputs, ...block.outputs, ...block.state].map(
267
+ (variable) => variable.id,
268
+ )
269
+ : [],
270
+ ),
271
+ job: job < 0 ? null : job + 1,
272
+ slots: { paths: new Slots(), locals: new Slots(), calls: new Slots() },
273
+ };
274
+ rows.push(row);
275
+ const fn = "parameters" in routine ? routine : undefined;
276
+ routineRows.push({
277
+ key: routine.id,
278
+ function: functionIds.get(routine.id) ?? null,
279
+ instance: instance === null ? null : paths.add(instance),
280
+ name:
281
+ ("inputs" in routine ? routine.job?.name : undefined) ??
282
+ fn?.origin?.name ??
283
+ routine.name,
284
+ declaration: range(
285
+ ("inputs" in routine ? routine.job?.span : undefined) ?? routine.span,
286
+ ),
287
+ });
288
+ };
289
+ for (const fn of program.functions) {
290
+ const owner = fn.owner?.block;
291
+ if (owner === undefined) {
292
+ addRow(fn, null);
293
+ continue;
294
+ }
295
+ for (const path of instances.get(owner) ?? []) {
296
+ addRow(fn, path);
297
+ }
298
+ }
299
+ for (const block of program.blocks) {
300
+ if (block.standard || serviceBlock(block) || !block.body.length) {
301
+ continue;
302
+ }
303
+ for (const path of instances.get(block.id) ?? []) {
304
+ addRow(block, path);
305
+ }
306
+ }
307
+
308
+ /** The storage path of a place in a row, or nothing for a temporary, local or parameter. */
309
+ const spell = (
310
+ row: Row,
311
+ root: string,
312
+ path: readonly ReconstructedSegment[],
313
+ ): Spelled | undefined => {
314
+ const variable = variables.get(root);
315
+ if (!variable) {
316
+ return undefined;
317
+ }
318
+ const base = (): string | undefined => {
319
+ if (row.fields.has(root)) {
320
+ return row.instance === null
321
+ ? undefined
322
+ : `${row.instance}.${variable.name}`;
323
+ }
324
+ if (variable.storage === "constant") {
325
+ return `${moduleName(variable)}.${variable.name}`;
326
+ }
327
+ return storagePath(variable);
328
+ };
329
+ const start = base();
330
+ return start === undefined
331
+ ? undefined
332
+ : extend(
333
+ row,
334
+ { text: start, indexes: [], type: types.get(variable.type) },
335
+ path,
336
+ );
337
+ };
338
+
339
+ /** A spelled place followed further along a path evaluated in `row`. */
340
+ const extend = (
341
+ row: Row,
342
+ spelled: Spelled,
343
+ path: readonly ReconstructedSegment[],
344
+ ): Spelled => {
345
+ let { text: current, type } = spelled;
346
+ const indexes = [...spelled.indexes];
347
+ for (const segment of path) {
348
+ if (segment.kind === "field") {
349
+ if (type?.kind === "block") {
350
+ // Block outputs are fields of the instance itself, so its `out` view adds no segment.
351
+ if (segment.name === "out") {
352
+ type = type.output ? types.get(type.output) : undefined;
353
+ continue;
354
+ }
355
+ const block = blocks.get(type.block);
356
+ const field = block
357
+ ? [...block.inputs, ...block.outputs, ...block.state].find(
358
+ (variable) => variable.name === segment.name,
359
+ )
360
+ : undefined;
361
+ type = field ? types.get(field.type) : undefined;
362
+ } else if (type?.kind === "record") {
363
+ const field = type.fields.find((item) => item.name === segment.name);
364
+ type = field ? types.get(field.type) : undefined;
365
+ } else {
366
+ type = undefined;
367
+ }
368
+ current += `.${segment.name}`;
369
+ continue;
370
+ }
371
+ type = type?.kind === "array" ? types.get(type.element) : undefined;
372
+ const value = segment.value;
373
+ if (value.kind === "constant" && value.value.kind === "integer") {
374
+ current += `[${value.value.value}]`;
375
+ } else {
376
+ current += "[*]";
377
+ indexes.push(expression(row, value));
378
+ }
379
+ }
380
+ return { text: current, indexes, type };
381
+ };
382
+
383
+ const localIndex = (row: Row, root: string): number => {
384
+ const key = `${row.index}:${root}`;
385
+ const known = localIndexes.get(key);
386
+ if (known !== undefined) {
387
+ return known;
388
+ }
389
+ const variable = variables.get(root);
390
+ localIndexes.set(key, locals.length);
391
+ locals.push({
392
+ routine: row.index,
393
+ name: variable?.name ?? root,
394
+ parameter: variable?.storage === "parameter",
395
+ reference: false,
396
+ definitions: [],
397
+ });
398
+ return locals.length - 1;
399
+ };
400
+
401
+ const opaque = (
402
+ reason: string,
403
+ type: string,
404
+ reads: readonly number[] = [],
405
+ ): number =>
406
+ expressions.add({
407
+ kind: "opaque",
408
+ text: texts.add(reason),
409
+ reads: [...reads],
410
+ type,
411
+ });
412
+
413
+ const expression = (row: Row, node: Reconstruction): number => {
414
+ switch (node.kind) {
415
+ case "read": {
416
+ // A constant table read at fixed indexes is its value; there is nothing to read live.
417
+ const table = variables.get(node.root);
418
+ const names = staticNames(node.path);
419
+ const fixed =
420
+ table?.storage === "constant" && table.initial && names
421
+ ? constantAt(table.initial, names)
422
+ : undefined;
423
+ if (fixed) {
424
+ return expressions.add({
425
+ kind: "constant",
426
+ value: constantValue(fixed),
427
+ type: node.type,
428
+ });
429
+ }
430
+ const spelled = spell(row, node.root, node.path);
431
+ if (!spelled) {
432
+ return opaque("not stored", node.type);
433
+ }
434
+ const path = row.slots.paths.of(paths.add(spelled.text));
435
+ const readBy = readers.get(spelled.text) ?? new Set<number>();
436
+ readBy.add(row.index);
437
+ readers.set(spelled.text, readBy);
438
+ const read = expressions.add(
439
+ spelled.indexes.length
440
+ ? {
441
+ kind: "pattern",
442
+ path,
443
+ indexes: [...spelled.indexes],
444
+ capturedAt: node.capturedAt,
445
+ ...(node.interleaved && { interleaved: true as const }),
446
+ type: node.type,
447
+ }
448
+ : {
449
+ kind: "read",
450
+ path,
451
+ capturedAt: node.capturedAt,
452
+ ...(node.interleaved && { interleaved: true as const }),
453
+ type: node.type,
454
+ },
455
+ );
456
+ // A field holding an object reference holds the object's id: show the object.
457
+ return referenceFields.has(anyIndex(spelled.text))
458
+ ? expressions.add({ kind: "reference", operand: read })
459
+ : read;
460
+ }
461
+ case "local": {
462
+ const names = staticNames(node.path);
463
+ return names
464
+ ? expressions.add({
465
+ kind: "local",
466
+ local: row.slots.locals.of(localIndex(row, node.root)),
467
+ path: names,
468
+ at: node.at,
469
+ type: node.type,
470
+ })
471
+ : opaque("a local at a dynamic index", node.type);
472
+ }
473
+ case "parameter": {
474
+ const names = staticNames(node.path);
475
+ if (!names) {
476
+ return opaque("a parameter at a dynamic index", node.type);
477
+ }
478
+ const written = writesThrough.has(
479
+ `${row.routine.id}#${node.parameter}`,
480
+ );
481
+ return expressions.add({
482
+ kind: "parameter",
483
+ parameter: node.parameter,
484
+ path: names,
485
+ at: node.at,
486
+ local: written
487
+ ? row.slots.locals.of(localIndex(row, node.root))
488
+ : null,
489
+ type: node.type,
490
+ });
491
+ }
492
+ case "call": {
493
+ const call = callIndexes.get(row)?.get(node.call);
494
+ return call === undefined
495
+ ? opaque("a call that isn't traced", node.type)
496
+ : expressions.add({
497
+ kind: "call",
498
+ call: row.slots.calls.of(call),
499
+ path: [...node.path],
500
+ type: node.type,
501
+ });
502
+ }
503
+ case "constant":
504
+ return expressions.add({
505
+ kind: "constant",
506
+ value: constantValue(node.value),
507
+ type: node.type,
508
+ });
509
+ case "clock":
510
+ return expressions.add({ kind: "clock", type: node.type });
511
+ case "unary":
512
+ return expressions.add({
513
+ kind: "unary",
514
+ operator: node.operator,
515
+ operand: expression(row, node.operand),
516
+ type: node.type,
517
+ });
518
+ case "binary":
519
+ return expressions.add({
520
+ kind: "binary",
521
+ operator: node.operator,
522
+ ...(node.policy && { policy: node.policy }),
523
+ left: expression(row, node.left),
524
+ right: expression(row, node.right),
525
+ type: node.type,
526
+ });
527
+ case "convert":
528
+ return expressions.add({
529
+ kind: "convert",
530
+ policy: node.policy,
531
+ operand: expression(row, node.operand),
532
+ type: node.type,
533
+ });
534
+ case "logical":
535
+ return expressions.add({
536
+ kind: "logical",
537
+ operator: node.operator,
538
+ left: expression(row, node.left),
539
+ right: expression(row, node.right),
540
+ });
541
+ case "select":
542
+ return expressions.add({
543
+ kind: "select",
544
+ condition: expression(row, node.condition),
545
+ // biome-ignore lint/suspicious/noThenProperty: a `?:` branch is data, not a thenable.
546
+ then: expression(row, node.then),
547
+ else: expression(row, node.else),
548
+ type: node.type,
549
+ });
550
+ case "record":
551
+ return expressions.add({
552
+ kind: "record",
553
+ fields: Object.fromEntries(
554
+ Object.entries(node.fields).map(([name, value]) => [
555
+ name,
556
+ expression(row, value),
557
+ ]),
558
+ ),
559
+ type: node.type,
560
+ });
561
+ case "array":
562
+ return expressions.add({
563
+ kind: "array",
564
+ lower: node.lower,
565
+ items: node.items.map((item) => expression(row, item)),
566
+ type: node.type,
567
+ });
568
+ case "opaque":
569
+ return opaque(
570
+ node.reason,
571
+ node.type,
572
+ node.reads.map((read) => expression(row, read)),
573
+ );
574
+ }
575
+ };
576
+
577
+ const condition = (row: Row, item: PathCondition): ExplainCondition => {
578
+ switch (item.kind) {
579
+ case "test":
580
+ return {
581
+ kind: "test",
582
+ test: expression(row, item.test),
583
+ holds: item.holds,
584
+ at: item.at,
585
+ text: text(item.span),
586
+ };
587
+ case "cases":
588
+ return {
589
+ kind: "cases",
590
+ test: expression(row, item.test),
591
+ values: item.values.map(constantValue),
592
+ member: item.member,
593
+ at: item.at,
594
+ text: text(item.span),
595
+ };
596
+ case "exits":
597
+ return {
598
+ kind: "exits",
599
+ any: item.any.map((all) => all.map((part) => condition(row, part))),
600
+ };
601
+ case "loop":
602
+ case "loopReturns":
603
+ // A loop by its index among the row's loops.
604
+ return { kind: item.kind, loop: item.loop };
605
+ case "job":
606
+ return { kind: "job", step: item.step };
607
+ case "jobBusy":
608
+ return { kind: "jobBusy" };
609
+ }
610
+ };
611
+
612
+ // A routine writes through a by-reference parameter when it assigns it, or passes it on to a
613
+ // routine that writes through the parameter it receives it as.
614
+ const parameterIndex = (routine: Routine, root: string): number =>
615
+ "parameters" in routine
616
+ ? routine.parameters.findIndex((parameter) => parameter.id === root)
617
+ : -1;
618
+ const calleeParameters = (
619
+ item: CoreStatement,
620
+ ): { routine: string; arguments: readonly CoreExpression[] } | undefined => {
621
+ if (item.kind === "invoke") {
622
+ return { routine: item.function, arguments: item.arguments };
623
+ }
624
+ if (item.kind !== "blockUpdate") {
625
+ return undefined;
626
+ }
627
+ const block = instancedBlock(
628
+ variables.get(item.instance)?.type ?? "",
629
+ types,
630
+ );
631
+ const called = block && blocks.get(block.block);
632
+ return called
633
+ ? {
634
+ routine: called.id,
635
+ arguments: called.inputs.flatMap((input) => {
636
+ const value = item.inputs[input.name];
637
+ return value ? [value] : [];
638
+ }),
639
+ }
640
+ : undefined;
641
+ };
642
+ const statementsOf = (items: readonly CoreStatement[]): CoreStatement[] =>
643
+ items.flatMap((item) => [
644
+ item,
645
+ ...nestedBodies(item).flatMap(statementsOf),
646
+ ]);
647
+ const writesThrough = new Set<string>();
648
+ const allRoutines: Routine[] = [...program.functions, ...program.blocks];
649
+ const propagate = (): boolean => {
650
+ const added = allRoutines.flatMap((routine) =>
651
+ statementsOf(routine.body).flatMap((item) => {
652
+ const passed = calleeParameters(item);
653
+ const indexes = [
654
+ ...(item.kind === "assign"
655
+ ? [parameterIndex(routine, item.root)]
656
+ : []),
657
+ ...(passed?.arguments ?? []).flatMap((argument, index) =>
658
+ argument.kind === "borrow" &&
659
+ writesThrough.has(`${passed?.routine}#${index}`)
660
+ ? [parameterIndex(routine, argument.place.root)]
661
+ : [],
662
+ ),
663
+ ];
664
+ return indexes
665
+ .filter((index) => index >= 0)
666
+ .map((index) => `${routine.id}#${index}`)
667
+ .filter((key) => !writesThrough.has(key));
668
+ }),
669
+ );
670
+ for (const key of added) {
671
+ writesThrough.add(key);
672
+ }
673
+ return added.length > 0;
674
+ };
675
+ while (propagate()) {
676
+ // Each round adds the parameters that pass a written-through place on.
677
+ }
678
+
679
+ const segments = (
680
+ row: Row,
681
+ path: CorePath,
682
+ at: number,
683
+ ): ReconstructedSegment[] =>
684
+ path.map((segment) =>
685
+ segment.kind === "field"
686
+ ? segment
687
+ : {
688
+ kind: "index",
689
+ value: row.conditions.reconstruct(segment.value, at),
690
+ },
691
+ );
692
+ const written = (spelled: Spelled): ExplainAssignment["writes"] =>
693
+ spelled.indexes.length
694
+ ? {
695
+ kind: "pattern",
696
+ path: paths.add(spelled.text),
697
+ indexes: [...spelled.indexes],
698
+ }
699
+ : { kind: "path", path: paths.add(spelled.text) };
700
+ const loopOf = (row: Row, loop: number | null): number | null =>
701
+ loop === null ? null : (loopBases.get(row) ?? 0) + loop;
702
+ const typeIsAggregate = (spelled: Spelled): boolean =>
703
+ spelled.type !== undefined && aggregateKinds.has(spelled.type.kind);
704
+
705
+ /** The receiver of a call in a row: a block instance's path, or none for a function. */
706
+ const receiver = (
707
+ row: Row,
708
+ instance: string | undefined,
709
+ index: CoreExpression | undefined,
710
+ at: number,
711
+ callee: string,
712
+ ): ExplainCall["receiver"] => {
713
+ if (instance === undefined) {
714
+ return functions.get(callee)?.owner && row.instance !== null
715
+ ? { kind: "path", path: paths.add(row.instance) }
716
+ : { kind: "none" };
717
+ }
718
+ const spelled = spell(
719
+ row,
720
+ instance,
721
+ index
722
+ ? [{ kind: "index", value: row.conditions.reconstruct(index, at) }]
723
+ : [],
724
+ );
725
+ if (!spelled) {
726
+ return { kind: "none" };
727
+ }
728
+ return spelled.indexes.length
729
+ ? {
730
+ kind: "pattern",
731
+ path: paths.add(spelled.text),
732
+ indexes: [...spelled.indexes],
733
+ }
734
+ : { kind: "path", path: paths.add(spelled.text) };
735
+ };
736
+
737
+ // Calls get their indexes first, so expressions can name call results.
738
+ for (const row of rows) {
739
+ const indexes = new Map<CoreStatement, number>();
740
+ for (const item of row.conditions.statements.keys()) {
741
+ if (item.kind === "invoke" || item.kind === "blockUpdate") {
742
+ indexes.set(item, indexes.size + calls.length);
743
+ }
744
+ }
745
+ callIndexes.set(row, indexes);
746
+ for (const call of indexes.values()) {
747
+ row.slots.calls.of(call);
748
+ }
749
+ calls.push(
750
+ ...[...indexes.keys()].map(
751
+ (): ExplainCall => ({
752
+ routine: row.index,
753
+ position: 0,
754
+ conditions: null,
755
+ site: null,
756
+ callee: "",
757
+ receiver: { kind: "none" },
758
+ arguments: [],
759
+ loop: null,
760
+ }),
761
+ ),
762
+ );
763
+ loopBases.set(row, loops.length);
764
+ for (const loop of row.conditions.loops) {
765
+ loops.push({
766
+ routine: row.index,
767
+ position: loop.position,
768
+ counter: 0,
769
+ first: 0,
770
+ limit: 0,
771
+ exclusive: loop.exclusive,
772
+ step: 0,
773
+ maxIterations: loop.maxIterations,
774
+ breaks: [],
775
+ parent: null,
776
+ site: site(loop.statement.span),
777
+ });
778
+ }
779
+ }
780
+
781
+ for (const row of rows) {
782
+ const { routine, conditions } = row;
783
+ const base = loopBases.get(row) ?? 0;
784
+ conditions.loops.forEach((loop, index) => {
785
+ const counter = variables.get(loop.counter);
786
+ const slot = loops[base + index];
787
+ if (!slot) {
788
+ return;
789
+ }
790
+ loops[base + index] = {
791
+ ...slot,
792
+ counter: expression(
793
+ row,
794
+ conditions.reconstruct(
795
+ {
796
+ kind: "load",
797
+ root: loop.counter,
798
+ type: counter?.type ?? "DINT",
799
+ span: loop.statement.span,
800
+ },
801
+ loop.position,
802
+ ),
803
+ ),
804
+ first: expression(row, loop.first),
805
+ limit: expression(row, loop.limit),
806
+ step: expressions.add({
807
+ kind: "constant",
808
+ value: Number(loop.step),
809
+ type: counter?.type ?? "DINT",
810
+ }),
811
+ breaks: loop.breaks.map((all) =>
812
+ all.map((part) => condition(row, part)),
813
+ ),
814
+ parent: loop.parent === null ? null : base + loop.parent,
815
+ };
816
+ });
817
+ const block = "inputs" in routine ? routine : undefined;
818
+ for (const [item, flow] of conditions.statements) {
819
+ const first = assignments.length;
820
+ const at = flow.position;
821
+ const record: Record = {
822
+ routine: row.index,
823
+ position: at,
824
+ conditions: conditionsIndex(
825
+ flow.conditions.map((part) => condition(row, part)),
826
+ ),
827
+ site: site(item.span),
828
+ };
829
+ const loop = loopOf(row, flow.loop);
830
+ const reconstruct = (value: CoreExpression) =>
831
+ expression(row, conditions.reconstruct(value, at));
832
+ /** A write of `value` to `root`: stored, a local's definition, or nothing for a temporary. */
833
+ const write = (
834
+ root: string,
835
+ path: CorePath,
836
+ kind: "assign" | "call" | "counter",
837
+ value: number | null,
838
+ ): void => {
839
+ const variable = variables.get(root);
840
+ const parameter = parameterIndex(routine, root);
841
+ const local =
842
+ variable?.storage === "local" &&
843
+ routine.locals.some((candidate) => candidate.id === root);
844
+ const temporary = local && root.includes(":temporary:");
845
+ if (temporary) {
846
+ return;
847
+ }
848
+ if (local || parameter >= 0) {
849
+ const names = staticNames(segments(row, path, at));
850
+ const target = locals[localIndex(row, root)];
851
+ target?.definitions.push({
852
+ ...record,
853
+ kind: kind === "counter" ? "counter" : "assign",
854
+ path: names ?? [],
855
+ value: names ? value : null,
856
+ call: null,
857
+ loop,
858
+ });
859
+ return;
860
+ }
861
+ const spelled = spell(row, root, segments(row, path, at));
862
+ if (!spelled) {
863
+ return;
864
+ }
865
+ assignments.push({
866
+ ...record,
867
+ kind,
868
+ writes: written(spelled),
869
+ whole: typeIsAggregate(spelled),
870
+ value,
871
+ block: null,
872
+ via: [],
873
+ loop,
874
+ });
875
+ };
876
+ /** A local or temporary a call borrows, which the callee writes through. */
877
+ const borrowed = (
878
+ call: number,
879
+ argument: CoreExpression,
880
+ index: number,
881
+ callee: string,
882
+ ) => {
883
+ if (
884
+ argument.kind !== "borrow" ||
885
+ !writesThrough.has(`${callee}#${index}`)
886
+ ) {
887
+ return;
888
+ }
889
+ const root = argument.place.root;
890
+ const isLocal =
891
+ routine.locals.some((candidate) => candidate.id === root) &&
892
+ !root.includes(":temporary:");
893
+ if (!isLocal && parameterIndex(routine, root) < 0) {
894
+ return;
895
+ }
896
+ const names = staticNames(segments(row, argument.place.path, at));
897
+ locals[localIndex(row, root)]?.definitions.push({
898
+ ...record,
899
+ kind: "borrowed",
900
+ path: names ?? [],
901
+ value: null,
902
+ call,
903
+ loop,
904
+ });
905
+ };
906
+ switch (item.kind) {
907
+ case "assign":
908
+ write(item.root, item.path ?? [], "assign", reconstruct(item.value));
909
+ break;
910
+ case "invoke": {
911
+ const call = callIndexes.get(row)?.get(item) ?? 0;
912
+ calls[call] = {
913
+ ...record,
914
+ callee: item.function,
915
+ receiver: receiver(
916
+ row,
917
+ item.instance,
918
+ item.index,
919
+ at,
920
+ item.function,
921
+ ),
922
+ arguments: item.arguments.map((argument) => reconstruct(argument)),
923
+ loop,
924
+ };
925
+ item.arguments.forEach((argument, index) => {
926
+ borrowed(call, argument, index, item.function);
927
+ });
928
+ if (item.destination) {
929
+ const result = functions.get(item.function)?.result ?? "BOOL";
930
+ write(
931
+ item.destination,
932
+ [],
933
+ "call",
934
+ expressions.add({ kind: "call", call, path: [], type: result }),
935
+ );
936
+ }
937
+ break;
938
+ }
939
+ case "blockUpdate": {
940
+ const call = callIndexes.get(row)?.get(item) ?? 0;
941
+ const instance = variables.get(item.instance);
942
+ const type = instancedBlock(instance?.type ?? "", types);
943
+ const called = type && blocks.get(type.block);
944
+ const target = receiver(
945
+ row,
946
+ item.instance,
947
+ item.index,
948
+ at,
949
+ called?.id ?? "",
950
+ );
951
+ const spelled = spell(
952
+ row,
953
+ item.instance,
954
+ item.index
955
+ ? [
956
+ {
957
+ kind: "index",
958
+ value: conditions.reconstruct(item.index, at),
959
+ },
960
+ ]
961
+ : [],
962
+ );
963
+ calls[call] = {
964
+ ...record,
965
+ callee: called?.id ?? "",
966
+ receiver: target,
967
+ arguments: (called?.inputs ?? []).flatMap((input) => {
968
+ const value = item.inputs[input.name];
969
+ return value ? [reconstruct(value)] : [];
970
+ }),
971
+ loop,
972
+ };
973
+ if (!called || !spelled) {
974
+ break;
975
+ }
976
+ if (called.standard) {
977
+ const native = standardBlocks[called.standard];
978
+ const elapsed = native.outputs.some(([name]) => name === "elapsed")
979
+ ? extend(row, spelled, [{ kind: "field", name: "elapsed" }])
980
+ : undefined;
981
+ assignments.push({
982
+ ...record,
983
+ kind: "block",
984
+ writes: written(spelled),
985
+ whole: true,
986
+ value: null,
987
+ block: {
988
+ kind: called.standard,
989
+ inputs: Object.fromEntries(
990
+ Object.entries(item.inputs).map(([name, value]) => [
991
+ name,
992
+ reconstruct(value),
993
+ ]),
994
+ ),
995
+ elapsed: elapsed
996
+ ? expressions.add(
997
+ elapsed.indexes.length
998
+ ? {
999
+ kind: "pattern",
1000
+ path: row.slots.paths.of(paths.add(elapsed.text)),
1001
+ indexes: [...elapsed.indexes],
1002
+ capturedAt: at,
1003
+ type: "TIME",
1004
+ }
1005
+ : {
1006
+ kind: "read",
1007
+ path: row.slots.paths.of(paths.add(elapsed.text)),
1008
+ capturedAt: at,
1009
+ type: "TIME",
1010
+ },
1011
+ )
1012
+ : null,
1013
+ },
1014
+ via: [],
1015
+ loop,
1016
+ });
1017
+ break;
1018
+ }
1019
+ called.inputs.forEach((input, index) => {
1020
+ const value = item.inputs[input.name];
1021
+ if (!value) {
1022
+ return;
1023
+ }
1024
+ if (value.kind === "borrow") {
1025
+ borrowed(call, value, index, called.id);
1026
+ return;
1027
+ }
1028
+ const field = extend(row, spelled, [
1029
+ { kind: "field", name: input.name },
1030
+ ]);
1031
+ assignments.push({
1032
+ ...record,
1033
+ kind: "input",
1034
+ writes: written(field),
1035
+ whole: typeIsAggregate(field),
1036
+ value: reconstruct(value),
1037
+ block: null,
1038
+ via: [],
1039
+ loop,
1040
+ });
1041
+ });
1042
+ break;
1043
+ }
1044
+ case "for":
1045
+ write(item.counter, [], "counter", null);
1046
+ break;
1047
+ case "return": {
1048
+ returns.push({
1049
+ ...record,
1050
+ value: item.value ? reconstruct(item.value) : null,
1051
+ });
1052
+ const value = item.value;
1053
+ if (!block || !value || row.instance === null) {
1054
+ break;
1055
+ }
1056
+ // A block's return writes each output of its instance.
1057
+ const returned = conditions.reconstruct(value, at);
1058
+ for (const output of block.outputs) {
1059
+ const field = spell(row, output.id, []);
1060
+ if (!field) {
1061
+ continue;
1062
+ }
1063
+ assignments.push({
1064
+ ...record,
1065
+ kind: "return",
1066
+ writes: written(field),
1067
+ whole: typeIsAggregate(field),
1068
+ value: expression(
1069
+ row,
1070
+ projectReconstruction(
1071
+ returned,
1072
+ [{ kind: "field", name: output.name }],
1073
+ output.type,
1074
+ ),
1075
+ ),
1076
+ block: null,
1077
+ via: [],
1078
+ loop,
1079
+ });
1080
+ }
1081
+ break;
1082
+ }
1083
+ default:
1084
+ break;
1085
+ }
1086
+ if (assignments.length > first) {
1087
+ recorded.set(item, [
1088
+ ...(recorded.get(item) ?? []),
1089
+ ...Array.from(
1090
+ { length: assignments.length - first },
1091
+ (_, offset) => first + offset,
1092
+ ),
1093
+ ]);
1094
+ }
1095
+ }
1096
+ }
1097
+
1098
+ // Writes through a by-reference parameter land in the storage each call site passes.
1099
+ const calleeRows = (call: ExplainCall, caller: Row): Row[] =>
1100
+ rows
1101
+ .filter((row) => {
1102
+ if (row.routine.id !== call.callee) {
1103
+ return false;
1104
+ }
1105
+ if (call.receiver.kind === "none") {
1106
+ return row.instance === null;
1107
+ }
1108
+ if (call.receiver.kind === "pattern") {
1109
+ return false;
1110
+ }
1111
+ return paths.items[call.receiver.path] === row.instance;
1112
+ })
1113
+ .concat(
1114
+ call.receiver.kind === "none" &&
1115
+ caller.instance !== null &&
1116
+ functions.get(call.callee)?.owner
1117
+ ? rows.filter(
1118
+ (row) =>
1119
+ row.routine.id === call.callee &&
1120
+ row.instance === caller.instance,
1121
+ )
1122
+ : [],
1123
+ );
1124
+ const throughParameter = (
1125
+ target: Spelled,
1126
+ callee: Row,
1127
+ parameter: number,
1128
+ via: readonly number[],
1129
+ depth: number,
1130
+ ): void => {
1131
+ const root =
1132
+ "parameters" in callee.routine
1133
+ ? callee.routine.parameters[parameter]?.id
1134
+ : undefined;
1135
+ if (root === undefined || depth > 16) {
1136
+ return;
1137
+ }
1138
+ for (const [item, flow] of callee.conditions.statements) {
1139
+ const at = flow.position;
1140
+ const record: Record = {
1141
+ routine: callee.index,
1142
+ position: at,
1143
+ conditions: conditionsIndex(
1144
+ flow.conditions.map((part) => condition(callee, part)),
1145
+ ),
1146
+ site: site(item.span),
1147
+ };
1148
+ // A written place's runtime indexes are evaluated where the place is named, in the
1149
+ // outermost caller; one the callee computes itself isn't followed.
1150
+ const fixed = (path: CorePath) =>
1151
+ path.every(
1152
+ (segment) =>
1153
+ segment.kind === "field" || segment.value.kind === "constant",
1154
+ );
1155
+ if (
1156
+ item.kind === "assign" &&
1157
+ item.root === root &&
1158
+ fixed(item.path ?? [])
1159
+ ) {
1160
+ const spelled = extend(
1161
+ callee,
1162
+ target,
1163
+ segments(callee, item.path ?? [], at),
1164
+ );
1165
+ assignments.push({
1166
+ ...record,
1167
+ kind: "assign",
1168
+ writes: written(spelled),
1169
+ whole: typeIsAggregate(spelled),
1170
+ value: expression(
1171
+ callee,
1172
+ callee.conditions.reconstruct(item.value, at),
1173
+ ),
1174
+ block: null,
1175
+ via: [...via],
1176
+ loop: loopOf(callee, flow.loop),
1177
+ });
1178
+ }
1179
+ const passed = calleeParameters(item);
1180
+ const call = callIndexes.get(callee)?.get(item);
1181
+ const nested = call === undefined ? undefined : calls[call];
1182
+ if (!passed || call === undefined || !nested) {
1183
+ continue;
1184
+ }
1185
+ passed.arguments.forEach((argument, index) => {
1186
+ if (
1187
+ argument.kind !== "borrow" ||
1188
+ argument.place.root !== root ||
1189
+ !fixed(argument.place.path) ||
1190
+ !writesThrough.has(`${passed.routine}#${index}`)
1191
+ ) {
1192
+ return;
1193
+ }
1194
+ const inner = extend(
1195
+ callee,
1196
+ target,
1197
+ segments(callee, argument.place.path, at),
1198
+ );
1199
+ for (const next of calleeRows(nested, callee)) {
1200
+ throughParameter(inner, next, index, [call, ...via], depth + 1);
1201
+ }
1202
+ });
1203
+ }
1204
+ };
1205
+ for (const row of rows) {
1206
+ for (const [item, call] of callIndexes.get(row) ?? []) {
1207
+ const passed = calleeParameters(item);
1208
+ const record = calls[call];
1209
+ if (!passed || !record) {
1210
+ continue;
1211
+ }
1212
+ const at = row.conditions.statements.get(item)?.position ?? 0;
1213
+ passed.arguments.forEach((argument, index) => {
1214
+ if (
1215
+ argument.kind !== "borrow" ||
1216
+ !writesThrough.has(`${passed.routine}#${index}`)
1217
+ ) {
1218
+ return;
1219
+ }
1220
+ const target = spell(
1221
+ row,
1222
+ argument.place.root,
1223
+ segments(row, argument.place.path, at),
1224
+ );
1225
+ if (!target) {
1226
+ return;
1227
+ }
1228
+ for (const callee of calleeRows(record, row)) {
1229
+ throughParameter(target, callee, index, [call], 0);
1230
+ }
1231
+ });
1232
+ }
1233
+ }
1234
+
1235
+ // The routines each task runs directly, and every row each task reaches through calls.
1236
+ const entries: ExplainFile["entries"] = [];
1237
+ const rowTasks = new Map<number, Set<string>>();
1238
+ for (const task of plan.specializedTasks.tasks) {
1239
+ const reached = new Set<number>();
1240
+ const visit = (row: Row): void => {
1241
+ if (reached.has(row.index)) {
1242
+ return;
1243
+ }
1244
+ reached.add(row.index);
1245
+ const tasks = rowTasks.get(row.index) ?? new Set<string>();
1246
+ tasks.add(task.name);
1247
+ rowTasks.set(row.index, tasks);
1248
+ for (const call of callIndexes.get(row)?.values() ?? []) {
1249
+ const record = calls[call];
1250
+ if (!record) {
1251
+ continue;
1252
+ }
1253
+ const targets =
1254
+ record.receiver.kind === "pattern"
1255
+ ? rows.filter((candidate) => candidate.routine.id === record.callee)
1256
+ : calleeRows(record, row);
1257
+ targets.forEach(visit);
1258
+ }
1259
+ };
1260
+ task.programs.forEach((name) => {
1261
+ const entry = program.programs.find((item) => item.name === name)?.entry;
1262
+ const row = rows.find(
1263
+ (candidate) =>
1264
+ candidate.routine.id === entry && candidate.instance === null,
1265
+ );
1266
+ if (row) {
1267
+ entries.push({
1268
+ routine: row.index,
1269
+ task: task.name,
1270
+ order: entries.filter((item) => item.task === task.name).length,
1271
+ });
1272
+ visit(row);
1273
+ }
1274
+ });
1275
+ }
1276
+
1277
+ // Flags, stored at the shortest path they apply to.
1278
+ const flags = new Map<string, ExplainFlags>();
1279
+ const flag = (path: string): ExplainFlags => {
1280
+ const known = flags.get(path);
1281
+ if (known) {
1282
+ return known;
1283
+ }
1284
+ const created: ExplainFlags = {
1285
+ path: paths.add(path),
1286
+ input: null,
1287
+ clientWritable: false,
1288
+ hmiControl: null,
1289
+ retained: false,
1290
+ constantTable: false,
1291
+ writerTasks: [],
1292
+ service: null,
1293
+ initial: null,
1294
+ reference: false,
1295
+ };
1296
+ flags.set(path, created);
1297
+ return created;
1298
+ };
1299
+ const writtenPaths = new Set(
1300
+ assignments.map((assignment) => paths.items[assignment.writes.path]),
1301
+ );
1302
+ for (const variable of program.variables) {
1303
+ const path =
1304
+ variable.storage === "constant"
1305
+ ? `${moduleName(variable)}.${variable.name}`
1306
+ : storagePath(variable);
1307
+ if (path === undefined) {
1308
+ continue;
1309
+ }
1310
+ const published = access(variable) === "readwrite";
1311
+ const constant = variable.storage === "constant";
1312
+ if (published || variable.retain || constant) {
1313
+ const item = flag(path);
1314
+ item.clientWritable = published;
1315
+ item.retained = variable.retain;
1316
+ item.constantTable = constant;
1317
+ }
1318
+ if (variable.initial && (constant || !writtenPaths.has(path))) {
1319
+ flag(path).initial = constantValue(variable.initial);
1320
+ }
1321
+ }
1322
+ manifest.io.forEach((io, index) => {
1323
+ if (io.direction === "input") {
1324
+ flag(io.path).input = index;
1325
+ }
1326
+ });
1327
+ for (const block of program.blocks) {
1328
+ const endpoint = plan.http[block.id];
1329
+ if (!serviceBlock(block) || !endpoint) {
1330
+ continue;
1331
+ }
1332
+ for (const path of instances.get(block.id) ?? []) {
1333
+ const instance = instanceText(path);
1334
+ const owner = jobInstances
1335
+ .map((job, index) => ({ ...job, id: index + 1 }))
1336
+ .filter((job) => instance.startsWith(`${job.instance}.`))
1337
+ .sort((a, b) => b.instance.length - a.instance.length)[0];
1338
+ flag(instance).service = {
1339
+ job: owner?.id ?? 0,
1340
+ service: serviceOfPath(endpoint.path) ?? endpoint.path,
1341
+ };
1342
+ }
1343
+ }
1344
+ for (const field of program.references?.fields ?? []) {
1345
+ flag(field).reference = true;
1346
+ }
1347
+ // An HMI control names the published IEC symbol it writes.
1348
+ const targets = createPaths(manifest);
1349
+ for (const control of plan.project.hmi?.controls ?? []) {
1350
+ const path = targets.fromTarget(control.target);
1351
+ if (path) {
1352
+ flag(path).hmiControl = control.label;
1353
+ }
1354
+ }
1355
+ const writers = new Map<string, Set<string>>();
1356
+ for (const assignment of assignments) {
1357
+ const path = paths.items[assignment.writes.path];
1358
+ if (path === undefined) {
1359
+ continue;
1360
+ }
1361
+ const tasks = writers.get(path) ?? new Set<string>();
1362
+ for (const task of rowTasks.get(assignment.routine) ?? []) {
1363
+ tasks.add(task);
1364
+ }
1365
+ writers.set(path, tasks);
1366
+ }
1367
+ for (const [path, tasks] of writers) {
1368
+ const readTasks = new Set(
1369
+ [...(readers.get(path) ?? [])].flatMap((row) => [
1370
+ ...(rowTasks.get(row) ?? []),
1371
+ ]),
1372
+ );
1373
+ if (tasks.size > 1 || [...readTasks].some((task) => !tasks.has(task))) {
1374
+ flag(path).writerTasks = [...tasks].sort();
1375
+ }
1376
+ }
1377
+
1378
+ const file: ExplainFile = {
1379
+ kind: "tsplc-explain",
1380
+ version: 1,
1381
+ paths: paths.items,
1382
+ texts: texts.items,
1383
+ expressions: expressions.items,
1384
+ conditions: conditionTree.items,
1385
+ sites: sites.items,
1386
+ routines: routineRows.map((routine, index) => {
1387
+ const row = rows[index];
1388
+ const base = row ? (loopBases.get(row) ?? 0) : 0;
1389
+ return {
1390
+ ...routine,
1391
+ job: row?.job ?? null,
1392
+ paths: row?.slots.paths.items ?? [],
1393
+ locals: row?.slots.locals.items ?? [],
1394
+ calls: row?.slots.calls.items ?? [],
1395
+ loops: Array.from(
1396
+ { length: row?.conditions.loops.length ?? 0 },
1397
+ (_, loop) => base + loop,
1398
+ ),
1399
+ };
1400
+ }),
1401
+ loops,
1402
+ assignments,
1403
+ locals,
1404
+ returns,
1405
+ calls,
1406
+ entries,
1407
+ flags: [...flags.values()],
1408
+ references: Object.fromEntries(
1409
+ (program.references?.objects ?? []).map(({ id, path }) => [
1410
+ String(id),
1411
+ paths.add(path),
1412
+ ]),
1413
+ ),
1414
+ };
1415
+ return { file, assignmentsOf: (statement) => recorded.get(statement) ?? [] };
1416
+ }
1417
+
1418
+ /** A build's `explain.json`, and the assignments of it each statement makes itself. */
1419
+ export interface Explanations {
1420
+ file: ExplainFile;
1421
+ assignmentsOf(statement: CoreStatement): readonly number[];
1422
+ }
1423
+
1424
+ /**
1425
+ * The manifest's last-writer slots with the assignments each site stands for, and whether the slot
1426
+ * names its path's writer exactly: when every statement that can write the path writes it directly,
1427
+ * where a probe records it. Writes made by a block, a loop counter or through a parameter aren't probed.
1428
+ */
1429
+ export function explainedWriters(
1430
+ manifest: DebugManifest,
1431
+ explained: Explanations,
1432
+ sites: readonly (readonly { id: number; statement: CoreStatement }[])[],
1433
+ ): DebugManifest["writers"] {
1434
+ const explainer = createExplainer(manifest, explained.file);
1435
+ return manifest.writers.map((writer, index) => {
1436
+ const probed = sites[index] ?? [];
1437
+ const exact = explainer.explain(writer.output).writers.every((item) => {
1438
+ const assignment = explained.file.assignments[item.assignment];
1439
+ return (
1440
+ assignment !== undefined &&
1441
+ (assignment.kind === "assign" || assignment.kind === "call") &&
1442
+ !assignment.via.length
1443
+ );
1444
+ });
1445
+ return {
1446
+ ...writer,
1447
+ exact,
1448
+ sites: writer.sites.map((site) => ({
1449
+ ...site,
1450
+ assignments: probed
1451
+ .filter((item) => item.id === site.id)
1452
+ .flatMap((item) => [...explained.assignmentsOf(item.statement)])
1453
+ .filter((assignment) => {
1454
+ const written = explained.file.assignments[assignment];
1455
+ return (
1456
+ written !== undefined &&
1457
+ explainer
1458
+ .explain(writer.output)
1459
+ .writers.some((item) => item.assignment === assignment)
1460
+ );
1461
+ }),
1462
+ })),
1463
+ };
1464
+ });
1465
+ }