@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.
@@ -54,21 +54,34 @@ const globalInitializer = (
54
54
  : targetTypes.declarationInitializer(value, item.type);
55
55
  };
56
56
 
57
+ /**
58
+ * How a variable is published for the build target: an exposure is read-only, and any other
59
+ * published variable is writable by clients. Unpublished variables have no access.
60
+ */
61
+ export const publishedAccess = (
62
+ plan: CodesysPlan,
63
+ ): ((variable: Variable) => "read" | "readwrite" | undefined) => {
64
+ const published = new Set(plan.publication[plan.options.buildTarget]);
65
+ return (variable) => {
66
+ if (!published.has(variable.id)) {
67
+ return undefined;
68
+ }
69
+ return variable.exposure ? "read" : "readwrite";
70
+ };
71
+ };
72
+
57
73
  /** The global lists of module storage; each variable's global symbol goes into `symbols.references`. */
58
74
  export function emitGlobalLists(
59
75
  plan: CodesysPlan,
60
76
  symbols: CodesysSymbols,
61
77
  ): { objects: GeneratedObject[]; mappings: SourceMapping[] } {
62
- const { options } = plan;
63
78
  const { globals, references, targetTypes } = symbols;
64
79
  const objects: GeneratedObject[] = [];
65
80
  const mappings: SourceMapping[] = [];
81
+ const access = publishedAccess(plan);
66
82
  for (const group of globals) {
67
83
  const { name, fields } = group;
68
- const published = new Set(plan.publication[options.buildTarget]);
69
- const publish = group.variables.some((variable) =>
70
- published.has(variable.id),
71
- );
84
+ const publish = group.variables.some((variable) => access(variable));
72
85
  const lines = [
73
86
  ...(publish ? ["{attribute 'linkalways'}"] : []),
74
87
  "{attribute 'qualified_only'}",
@@ -78,10 +91,9 @@ export function emitGlobalLists(
78
91
  for (const item of section.variables) {
79
92
  const field = required(fields.get(item.id));
80
93
  references.set(item.id, `${name}.${field}`);
81
- if (published.has(item.id)) {
82
- lines.push(
83
- ` {attribute 'symbol' := '${item.exposure ? "read" : "readwrite"}'}`,
84
- );
94
+ const symbol = access(item);
95
+ if (symbol) {
96
+ lines.push(` {attribute 'symbol' := '${symbol}'}`);
85
97
  }
86
98
  mappings.push({
87
99
  path: `${name}.st`,
@@ -1,6 +1,7 @@
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
2
  import {
3
3
  type CoreFunctionBlock,
4
+ type FunctionBlock,
4
5
  type GeneratedObject,
5
6
  httpErrors,
6
7
  jobError,
@@ -944,6 +945,17 @@ IF digits=0 THEN malformed:=TRUE;END_IF;IF negative THEN numberValue:=-numberVal
944
945
  );
945
946
  };
946
947
 
948
+ type ServiceRuntime = Extract<
949
+ NonNullable<FunctionBlock["runtime"]>,
950
+ { kind: "http" | "rpc" }
951
+ >;
952
+
953
+ /** A block that calls a service: its body is the request state machine `emitServiceBlock` writes. */
954
+ export const serviceBlock = <Block extends Pick<FunctionBlock, "runtime">>(
955
+ block: Block,
956
+ ): block is Block & { runtime: ServiceRuntime } =>
957
+ block.runtime?.kind === "http" || block.runtime?.kind === "rpc";
958
+
947
959
  /** A service-call block: its HTTP or OPC UA client, the client's methods and, over OPC UA, its slots' global list. */
948
960
  export function emitServiceBlock(
949
961
  { plan, symbols, instrumentation }: EmissionContext,
@@ -6,10 +6,18 @@ import type {
6
6
  CoreStatement,
7
7
  GeneratedObject,
8
8
  SourceSpan,
9
+ VerifiedCoreModule,
9
10
  } from "@tsplc/compiler/ir";
10
- import type { DebugManifest } from "@tsplc/debug/manifest";
11
+ import type { ResolvedDebugConfig } from "@tsplc/config";
12
+ import type { DebugManifest, DebugType } from "@tsplc/debug/manifest";
13
+ import { createPaths, type PathManifest } from "@tsplc/debug/paths";
11
14
  import { elementaryType, integerRange } from "@tsplc/iec";
12
- import { DebugAnalysis, type InstancePath, type Operand } from "./debug";
15
+ import {
16
+ DebugAnalysis,
17
+ type InstancePath,
18
+ type Operand,
19
+ storagePath,
20
+ } from "./debug";
13
21
  import {
14
22
  expressionText,
15
23
  placeText,
@@ -17,7 +25,11 @@ import {
17
25
  storageName,
18
26
  } from "./expressions";
19
27
  import { type RpcChannel, rpcSlots } from "./http";
20
- import { isStoragePath, resolveStoragePath } from "./io-paths";
28
+ import {
29
+ isStoragePath,
30
+ resolveStoragePath,
31
+ type StorageBinding,
32
+ } from "./io-paths";
21
33
  import { ioAddress } from "./manifest";
22
34
  import { Names } from "./names";
23
35
  import type { CodesysPlan } from "./plan";
@@ -25,6 +37,97 @@ import { type CodesysSymbols, type EmissionContext, required } from "./symbols";
25
37
  import { telemetryClient, telemetryObjects } from "./telemetry";
26
38
  import { stStringLiteral } from "./types";
27
39
 
40
+ /**
41
+ * The most storage paths `debug.writers.paths` may match. Each is a slot in `GVL_TsplcDebug` and
42
+ * a store on every statement that writes it.
43
+ */
44
+ export const maxWriterPaths = 256;
45
+
46
+ /** Module storage as the debugger's paths name it, for expanding `debug.writers.paths`. */
47
+ const storageShape = (core: VerifiedCoreModule): PathManifest => ({
48
+ roots: core.variables.flatMap((variable) => {
49
+ const path =
50
+ variable.storage === "module" ? storagePath(variable) : undefined;
51
+ return path
52
+ ? [{ path, target: "", type: variable.type, readable: true }]
53
+ : [];
54
+ }),
55
+ io: [],
56
+ constants: [],
57
+ types: Object.fromEntries(
58
+ core.types.flatMap((type): [string, DebugType][] => {
59
+ switch (type.kind) {
60
+ case "record":
61
+ return [
62
+ [
63
+ type.id,
64
+ {
65
+ kind: "record",
66
+ name: type.id,
67
+ fields: type.fields.map((field) => ({
68
+ name: field.name,
69
+ target: field.name,
70
+ type: field.type,
71
+ })),
72
+ },
73
+ ],
74
+ ];
75
+ case "array":
76
+ return [
77
+ [
78
+ type.id,
79
+ {
80
+ kind: "array",
81
+ element: type.element,
82
+ length: type.length,
83
+ lower: type.lowerBound,
84
+ },
85
+ ],
86
+ ];
87
+ default:
88
+ return [];
89
+ }
90
+ }),
91
+ ),
92
+ });
93
+
94
+ /**
95
+ * The module storage paths `debug.writers.paths` matches. A pattern that names a block's field or
96
+ * anything else that isn't module storage is reported, as is matching more than `maxWriterPaths`.
97
+ */
98
+ export function writerPaths(
99
+ core: VerifiedCoreModule,
100
+ settings: ResolvedDebugConfig | undefined,
101
+ report: (message: string) => void,
102
+ ): StorageBinding[] {
103
+ const writers = settings?.writers;
104
+ if (typeof writers !== "object") {
105
+ return [];
106
+ }
107
+ const expanded = (() => {
108
+ try {
109
+ return createPaths(storageShape(core)).expand(
110
+ writers.paths,
111
+ maxWriterPaths,
112
+ );
113
+ } catch (error) {
114
+ if (error instanceof RangeError) {
115
+ report(`debug.writers.paths match more than ${maxWriterPaths} values.`);
116
+ return [];
117
+ }
118
+ throw error;
119
+ }
120
+ })();
121
+ return expanded.flatMap((path) => {
122
+ const resolved = resolveStoragePath(core, path);
123
+ if ("error" in resolved) {
124
+ report(`debug.writers.paths: ${resolved.error}`);
125
+ return [];
126
+ }
127
+ return [resolved];
128
+ });
129
+ }
130
+
28
131
  /**
29
132
  * The debugger's and telemetry's names in the program: `GVL_TsplcDebug` and its fields, each
30
133
  * task's ring, and the instrumentation fields of each block.
@@ -59,6 +162,11 @@ export function planInstrumentation(
59
162
  )
60
163
  ).map(({ key, root, segments }) => ({ key, root, segments })),
61
164
  ];
165
+ for (const { key, root, segments } of plan.writerPaths) {
166
+ if (!outputs.some((output) => output.key === key)) {
167
+ outputs.push({ key, root, segments });
168
+ }
169
+ }
62
170
  const analysis = new DebugAnalysis(core, plan.deployment, settings, outputs);
63
171
  /** `GVL_TsplcDebug`, and the names of its fields. */
64
172
  const global = symbols.names.allocateObject("GVL", "TsplcDebug");
@@ -136,11 +244,28 @@ export function planInstrumentation(
136
244
  );
137
245
  }
138
246
  }
247
+ // Without a ring, a task whose writers the debugger follows records the clock itself.
248
+ const scanClocks = new Map<string, string>(
249
+ plan.writerPaths.length
250
+ ? plan.deployment.tasks.flatMap((task) =>
251
+ rings.has(task.name)
252
+ ? []
253
+ : [
254
+ [
255
+ task.name,
256
+ `${global}.${names.allocate(`scanClock_${task.name}`)}`,
257
+ ],
258
+ ],
259
+ )
260
+ : [],
261
+ );
139
262
  return {
140
263
  analysis,
141
264
  global,
142
265
  slots,
143
266
  rings,
267
+ /** Each task's clock in `GVL_TsplcDebug`, by task, when it has no ring that reads the clock. */
268
+ scanClocks,
144
269
  telemetryNames,
145
270
  jobs,
146
271
  jobIds,
@@ -231,6 +356,9 @@ export function emitDebugGlobal(
231
356
  }
232
357
 
233
358
  const fields = [`buildId : STRING(16) := '${id}'`];
359
+ for (const target of instrumentation.scanClocks.values()) {
360
+ fields.push(`${target.slice(instrumentation.global.length + 1)} : DINT`);
361
+ }
234
362
  for (const [task, field] of instrumentation.rings) {
235
363
  fields.push(
236
364
  `${field} : ${required(instrumentation.telemetryNames).writer} := (task := '${task}')`,
@@ -34,7 +34,7 @@ import { serviceOfPath } from "@tsplc/server";
34
34
  import type { HardwareCatalog } from "@tsplc/typegen/hardware";
35
35
  import { version } from "../../package.json";
36
36
  import { type InstancePath, storagePath } from "./debug";
37
- import { Sources } from "./sources";
37
+ import type { Sources } from "./sources";
38
38
  import {
39
39
  type CodesysSymbols,
40
40
  type EmissionContext,
@@ -168,7 +168,7 @@ function debugTypes(
168
168
  }
169
169
 
170
170
  /** A folded constant's JSON value; integers beyond doubles' exact range stay strings. */
171
- const constantValue = (value: Constant): unknown => {
171
+ export const constantValue = (value: Constant): unknown => {
172
172
  switch (value.kind) {
173
173
  case "integer":
174
174
  return Number.isSafeInteger(Number(value.value))
@@ -440,11 +440,13 @@ const routineTarget = (
440
440
  export function debugManifest(
441
441
  context: EmissionContext,
442
442
  ioTarget: (key: string) => { target: string; type: string } | undefined,
443
+ sources: Sources,
444
+ /** Filled with the id of each function the manifest lists, by routine. */
445
+ functionIds: Map<string, number>,
443
446
  ): DebugManifest {
444
447
  const { plan, symbols, instrumentation } = context;
445
448
  const { core, project, deployment, options } = plan;
446
449
  const settings = project.debug;
447
- const sources = new Sources(project.root);
448
450
  const global = (field: string) => `${instrumentation.global}.${field}`;
449
451
 
450
452
  const declaredFunctions = new Map<
@@ -452,18 +454,24 @@ export function debugManifest(
452
454
  { id: number; range: SourceRange }
453
455
  >();
454
456
  const routines = new Map(core.functions.map((fn) => [fn.id, fn]));
457
+ const emittedBlocks = new Map(core.blocks.map((block) => [block.id, block]));
455
458
  // A merged instance's own locals are not in the program's variables any more.
456
459
  const variables = new Map([
457
460
  ...instrumentation.analysis.variables,
458
- ...plan.specialized.flatMap((fn) =>
461
+ ...plan.specialized.functions.flatMap((fn) =>
459
462
  [...fn.parameters, ...fn.locals].map(
460
463
  (variable) => [variable.id, variable] as const,
461
464
  ),
462
465
  ),
466
+ ...plan.specialized.blocks.flatMap((block) =>
467
+ block.locals.map((variable) => [variable.id, variable] as const),
468
+ ),
463
469
  ]);
464
470
  const functions = [
465
- ...plan.specialized,
466
- ...core.blocks.filter((block) => !block.standard && !block.runtime),
471
+ ...plan.specialized.functions,
472
+ ...plan.specialized.blocks.filter(
473
+ (block) => !block.standard && !block.runtime,
474
+ ),
467
475
  ].flatMap((routine): DebugFunction[] => {
468
476
  const block = "inputs" in routine ? routine : undefined;
469
477
  const fn = "parameters" in routine ? routine : undefined;
@@ -475,12 +483,13 @@ export function debugManifest(
475
483
  // routine that only returned a constant was replaced by it, and has nothing to describe.
476
484
  const runs = fn
477
485
  ? routines.get(plan.sharedRoutines.get(fn.id) ?? fn.id)
478
- : routine;
486
+ : emittedBlocks.get(routine.id);
479
487
  if (!runs) {
480
488
  return [];
481
489
  }
482
490
  const id = declaredFunctions.size;
483
491
  declaredFunctions.set(routine.id, { id, range: declaration });
492
+ functionIds.set(routine.id, id);
484
493
  const task = instrumentation.analysis.tasks.get(runs.id);
485
494
  const origin = fn?.origin;
486
495
  return [
@@ -657,11 +666,19 @@ export function debugManifest(
657
666
  jobs,
658
667
  events,
659
668
  writers,
660
- tasks: deployment.tasks.map((task) => ({
661
- name: task.name,
662
- intervalMs: Number(task.intervalNanoseconds) / 1e6,
663
- priority: task.priority,
664
- })),
669
+ tasks: deployment.tasks.map((task) => {
670
+ // The task's ring sender reads the clock at the start of its first program.
671
+ const ring = instrumentation.rings.get(task.name);
672
+ const clock = ring
673
+ ? global(`${ring}.now`)
674
+ : instrumentation.scanClocks.get(task.name);
675
+ return {
676
+ name: task.name,
677
+ intervalMs: Number(task.intervalNanoseconds) / 1e6,
678
+ priority: task.priority,
679
+ ...(clock && { clock }),
680
+ };
681
+ }),
665
682
  errors: jobErrors,
666
683
  };
667
684
  }
@@ -2,18 +2,20 @@ import {
2
2
  type Constant,
3
3
  type CoreExpression,
4
4
  type CoreStatement,
5
- type ElementaryFunction,
6
- floatMaximum,
7
5
  type GeneratedObject,
8
6
  integerRange,
9
7
  integerType,
10
- isElementary,
11
8
  nestedBodies,
12
9
  type PlcType,
13
10
  pathIndexes,
14
11
  statementExpressions,
15
12
  subexpressions,
16
13
  } from "@tsplc/compiler/ir";
14
+ import {
15
+ type ElementaryFunction,
16
+ floatMaximum,
17
+ isElementary,
18
+ } from "@tsplc/iec/arithmetic";
17
19
 
18
20
  /** The Structured Text function each elementary function is. */
19
21
  const elementaryNames: Readonly<Record<ElementaryFunction, string>> = {
@@ -2,7 +2,6 @@
2
2
  import {
3
3
  type Constant,
4
4
  type CoreExpression,
5
- type CoreFunction,
6
5
  type CoreStatement,
7
6
  type Deployment,
8
7
  type Diagnostic,
@@ -22,6 +21,7 @@ import {
22
21
  import type {
23
22
  Publication,
24
23
  ResolvedDebugConfig,
24
+ ResolvedHmiConfig,
25
25
  ResolvedTelemetryConfig,
26
26
  ResolvedTsplcConfig,
27
27
  } from "@tsplc/config";
@@ -32,8 +32,10 @@ import { type CodesysOptions, optionsSchema } from "./config";
32
32
  import {
33
33
  type HttpEndpoint,
34
34
  resolveHttpEndpoint,
35
+ serviceBlock,
35
36
  validateHttpLayout,
36
37
  } from "./http";
38
+ import { writerPaths } from "./instrumentation";
37
39
  import {
38
40
  iecSpelling,
39
41
  isStoragePath,
@@ -63,15 +65,20 @@ export interface CodesysPlan {
63
65
  readonly [planned]: true;
64
66
  readonly core: VerifiedCoreModule;
65
67
  /**
66
- * The functions as the frontend specialized them, one per instance, and the routine each that
67
- * `shareRoutines` merged away runs as. The debug manifest describes every instance.
68
+ * The module as the frontend specialized it, one routine per instance, before programs are joined
69
+ * and routines folded, shared and forwarded, with each task's programs in that module. The debug
70
+ * manifest and explanations describe every instance, whatever the emitted routines look like.
68
71
  */
69
- readonly specialized: readonly CoreFunction[];
72
+ readonly specialized: VerifiedCoreModule;
73
+ readonly specializedTasks: Deployment;
74
+ /** The routine each specialized function that `shareRoutines` merged away runs as. */
70
75
  readonly sharedRoutines: ReadonlyMap<string, string>;
71
76
  readonly deployment: Deployment;
72
77
  readonly options: CodesysOptions;
73
78
  /** `io` keys that name authored storage, resolved against the verified types. */
74
79
  readonly storageBindings: readonly StorageBinding[];
80
+ /** The storage paths `debug.writers.paths` matches, each recorded in a last-writer slot. */
81
+ readonly writerPaths: readonly StorageBinding[];
75
82
  readonly publication: Publication;
76
83
  readonly http: Readonly<Record<string, HttpEndpoint>>;
77
84
  readonly project: CodesysProject;
@@ -92,6 +99,8 @@ export interface CodesysProject {
92
99
  "transport" | "baseUrlEnv"
93
100
  >;
94
101
  hardware?: ProjectHardware;
102
+ /** The HMI's controls, whose targets the debugger names as clients that write. */
103
+ hmi?: Pick<ResolvedHmiConfig, "controls">;
95
104
  /** Where HTTP credentials and the telemetry base URL are read from; this process's environment by default. */
96
105
  environment?: Readonly<Record<string, string | undefined>>;
97
106
  }
@@ -148,7 +157,7 @@ export function planCodesys(
148
157
  };
149
158
  const http = new Map<string, HttpEndpoint>();
150
159
  for (const block of core.blocks) {
151
- if (block.runtime?.kind === "http" || block.runtime?.kind === "rpc") {
160
+ if (serviceBlock(block)) {
152
161
  try {
153
162
  validateHttpLayout(
154
163
  block,
@@ -179,6 +188,7 @@ export function planCodesys(
179
188
  }
180
189
 
181
190
  const storageBindings = validateIo(core, options, report);
191
+ const writerBindings = writerPaths(core, project.debug, report);
182
192
  validateTasks(core, scheduled, report);
183
193
  validateStorage(core, options, report);
184
194
  validateConstants(core, report);
@@ -203,11 +213,15 @@ export function planCodesys(
203
213
 
204
214
  const plan: CodesysPlan = Object.freeze({
205
215
  core,
206
- specialized: specialized.functions,
216
+ specialized,
217
+ specializedTasks: {
218
+ tasks: schedulePrograms(specialized, deployment.tasks, () => {}),
219
+ },
207
220
  sharedRoutines: routines,
208
221
  deployment: structuredClone(scheduled),
209
222
  options: structuredClone(options),
210
223
  storageBindings,
224
+ writerPaths: writerBindings,
211
225
  publication,
212
226
  http: Object.fromEntries(http),
213
227
  project,
@@ -225,8 +239,10 @@ export function planCodesys(
225
239
  Object.freeze(value);
226
240
  };
227
241
  freeze(plan.deployment);
242
+ freeze(plan.specializedTasks);
228
243
  freeze(plan.options);
229
244
  freeze(plan.storageBindings);
245
+ freeze(plan.writerPaths);
230
246
  freeze(plan.publication);
231
247
  plans.add(plan);
232
248
  return { plan, diagnostics: [] };
@@ -28,8 +28,10 @@ export function emitScanProgram(
28
28
  (item) => item.programs[0] === program.name,
29
29
  );
30
30
  const ring = task && instrumentation.rings.get(task.name);
31
+ const clock = task && instrumentation.scanClocks.get(task.name);
31
32
  const lines = [
32
33
  ...(ring ? [`${instrumentation.global}.${ring}();`] : []),
34
+ ...(clock ? [`${clock} := TO_DINT(TIME_TO_UDINT(TIME()));`] : []),
33
35
  ...channels
34
36
  .filter((channel) => channel.input)
35
37
  .map(
@@ -3,6 +3,7 @@ import {
3
3
  type Constant,
4
4
  type Diagnostic,
5
5
  error,
6
+ type PlcModule,
6
7
  type SourceSpan,
7
8
  type TypeId,
8
9
  } from "@tsplc/compiler/ir";
@@ -188,6 +189,8 @@ export const lowerElaboration = (
188
189
  /** Routines specialized from class methods, by `<entry file>:<routine>`. */
189
190
  origins: Map<string, { name: string; instance?: string }>;
190
191
  folded: Folded[];
192
+ /** Each referable object's storage path by the id a reference holds, and the fields that hold one. */
193
+ references: NonNullable<PlcModule["references"]>;
191
194
  /** The string each member of a literal union's enum stands for, by `<types file>:<enum>`. */
192
195
  literals: Map<string, Record<string, string>>;
193
196
  } => {
@@ -196,7 +199,16 @@ export const lowerElaboration = (
196
199
  const origins = new Map<string, { name: string; instance?: string }>();
197
200
  const folded: Folded[] = [];
198
201
  const literals = new Map<string, Record<string, string>>();
199
- const result = { sources, diagnostics, origins, folded, literals };
202
+ const references: { id: number; path: string }[] = [];
203
+ const referenceFields: string[] = [];
204
+ const result = {
205
+ sources,
206
+ diagnostics,
207
+ origins,
208
+ folded,
209
+ literals,
210
+ references: { objects: references, fields: referenceFields },
211
+ };
200
212
  const runtime = runtimeSources(program).filter(
201
213
  (source) => !source.isDeclarationFile && !inSdk(sdk, source.fileName),
202
214
  );
@@ -344,6 +356,9 @@ export const lowerElaboration = (
344
356
  for (const { name, members } of specializer.layouts.literalEnums) {
345
357
  literals.set(`${typesFile}:${name}`, members);
346
358
  }
359
+ const table = specializer.storage.referenceTable();
360
+ references.push(...table.references);
361
+ referenceFields.push(...table.referenceFields);
347
362
  for (const item of specializer.storage.folded()) {
348
363
  const known = constant(item.value, item.iec);
349
364
  if (known) {
@@ -12,7 +12,7 @@ import {
12
12
  type Step,
13
13
  tsPath,
14
14
  } from "./model";
15
- import { referenceLayout, referenceType } from "./references";
15
+ import { referable, referenceLayout, referenceType } from "./references";
16
16
  import { constant, type Value } from "./values";
17
17
  import { ScanWrites } from "./writes";
18
18
 
@@ -110,9 +110,64 @@ export class Storage {
110
110
  const found =
111
111
  type !== undefined && referenceType(type) && this.written(holder, name);
112
112
  this.referenceFields.set(key, found);
113
+ if (found) {
114
+ this.references.push({ holder, name });
115
+ }
113
116
  return found;
114
117
  }
115
118
 
119
+ /** The fields that store a reference, found while laying out instances. */
120
+ private readonly references: { holder: ModelNode; name: string }[] = [];
121
+
122
+ /**
123
+ * Where each referable object is, in the storage spelling the debugger names module storage
124
+ * with, and the storage paths of fields that store a reference: the debugger shows a reference's
125
+ * id as the object it is. Empty when no field stores a reference.
126
+ */
127
+ referenceTable(): {
128
+ references: { id: number; path: string }[];
129
+ referenceFields: string[];
130
+ } {
131
+ if (!this.references.length) {
132
+ return { references: [], referenceFields: [] };
133
+ }
134
+ return {
135
+ references: this.model.nodes.flatMap((node) => {
136
+ const path = referable(node) ? this.storagePlace(node) : undefined;
137
+ return path === undefined ? [] : [{ id: node.id, path }];
138
+ }),
139
+ referenceFields: this.references.flatMap(({ holder, name }) => {
140
+ const path = this.storagePlace(holder);
141
+ return path === undefined ? [] : [`${path}.${name}`];
142
+ }),
143
+ };
144
+ }
145
+
146
+ /** A node's place as module storage: its root's module, the root unless flattened, then fields and indexes. */
147
+ private storagePlace(node: ModelNode): string | undefined {
148
+ const owner = node.owner;
149
+ if (!owner) {
150
+ return undefined;
151
+ }
152
+ const root = this.flattened(owner.root)
153
+ ? owner.root.name
154
+ : `${owner.root.name}.${owner.root.name}`;
155
+ return (
156
+ root +
157
+ owner.steps
158
+ .map((step, index) => {
159
+ const holder = this.model.at(owner.root, owner.steps.slice(0, index));
160
+ if (step.kind === "index") {
161
+ return holder && this.mixedStates(holder)
162
+ ? `.${mixedItem(step.index)}`
163
+ : `[${step.index}]`;
164
+ }
165
+ return /^\d+$/.test(step.name) ? `[${step.name}]` : `.${step.name}`;
166
+ })
167
+ .join("")
168
+ );
169
+ }
170
+
116
171
  /** Asked of every field each time an instance's layout is, so answered once. */
117
172
  private readonly referenceFields = new Map<string, boolean>();
118
173
 
@@ -1,7 +1,7 @@
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
+
2
3
  import {
3
4
  aggregate,
4
- type BinaryOperator,
5
5
  type Constant,
6
6
  canAssign,
7
7
  comparisonOperators,
@@ -19,12 +19,12 @@ import {
19
19
  type PlcType,
20
20
  parseInteger,
21
21
  placeType,
22
- roundFloat,
23
22
  type SourceSpan,
24
23
  type Statement,
25
24
  type Variable,
26
25
  valueRange,
27
26
  } from "@tsplc/compiler/ir";
27
+ import { type BinaryOperator, roundFloat } from "@tsplc/iec/arithmetic";
28
28
  import ts from "typescript";
29
29
  import type { BlockResolver, BlockSource } from "./blocks";
30
30
  import { intrinsicExpression } from "./intrinsics";
@@ -4,10 +4,9 @@ import {
4
4
  defaultValue,
5
5
  durationLiteral,
6
6
  type Expression,
7
- elementaryFunctions,
8
7
  parseInteger,
9
- type UnaryOperator,
10
8
  } from "@tsplc/compiler/ir";
9
+ import { elementaryFunctions, type UnaryOperator } from "@tsplc/iec/arithmetic";
11
10
  import ts from "typescript";
12
11
  import type { ExpressionLowering } from "./expressions";
13
12
  import { numericLiteral } from "./types";
@@ -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
+
2
3
  import {
3
4
  aggregate,
4
5
  type Constant,
@@ -6,13 +7,13 @@ import {
6
7
  type IntegerInterval,
7
8
  integerRange,
8
9
  loopBounds,
9
- loopIterations,
10
10
  maxLoopIterations,
11
11
  type PlcFunction,
12
12
  type PlcType,
13
13
  type Statement,
14
14
  type Variable,
15
15
  } from "@tsplc/compiler/ir";
16
+ import { loopIterations } from "@tsplc/iec/arithmetic";
16
17
  import ts from "typescript";
17
18
  import type { AnalysisContext, ExpressionLowering } from "./expressions";
18
19
  import type { Positions } from "./positions";
@@ -483,7 +484,7 @@ export class StatementLowering {
483
484
  const direction = ascending ? 1n : -1n;
484
485
  const finish = BigInt(bound.value) - (exclusive ? direction : 0n);
485
486
  const first = BigInt(start.value);
486
- const count = loopIterations(first, finish, step);
487
+ const count = loopIterations(first, BigInt(bound.value), exclusive, step);
487
488
  this.checkIterations(node, count);
488
489
  if (existing) {
489
490
  this.checkFinalIncrement(node, plcType, first + count * step);