@tsplc/compiler 0.5.7 → 0.5.9

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.
Files changed (59) hide show
  1. package/dist/bun-runtime.js +8 -2
  2. package/dist/bun-runtime.js.map +3 -3
  3. package/dist/cli.js +17 -5
  4. package/dist/cli.js.map +5 -5
  5. package/dist/codesys.js +2933 -1724
  6. package/dist/codesys.js.map +20 -19
  7. package/dist/index.js +870 -685
  8. package/dist/index.js.map +20 -19
  9. package/dist/ir.js +1654 -1364
  10. package/dist/ir.js.map +16 -14
  11. package/dist/project.js +5 -2
  12. package/dist/project.js.map +3 -3
  13. package/dist/telemetry.js +8 -2
  14. package/dist/telemetry.js.map +3 -3
  15. package/package.json +9 -9
  16. package/src/codesys/debug.ts +17 -2
  17. package/src/codesys/emit.ts +34 -11
  18. package/src/codesys/engineering.ts +27 -12
  19. package/src/codesys/explain.ts +1465 -0
  20. package/src/codesys/global-lists.ts +21 -9
  21. package/src/codesys/http.ts +12 -0
  22. package/src/codesys/instrumentation.ts +131 -3
  23. package/src/codesys/manifest.ts +29 -12
  24. package/src/codesys/numeric.ts +5 -3
  25. package/src/codesys/plan.ts +31 -28
  26. package/src/codesys/programs.ts +63 -1
  27. package/src/codesys/types.ts +34 -12
  28. package/src/frontend/async.ts +14 -8
  29. package/src/frontend/coroutines.ts +55 -16
  30. package/src/frontend/elaborate/expressions.ts +10 -2
  31. package/src/frontend/elaborate/filtered-arrays.ts +5 -5
  32. package/src/frontend/elaborate/index.ts +42 -4
  33. package/src/frontend/elaborate/model.ts +48 -1
  34. package/src/frontend/elaborate/references.ts +6 -6
  35. package/src/frontend/elaborate/specialize.ts +18 -4
  36. package/src/frontend/elaborate/storage.ts +58 -2
  37. package/src/frontend/expressions.ts +2 -2
  38. package/src/frontend/generated-names.ts +95 -0
  39. package/src/frontend/intrinsics.ts +1 -2
  40. package/src/frontend/promise-chains.ts +22 -8
  41. package/src/frontend/promises.ts +8 -10
  42. package/src/frontend/statements.ts +3 -2
  43. package/src/frontend/tasks.ts +8 -8
  44. package/src/frontend/typescript.ts +5 -2
  45. package/src/ir/conditions.ts +895 -0
  46. package/src/ir/core-model.ts +2 -2
  47. package/src/ir/fold.ts +15 -107
  48. package/src/ir/identity.ts +9 -0
  49. package/src/ir/index.ts +18 -13
  50. package/src/ir/job-errors.ts +14 -0
  51. package/src/ir/link.ts +1 -0
  52. package/src/ir/model.ts +16 -79
  53. package/src/ir/numeric.ts +5 -41
  54. package/src/ir/ranges.ts +8 -14
  55. package/src/ir/scalars.ts +6 -4
  56. package/src/ir/share.ts +0 -52
  57. package/src/project/debugger.ts +9 -0
  58. package/src/project/project.ts +6 -0
  59. package/src/project/release.ts +7 -4
@@ -1,6 +1,6 @@
1
+ import type { BinaryOperator, UnaryOperator } from "@tsplc/iec/arithmetic";
1
2
  import type { SourceSpan } from "./diagnostics";
2
3
  import type {
3
- BinaryOperator,
4
4
  Constant,
5
5
  FunctionBlock,
6
6
  MethodOwner,
@@ -8,7 +8,6 @@ import type {
8
8
  PlcModule,
9
9
  PlcProgram,
10
10
  TelemetryCall,
11
- UnaryOperator,
12
11
  Variable,
13
12
  } from "./model";
14
13
  import type { PlcType } from "./types";
@@ -164,6 +163,7 @@ export const verified: unique symbol = Symbol("verified core");
164
163
  export interface VerifiedCoreModule {
165
164
  readonly [verified]: true;
166
165
  readonly folded?: PlcModule["folded"];
166
+ readonly references?: PlcModule["references"];
167
167
  readonly types: readonly PlcType[];
168
168
  readonly variables: readonly Variable[];
169
169
  readonly functions: readonly CoreFunction[];
package/src/ir/fold.ts CHANGED
@@ -1,18 +1,17 @@
1
- import { nanosecondsPerMillisecond } from "./domains";
2
1
  import {
3
- type BinaryOperator,
4
- type Constant,
5
- type Expression,
2
+ applyIntegerPolicy,
3
+ booleanOperation,
4
+ compare,
6
5
  elementaryValue,
6
+ floatArithmetic,
7
+ integerArithmetic,
7
8
  isElementary,
8
- type Variable,
9
- } from "./model";
10
- import {
11
- applyIntegerPolicy,
12
- integerType,
13
9
  roundFloat,
14
10
  saturateFloat,
15
- } from "./numeric";
11
+ } from "@tsplc/iec/arithmetic";
12
+ import { nanosecondsPerMillisecond } from "./domains";
13
+ import type { Constant, Expression, Variable } from "./model";
14
+ import { integerType } from "./numeric";
16
15
  import type { PlcType } from "./types";
17
16
 
18
17
  type Types = ReadonlyMap<string, PlcType> | undefined;
@@ -215,7 +214,12 @@ const foldBinary = (
215
214
  target: PlcType | undefined,
216
215
  ): Constant | undefined => {
217
216
  if (left.kind === "bool" && right.kind === "bool") {
218
- return foldLogical(expression.operator, left.value, right.value);
217
+ const value = booleanOperation(
218
+ expression.operator,
219
+ left.value,
220
+ right.value,
221
+ );
222
+ return value === undefined ? undefined : { kind: "bool", value };
219
223
  }
220
224
  if (left.kind !== right.kind || !ordered(left) || !ordered(right)) {
221
225
  return undefined;
@@ -258,102 +262,6 @@ const foldBinary = (
258
262
  return undefined;
259
263
  };
260
264
 
261
- const foldLogical = (
262
- operator: BinaryOperator,
263
- left: boolean,
264
- right: boolean,
265
- ): Constant | undefined => {
266
- switch (operator) {
267
- case "and":
268
- return { kind: "bool", value: left && right };
269
- case "or":
270
- return { kind: "bool", value: left || right };
271
- case "equal":
272
- return { kind: "bool", value: left === right };
273
- case "notEqual":
274
- return { kind: "bool", value: left !== right };
275
- default:
276
- return undefined;
277
- }
278
- };
279
-
280
- const compare = <Value extends bigint | number | string>(
281
- operator: BinaryOperator,
282
- left: Value,
283
- right: Value,
284
- ): boolean | undefined => {
285
- switch (operator) {
286
- case "equal":
287
- return left === right;
288
- case "notEqual":
289
- return left !== right;
290
- case "less":
291
- return left < right;
292
- case "lessEqual":
293
- return left <= right;
294
- case "greater":
295
- return left > right;
296
- case "greaterEqual":
297
- return left >= right;
298
- default:
299
- return undefined;
300
- }
301
- };
302
-
303
- const integerArithmetic = (
304
- operator: BinaryOperator,
305
- left: bigint,
306
- right: bigint,
307
- ): bigint | undefined => {
308
- switch (operator) {
309
- case "add":
310
- return left + right;
311
- case "subtract":
312
- return left - right;
313
- case "multiply":
314
- return left * right;
315
- case "divide":
316
- return right === 0n ? undefined : left / right;
317
- case "remainder":
318
- return right === 0n ? undefined : left % right;
319
- case "bitAnd":
320
- return left & right;
321
- case "bitOr":
322
- return left | right;
323
- case "bitXor":
324
- return left ^ right;
325
- case "shiftLeft":
326
- return right < 0n || right > 63n ? undefined : left << right;
327
- case "shiftRight":
328
- return right < 0n || right > 63n ? undefined : left >> right;
329
- default:
330
- return undefined;
331
- }
332
- };
333
-
334
- const floatArithmetic = (
335
- operator: BinaryOperator,
336
- left: number,
337
- right: number,
338
- ): number | undefined => {
339
- switch (operator) {
340
- case "add":
341
- return left + right;
342
- case "subtract":
343
- return left - right;
344
- case "multiply":
345
- return left * right;
346
- case "divide":
347
- return left / right;
348
- case "remainder":
349
- return left % right;
350
- case "power":
351
- return left ** right;
352
- default:
353
- return undefined;
354
- }
355
- };
356
-
357
265
  /** A float result as its type holds it, or nothing when it isn't finite, as NaN and infinities aren't constants. */
358
266
  const finiteFloat = (
359
267
  value: number,
@@ -0,0 +1,9 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ /**
4
+ * Generated names are a fixed function of the identity of what they stand for, so the same source
5
+ * names the same things whatever else changes: an online change then finds every piece of state
6
+ * where it left it. A digest keeps the name short and its identity out of the PLC's namespace.
7
+ */
8
+ export const identityDigest = (identity: string): string =>
9
+ createHash("sha256").update(identity).digest("hex").slice(0, 8);
package/src/ir/index.ts CHANGED
@@ -6,6 +6,16 @@ export {
6
6
  placeType,
7
7
  valueFits,
8
8
  } from "./aggregates";
9
+ export {
10
+ type LoopConditions,
11
+ type PathCondition,
12
+ pathConditions,
13
+ projectReconstruction,
14
+ type ReconstructedSegment,
15
+ type Reconstruction,
16
+ type RoutineConditions,
17
+ type StatementConditions,
18
+ } from "./conditions";
9
19
  export {
10
20
  type CheckedPlace,
11
21
  type CoreExpression,
@@ -32,22 +42,24 @@ export {
32
42
  nanosecondsPerMillisecond,
33
43
  } from "./domains";
34
44
  export { fold } from "./fold";
35
- export { errorName, httpErrors, jobError, jobErrors } from "./job-errors";
45
+ export { identityDigest } from "./identity";
46
+ export {
47
+ errorName,
48
+ httpErrors,
49
+ jobError,
50
+ jobErrors,
51
+ reservedErrors,
52
+ } from "./job-errors";
36
53
  export { layoutIssue, maxNestingDepth, maxScalarElements } from "./layouts";
37
54
  export {
38
55
  type Artifact,
39
- type BinaryOperator,
40
56
  type Constant,
41
57
  comparisonOperators,
42
58
  type Deployment,
43
- type ElementaryFunction,
44
59
  type EmitResult,
45
60
  type Expression,
46
- elementaryFunctions,
47
- elementaryValue,
48
61
  type FunctionBlock,
49
62
  type GeneratedObject,
50
- isElementary,
51
63
  type MathHelper,
52
64
  type MethodOwner,
53
65
  type Place,
@@ -60,20 +72,15 @@ export {
60
72
  type Task,
61
73
  type TelemetryCall,
62
74
  telemetryOperands,
63
- type UnaryOperator,
64
75
  type Variable,
65
76
  } from "./model";
66
77
  export { isVerifiedCore, normalizeModule } from "./normalize";
67
78
  export {
68
- applyIntegerPolicy,
69
79
  canAssign,
70
80
  constantFits,
71
- floatMaximum,
72
81
  type IntegerInterval,
73
82
  integerType,
74
83
  parseInteger,
75
- roundFloat,
76
- saturateFloat,
77
84
  wrapsNatively,
78
85
  } from "./numeric";
79
86
  export {
@@ -84,7 +91,6 @@ export {
84
91
  export {
85
92
  interval,
86
93
  loopBounds,
87
- loopIterations,
88
94
  maxLoopIterations,
89
95
  narrowRanges,
90
96
  valueRange,
@@ -92,7 +98,6 @@ export {
92
98
  export { scalarIssue } from "./scalars";
93
99
  export {
94
100
  foldConstantRoutines,
95
- joinPrograms,
96
101
  type SharedRoutines,
97
102
  shareRoutines,
98
103
  } from "./share";
@@ -7,11 +7,20 @@ export const jobError = {
7
7
  network: 5,
8
8
  tls: 6,
9
9
  noRequestSlot: 7,
10
+ /**
11
+ * An online change replaced the code of a job that was running: its step and stored state
12
+ * were made for the old code, so it stops instead of resuming in the new. Like `cancelled`,
13
+ * it skips `catch`, so a retry can't send a request twice.
14
+ */
15
+ codeChanged: 11001,
10
16
  } as const;
11
17
 
12
18
  /** An HTTP response fails a job with `base` + its status, up to `last`. */
13
19
  export const httpErrors = { base: 10000, last: 10999 };
14
20
 
21
+ /** Codes tsPLC itself reports from 11000 on, which a program's own `throw` may not use. */
22
+ export const reservedErrors = { first: 11000, last: 11099 };
23
+
15
24
  /** Job error codes, as every generated async block and service call reports them. */
16
25
  export const jobErrors: Record<string, string> = {
17
26
  [jobError.cancelled]: "cancelled",
@@ -21,6 +30,8 @@ export const jobErrors: Record<string, string> = {
21
30
  [jobError.network]: "network error or server restarted",
22
31
  [jobError.tls]: "TLS error",
23
32
  [jobError.noRequestSlot]: "no free request slot",
33
+ [jobError.codeChanged]:
34
+ "an online change replaced the job's code while it ran",
24
35
  [httpErrors.base]: "HTTP status: 10000 + status code",
25
36
  };
26
37
 
@@ -29,5 +40,8 @@ export const errorName = (code: number): string | undefined => {
29
40
  if (code > httpErrors.base && code <= httpErrors.last) {
30
41
  return `HTTP ${code - httpErrors.base}`;
31
42
  }
43
+ if (code >= reservedErrors.first && code <= reservedErrors.last) {
44
+ return jobErrors[code];
45
+ }
32
46
  return code < httpErrors.base ? jobErrors[code] : undefined;
33
47
  };
package/src/ir/link.ts CHANGED
@@ -55,6 +55,7 @@ export function linkModule(
55
55
  blocks: linkedBlocks,
56
56
  programs: module.programs,
57
57
  ...(module.folded && { folded: module.folded }),
58
+ ...(module.references && { references: module.references }),
58
59
  };
59
60
  }
60
61
 
package/src/ir/model.ts CHANGED
@@ -1,3 +1,8 @@
1
+ import {
2
+ type BinaryOperator,
3
+ comparisonOperatorNames,
4
+ type UnaryOperator,
5
+ } from "@tsplc/iec/arithmetic";
1
6
  import type { Diagnostic, SourceSpan } from "./diagnostics";
2
7
  import type { PlcType, SymbolId, TypeId } from "./types";
3
8
 
@@ -42,85 +47,9 @@ export interface Place {
42
47
  )[];
43
48
  }
44
49
 
45
- /**
46
- * The elementary functions on REAL and LREAL, Structured Text's SQRT, LN, LOG, EXP and the
47
- * trigonometric functions; each returns its operand's type.
48
- */
49
- export const elementaryFunctions = [
50
- "sqrt",
51
- "ln",
52
- "log10",
53
- "exp",
54
- "sin",
55
- "cos",
56
- "tan",
57
- "asin",
58
- "acos",
59
- "atan",
60
- ] as const;
61
- export type ElementaryFunction = (typeof elementaryFunctions)[number];
62
-
63
- /** Each elementary function as JavaScript computes it, which constants fold and simulations run with. */
64
- export const elementaryValue: Readonly<
65
- Record<ElementaryFunction, (value: number) => number>
66
- > = {
67
- sqrt: Math.sqrt,
68
- ln: Math.log,
69
- log10: Math.log10,
70
- exp: Math.exp,
71
- sin: Math.sin,
72
- cos: Math.cos,
73
- tan: Math.tan,
74
- asin: Math.asin,
75
- acos: Math.acos,
76
- atan: Math.atan,
77
- };
78
-
79
- export const isElementary = (
80
- operator: string,
81
- ): operator is ElementaryFunction =>
82
- (elementaryFunctions as readonly string[]).includes(operator);
83
-
84
- /** `truncate` is TRUNC, a REAL or LREAL toward zero as DINT. */
85
- export type UnaryOperator =
86
- | "not"
87
- | "negate"
88
- | "bitNot"
89
- | "timeToMilliseconds"
90
- | "clock"
91
- | "truncate"
92
- | ElementaryFunction;
93
-
94
- /** `power` is EXPT on REAL or LREAL. */
95
- export type BinaryOperator =
96
- | "add"
97
- | "subtract"
98
- | "multiply"
99
- | "divide"
100
- | "remainder"
101
- | "equal"
102
- | "notEqual"
103
- | "less"
104
- | "lessEqual"
105
- | "greater"
106
- | "greaterEqual"
107
- | "and"
108
- | "or"
109
- | "bitAnd"
110
- | "bitOr"
111
- | "bitXor"
112
- | "shiftLeft"
113
- | "shiftRight"
114
- | "power";
115
-
116
- export const comparisonOperators: ReadonlySet<BinaryOperator> = new Set([
117
- "equal",
118
- "notEqual",
119
- "less",
120
- "lessEqual",
121
- "greater",
122
- "greaterEqual",
123
- ]);
50
+ export const comparisonOperators: ReadonlySet<BinaryOperator> = new Set(
51
+ comparisonOperatorNames,
52
+ );
124
53
 
125
54
  export type Expression = { type: TypeId; span: SourceSpan } & (
126
55
  | { kind: "constant"; value: Constant }
@@ -392,6 +321,14 @@ export interface PlcModule {
392
321
  type?: TypeId;
393
322
  span: SourceSpan;
394
323
  }[];
324
+ /**
325
+ * Object references: the module storage path of each object by the id a reference holds (−1 is
326
+ * `undefined`), and the storage paths of the fields that hold a reference.
327
+ */
328
+ references?: {
329
+ objects: readonly { id: number; path: string }[];
330
+ fields: readonly string[];
331
+ };
395
332
  types: readonly PlcType[];
396
333
  variables: readonly Variable[];
397
334
  functions: readonly PlcFunction[];
package/src/ir/numeric.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
2
+ import { roundFloat } from "@tsplc/iec/arithmetic";
2
3
  import type { Constant } from "./model";
3
4
  import { integerRange, type PlcType } from "./types";
4
5
 
@@ -26,36 +27,13 @@ export const canonicalInteger = /^(?:0|-?[1-9][0-9]*)$/;
26
27
  export const integerType = (type: PlcType): type is IntegerType =>
27
28
  type.kind === "integer" || type.kind === "bits";
28
29
 
29
- // IEEE 754 binary32 (REAL) and binary64 (LREAL): the largest finite value, and the significand
30
- // precision, which bounds the integers the format holds exactly.
31
- const floatFormats = {
32
- 32: { maximum: Math.fround((2 - 2 ** -23) * 2 ** 127), precision: 24 },
33
- 64: { maximum: Number.MAX_VALUE, precision: 53 },
34
- } as const;
35
-
36
- export const floatMaximum = (type: FloatType): number =>
37
- floatFormats[type.bits].maximum;
30
+ // The significand precision of REAL (IEEE 754 binary32) and LREAL (binary64), which bounds the
31
+ // integers each format holds exactly.
32
+ const floatPrecision = { 32: 24, 64: 53 } as const;
38
33
 
39
34
  /** Every integer from minus this limit to this limit converts to the float type exactly. */
40
35
  export const exactIntegerLimit = (type: FloatType): bigint =>
41
- 1n << BigInt(floatFormats[type.bits].precision);
42
-
43
- /** The nearest value of the float type, as each typed REAL result rounds. */
44
- export const roundFloat = (value: number, type: FloatType): number =>
45
- type.bits === 32 ? Math.fround(value) : value;
46
-
47
- export const saturateFloat = (value: number, type: FloatType): number => {
48
- // Clamp before target rounding so a finite source cannot round to infinity.
49
- // Comparisons leave signed zero intact; min/max substitution is unnecessary.
50
- const maximum = floatMaximum(type);
51
- if (value < -maximum) {
52
- return -maximum;
53
- }
54
- if (value > maximum) {
55
- return maximum;
56
- }
57
- return roundFloat(value, type);
58
- };
36
+ 1n << BigInt(floatPrecision[type.bits]);
59
37
 
60
38
  type DecimalIssue = "malformed" | "exponent" | "fraction";
61
39
 
@@ -156,17 +134,3 @@ export const wrapsNatively = (expression: {
156
134
  (expression.operator === "add" ||
157
135
  expression.operator === "subtract" ||
158
136
  expression.operator === "multiply");
159
-
160
- export const applyIntegerPolicy = (
161
- value: bigint,
162
- type: IntegerType,
163
- policy: "wrap" | "saturate",
164
- ): bigint => {
165
- if (policy === "saturate") {
166
- const [minimum, maximum] = integerRange(type);
167
- return highest(minimum, lowest(value, maximum));
168
- }
169
- return type.kind === "integer" && type.signed
170
- ? BigInt.asIntN(type.bits, value)
171
- : BigInt.asUintN(type.bits, value);
172
- };
package/src/ir/ranges.ts CHANGED
@@ -1,5 +1,6 @@
1
+ import { type BinaryOperator, loopIterations } from "@tsplc/iec/arithmetic";
1
2
  import { fold } from "./fold";
2
- import type { BinaryOperator, Expression, MathHelper, Variable } from "./model";
3
+ import type { Expression, MathHelper, Variable } from "./model";
3
4
  import {
4
5
  admits,
5
6
  highest,
@@ -101,18 +102,6 @@ const arithmeticInterval = (
101
102
  /** The most iterations a bounded loop may prove. */
102
103
  export const maxLoopIterations = 1_000_000n;
103
104
 
104
- // FOR iterations from first to last inclusive; step is nonzero.
105
- export const loopIterations = (
106
- first: bigint,
107
- last: bigint,
108
- step: bigint,
109
- ): bigint => {
110
- if (step > 0n) {
111
- return last >= first ? (last - first) / step + 1n : 0n;
112
- }
113
- return last <= first ? (first - last) / -step + 1n : 0n;
114
- };
115
-
116
105
  export const loopBounds = (
117
106
  start: IntegerInterval,
118
107
  limit: IntegerInterval,
@@ -122,7 +111,12 @@ export const loopBounds = (
122
111
  const excluded = exclusive ? 1n : 0n;
123
112
  const first = step > 0n ? start[0] : start[1];
124
113
  const last = step > 0n ? limit[1] - excluded : limit[0] + excluded;
125
- const count = loopIterations(first, last, step);
114
+ const count = loopIterations(
115
+ first,
116
+ limit[step > 0n ? 1 : 0],
117
+ exclusive,
118
+ step,
119
+ );
126
120
  const range: IntegerInterval = first <= last ? [first, last] : [last, first];
127
121
  return { first, last, count, range };
128
122
  };
package/src/ir/scalars.ts CHANGED
@@ -1,10 +1,14 @@
1
+ import {
2
+ type ElementaryFunction,
3
+ floatMaximum,
4
+ isElementary,
5
+ roundFloat,
6
+ } from "@tsplc/iec/arithmetic";
1
7
  import { fold } from "./fold";
2
8
  import {
3
9
  type Constant,
4
10
  comparisonOperators,
5
- type ElementaryFunction,
6
11
  type Expression,
7
- isElementary,
8
12
  type Variable,
9
13
  } from "./model";
10
14
  import {
@@ -12,10 +16,8 @@ import {
12
16
  canAssign,
13
17
  constantFits,
14
18
  exactIntegerLimit,
15
- floatMaximum,
16
19
  type IntegerInterval,
17
20
  integerType,
18
- roundFloat,
19
21
  within,
20
22
  wrapsNatively,
21
23
  } from "./numeric";
package/src/ir/share.ts CHANGED
@@ -681,58 +681,6 @@ const returns = (items: readonly CoreStatement[]): boolean =>
681
681
  (item) => item.kind === "return" || nestedBodies(item).some(returns),
682
682
  );
683
683
 
684
- /**
685
- * Joins each group of programs into its first: one entry that runs the entries' bodies in the
686
- * group's order, which is the order a task runs them in. An entry that can return early would
687
- * skip the ones after it, so it stays a program of its own. `routines` maps each entry joined
688
- * away to the entry that now runs it.
689
- */
690
- export function joinPrograms(
691
- core: VerifiedCoreModule,
692
- groups: readonly (readonly string[])[],
693
- ): SharedRoutines {
694
- const functions = new Map(core.functions.map((fn) => [fn.id, fn]));
695
- const programs = new Map(core.programs.map((item) => [item.name, item]));
696
- const joined = new Map<string, CoreFunction>();
697
- const routines = new Map<string, string>();
698
- const removed = new Set<string>();
699
- for (const group of groups) {
700
- const members = group.flatMap((name) => {
701
- const program = programs.get(name);
702
- const entry = program && functions.get(program.entry);
703
- return program && entry && !returns(entry.body)
704
- ? [{ program, entry }]
705
- : [];
706
- });
707
- const [first, ...rest] = members;
708
- if (!first || !rest.length) {
709
- continue;
710
- }
711
- joined.set(first.entry.id, {
712
- ...first.entry,
713
- locals: members.flatMap(({ entry }) => entry.locals),
714
- body: members.flatMap(({ entry }) => entry.body),
715
- });
716
- for (const { program, entry } of rest) {
717
- removed.add(program.name);
718
- routines.set(entry.id, first.entry.id);
719
- }
720
- }
721
- if (!routines.size) {
722
- return { core, routines };
723
- }
724
- return {
725
- core: admitCore({
726
- ...core,
727
- functions: core.functions.flatMap((fn) =>
728
- routines.has(fn.id) ? [] : [joined.get(fn.id) ?? fn],
729
- ),
730
- programs: core.programs.filter((item) => !removed.has(item.name)),
731
- }),
732
- routines,
733
- };
734
- }
735
-
736
684
  /** A routine that only returns a constant, or does nothing: what each of its calls amounts to. */
737
685
  function constantResult(
738
686
  fn: CoreFunction,
@@ -10,6 +10,7 @@ import {
10
10
  createDebugger,
11
11
  createLoginAdapter,
12
12
  createOpcUaAdapter,
13
+ loadExplanations,
13
14
  loadManifest,
14
15
  opcUaConnection,
15
16
  serveDebugger,
@@ -70,6 +71,14 @@ export async function serveProjectDebugger(
70
71
  watch: config.debug?.watch ?? {},
71
72
  ...(serverUrl && token && { server: { url: serverUrl, token } }),
72
73
  projectRoot: root,
74
+ explanations: await loadExplanations(file, manifest),
75
+ // The forced list comes from the agent's login; an OPC UA endpoint has no such list.
76
+ forced: flags.opcua
77
+ ? null
78
+ : async () => {
79
+ const { login } = await connect(env).status();
80
+ return login && "forced" in login ? login.forced : null;
81
+ },
73
82
  log,
74
83
  });
75
84
  const server = serveDebugger(debug, { port: port.data, log });
@@ -42,6 +42,7 @@ import {
42
42
  simulationConfig,
43
43
  } from "@tsplc/config";
44
44
  import { emittedFiles, emittedStDirectory } from "@tsplc/config/project-files";
45
+ import { explainFileName } from "@tsplc/debug/explain-file";
45
46
  import { debugManifestFile } from "@tsplc/debug/manifest";
46
47
  import {
47
48
  deviceTree,
@@ -152,6 +153,7 @@ async function loadProject(
152
153
  ...(shared.debug && { debug: shared.debug }),
153
154
  ...(shared.telemetry && { telemetry: shared.telemetry }),
154
155
  ...(shared.server && { server: shared.server }),
156
+ ...(shared.hmi && { hmi: shared.hmi }),
155
157
  // A simulation build drops fieldbus IO, but the debugger still shows the hardware it stands in for.
156
158
  hardware: {
157
159
  catalog: configured ? await loadHardware(configured, root) : catalog,
@@ -390,6 +392,10 @@ export async function buildProject(
390
392
  },
391
393
  ]
392
394
  : []),
395
+ // The manifest's digest covers these exact bytes.
396
+ ...(bundle.explain === undefined
397
+ ? []
398
+ : [{ path: explainFileName, content: bundle.explain }]),
393
399
  ];
394
400
  const stagedSt = join(staging, emittedSt);
395
401
  // Thousands of artifacts share a few hundred directories; each is made once.
@@ -12,6 +12,7 @@ import {
12
12
  serverTokenEnv,
13
13
  } from "@tsplc/config";
14
14
  import type { ReleaseConfig } from "@tsplc/config/build";
15
+ import { explainFileName } from "@tsplc/debug/explain-file";
15
16
  import { debugManifestFile } from "@tsplc/debug/manifest";
16
17
  import { contractVariables, plcContractSchema } from "@tsplc/opcua/contract";
17
18
  import { generatedFiles, generateProject } from "@tsplc/typegen";
@@ -96,10 +97,12 @@ export const prepareRelease = async (
96
97
  content: Bun.file(resolve(settings.sourceDir, source)),
97
98
  });
98
99
  }
99
- // The agent's debugger reads the program through its debug manifest.
100
- const debugManifest = resolve(settings.sourceDir, debugManifestFile);
101
- if (existsSync(debugManifest)) {
102
- files.push({ path: debugManifestFile, content: Bun.file(debugManifest) });
100
+ // The agent's debugger reads the program through its debug manifest, and explains it with `explain.json`.
101
+ for (const name of [debugManifestFile, explainFileName]) {
102
+ const path = resolve(settings.sourceDir, name);
103
+ if (existsSync(path)) {
104
+ files.push({ path: name, content: Bun.file(path) });
105
+ }
103
106
  }
104
107
  const serverScript =
105
108
  serverCheck && (await bundleServer(await serverCheck, config, root));