@tsplc/compiler 0.5.6 → 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.
Files changed (49) hide show
  1. package/dist/bun-runtime.js +139 -30
  2. package/dist/bun-runtime.js.map +8 -7
  3. package/dist/cli.js +24 -9
  4. package/dist/cli.js.map +6 -6
  5. package/dist/codesys.js +3237 -1957
  6. package/dist/codesys.js.map +19 -18
  7. package/dist/index.js +54 -6
  8. package/dist/index.js.map +8 -8
  9. package/dist/ir.js +1645 -1326
  10. package/dist/ir.js.map +13 -12
  11. package/dist/project.js +12 -6
  12. package/dist/project.js.map +4 -4
  13. package/package.json +9 -9
  14. package/src/codesys/debug.ts +17 -2
  15. package/src/codesys/emit.ts +40 -12
  16. package/src/codesys/explain.ts +1465 -0
  17. package/src/codesys/global-lists.ts +21 -9
  18. package/src/codesys/http.ts +125 -71
  19. package/src/codesys/instrumentation.ts +161 -9
  20. package/src/codesys/manifest.ts +29 -12
  21. package/src/codesys/numeric.ts +5 -3
  22. package/src/codesys/plan.ts +22 -6
  23. package/src/codesys/programs.ts +2 -0
  24. package/src/codesys/routines.ts +39 -9
  25. package/src/codesys/st-files.ts +73 -6
  26. package/src/codesys/telemetry.ts +70 -35
  27. package/src/frontend/elaborate/index.ts +16 -1
  28. package/src/frontend/elaborate/storage.ts +56 -1
  29. package/src/frontend/expressions.ts +2 -2
  30. package/src/frontend/intrinsics.ts +1 -2
  31. package/src/frontend/statements.ts +3 -2
  32. package/src/frontend/typescript.ts +3 -0
  33. package/src/ir/conditions.ts +895 -0
  34. package/src/ir/core-model.ts +2 -2
  35. package/src/ir/fold.ts +15 -107
  36. package/src/ir/index.ts +10 -11
  37. package/src/ir/link.ts +1 -0
  38. package/src/ir/model.ts +16 -79
  39. package/src/ir/numeric.ts +5 -41
  40. package/src/ir/ranges.ts +8 -14
  41. package/src/ir/scalars.ts +6 -4
  42. package/src/project/debugger.ts +9 -0
  43. package/src/project/project.ts +6 -0
  44. package/src/project/release.ts +7 -4
  45. package/src/runtime/async.ts +15 -12
  46. package/src/runtime/launch.ts +11 -4
  47. package/src/runtime/runtime.ts +26 -23
  48. package/src/runtime/telemetry.ts +14 -6
  49. package/src/runtime/transport.ts +172 -0
@@ -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(
@@ -1,5 +1,6 @@
1
1
  import {
2
2
  type Constant,
3
+ type CoreExpression,
3
4
  type CoreFunction,
4
5
  type CoreFunctionBlock,
5
6
  type CoreStatement,
@@ -181,6 +182,23 @@ export function emitRoutine(
181
182
  }
182
183
  };
183
184
 
185
+ const assignResult = (
186
+ destination: string,
187
+ value: CoreExpression,
188
+ depth: number,
189
+ span: SourceSpan,
190
+ ): void => {
191
+ if (value.kind === "constant") {
192
+ assignConstant(destination, value.value, value.type, depth, span);
193
+ } else {
194
+ write(
195
+ `${destination} := ${expressionText(storage, value)};`,
196
+ depth,
197
+ span,
198
+ );
199
+ }
200
+ };
201
+
184
202
  const tracked = block && instrumentation.fields.get(block.id);
185
203
  const body = (items: readonly CoreStatement[], depth: number): void => {
186
204
  for (const item of items) {
@@ -406,8 +424,19 @@ export function emitRoutine(
406
424
  case "return":
407
425
  writeProbes(probes, write, item, depth);
408
426
  if (block) {
409
- if (item.value) {
410
- const returned = expressionText(storage, item.value);
427
+ const { value } = item;
428
+ if (value?.kind === "constant" && value.value.kind === "record") {
429
+ for (const output of block.outputs) {
430
+ assignConstant(
431
+ storageName(storage, output.id),
432
+ required(value.value.fields[output.name]),
433
+ output.type,
434
+ depth,
435
+ item.span,
436
+ );
437
+ }
438
+ } else if (value) {
439
+ const returned = expressionText(storage, value);
411
440
  for (const output of block.outputs) {
412
441
  write(
413
442
  `${storageName(storage, output.id)} := ${returned}.${targetTypes.field(required(block.result), output.name)};`,
@@ -418,18 +447,19 @@ export function emitRoutine(
418
447
  }
419
448
  } else if (program) {
420
449
  if (item.value) {
421
- write(
422
- `${required(symbols.programResults.get(fn.id))} := ${expressionText(storage, item.value)};`,
450
+ assignResult(
451
+ required(symbols.programResults.get(fn.id)),
452
+ item.value,
423
453
  depth,
424
454
  item.span,
425
455
  );
426
456
  }
427
457
  } else if (!method || fn.result) {
428
- write(
429
- `${name} := ${item.value ? expressionText(storage, item.value) : "TRUE"};`,
430
- depth,
431
- item.span,
432
- );
458
+ if (item.value) {
459
+ assignResult(name, item.value, depth, item.span);
460
+ } else {
461
+ write(`${name} := TRUE;`, depth, item.span);
462
+ }
433
463
  }
434
464
  if (mutex) {
435
465
  release(mutex, depth, item.span);
@@ -129,17 +129,84 @@ function objectPaths(
129
129
  );
130
130
  return `${objectPath(owner)}/methods/${object.name}`;
131
131
  }
132
+ const folders = required(placed.get(object));
133
+ return [folderPath(folders), object.name].filter(Boolean).join("/");
134
+ };
135
+ const placedFolders = (object: GeneratedObject): string[] => {
132
136
  const folders = sourceFolders(plan.project.root, sourceModule(object));
133
137
  if (!folders) {
134
- return `${generatedFolder(object)}/${object.name}`;
138
+ return [generatedFolder(object)];
135
139
  }
136
140
  // A DUT directory can also contain sibling input/output layouts. Keep
137
141
  // that directory for every DUT, or its primary type would block the folder.
138
- const kept =
139
- object.kind !== "dataType" && folders.at(-1) === object.name
140
- ? folders.slice(0, -1)
141
- : folders;
142
- return [...kept, object.name].join("/");
142
+ return object.kind !== "dataType" && folders.at(-1) === object.name
143
+ ? folders.slice(0, -1)
144
+ : folders;
143
145
  };
146
+ const placed = new Map(
147
+ objects
148
+ .filter((object) => object.kind !== "method")
149
+ .map((object) => [object, placedFolders(object)]),
150
+ );
151
+ const folderPath = separatedFolders(
152
+ [...placed].map(([object, folders]) => ({ folders, name: object.name })),
153
+ );
144
154
  return objectPath;
145
155
  }
156
+
157
+ /**
158
+ * Each folder's path once no folder shares its name with an object beside it. CODESYS refuses that,
159
+ * ignoring case, as when a module's folder is named like an object another module places next to it:
160
+ * the folder takes the next free numbered name. Folders only organize the project, so no IEC name changes.
161
+ */
162
+ export function separatedFolders(
163
+ objects: readonly { folders: readonly string[]; name: string }[],
164
+ ): (folders: readonly string[]) => string {
165
+ const childrenOf = (entries: Iterable<readonly [string, string]>) => {
166
+ const children = new Map<string, Set<string>>();
167
+ for (const [parent, name] of entries) {
168
+ const names = children.get(parent) ?? new Set<string>();
169
+ names.add(name.toLowerCase());
170
+ children.set(parent, names);
171
+ }
172
+ return (parent: string) => children.get(parent) ?? new Set<string>();
173
+ };
174
+ const objectsIn = childrenOf(
175
+ objects.map(({ folders, name }) => [folders.join("/"), name] as const),
176
+ );
177
+ const foldersIn = childrenOf(
178
+ objects.flatMap(({ folders }) =>
179
+ folders.map((name, depth) => [folders.slice(0, depth).join("/"), name]),
180
+ ),
181
+ );
182
+ const renamed = new Map<string, string>();
183
+ const given = new Map<string, Set<string>>();
184
+ const folderPath = (folders: readonly string[]): string => {
185
+ const key = folders.join("/");
186
+ const known = renamed.get(key);
187
+ if (known !== undefined) {
188
+ return known;
189
+ }
190
+ if (folders.length === 0) {
191
+ return "";
192
+ }
193
+ const parentKey = folders.slice(0, -1).join("/");
194
+ const name = required(folders.at(-1));
195
+ const taken = given.get(parentKey) ?? new Set<string>();
196
+ given.set(parentKey, taken);
197
+ const blocked = (candidate: string) =>
198
+ objectsIn(parentKey).has(candidate.toLowerCase()) ||
199
+ taken.has(candidate.toLowerCase()) ||
200
+ (candidate !== name && foldersIn(parentKey).has(candidate.toLowerCase()));
201
+ const free = (count: number): string =>
202
+ blocked(`${name}_${count}`) ? free(count + 1) : `${name}_${count}`;
203
+ const chosen = blocked(name) ? free(2) : name;
204
+ taken.add(chosen.toLowerCase());
205
+ const path = [folderPath(folders.slice(0, -1)), chosen]
206
+ .filter(Boolean)
207
+ .join("/");
208
+ renamed.set(key, path);
209
+ return path;
210
+ };
211
+ return folderPath;
212
+ }
@@ -21,6 +21,7 @@ import {
21
21
  httpMethods,
22
22
  jsonScalar,
23
23
  nativeHttp,
24
+ opcuaClient,
24
25
  resolveHttpEndpoint,
25
26
  } from "./http";
26
27
  import { Sources } from "./sources";
@@ -361,11 +362,31 @@ export function planTelemetry(
361
362
 
362
363
  const server = project.server;
363
364
  const base = server?.baseUrlEnv && project.environment[server.baseUrlEnv];
365
+ const plan: TelemetryPlan = {
366
+ ...settings,
367
+ // One ring per task holds the trace too.
368
+ capacity: Math.max(
369
+ settings.capacity,
370
+ project.trace ? project.trace.capacity : 0,
371
+ ),
372
+ calls,
373
+ failures,
374
+ ...(project.trace && { traceOperands: project.trace.operands }),
375
+ };
364
376
  if (server?.transport === "opcua") {
365
- report(
366
- `Telemetry posts to the app server's ${telemetryPath} over HTTP; set server.transport to "http".`,
367
- );
368
- return {};
377
+ return {
378
+ telemetry: plan,
379
+ endpoint: {
380
+ transport: "opcua",
381
+ host: "",
382
+ port: 0,
383
+ authority: "",
384
+ path: telemetryPath,
385
+ token: "",
386
+ timeoutMs: options.http.timeoutMs,
387
+ tls: false,
388
+ },
389
+ };
369
390
  }
370
391
  if (!base) {
371
392
  report(
@@ -375,17 +396,7 @@ export function planTelemetry(
375
396
  }
376
397
  try {
377
398
  return {
378
- telemetry: {
379
- ...settings,
380
- // One ring per task holds the trace too.
381
- capacity: Math.max(
382
- settings.capacity,
383
- project.trace ? project.trace.capacity : 0,
384
- ),
385
- calls,
386
- failures,
387
- ...(project.trace && { traceOperands: project.trace.operands }),
388
- },
399
+ telemetry: plan,
389
400
  endpoint: resolveHttpEndpoint(
390
401
  `${base.replace(/\/+$/, "")}${telemetryPath}`,
391
402
  options.http,
@@ -452,20 +463,23 @@ const batchRecords = (recordBytes: number) => {
452
463
  * shared `Trace`, and a body each scan runs first that counts the scan, reads the clock and
453
464
  * sends. It encodes with the HTTP blocks' JSON methods, and sends through a native HTTP block.
454
465
  */
466
+ /** How the sender reaches the server: its HTTP client's endpoint and network, or the OPC UA slots it posts through. */
467
+ export type TelemetryTransport =
468
+ | { kind: "http"; endpoint: HttpEndpoint; network: string }
469
+ | { kind: "opcua"; timeoutMs: number; rpcGlobal: string };
470
+
455
471
  export function telemetryObjects({
456
472
  plan,
457
473
  names,
458
474
  target,
459
- endpoint,
460
- network,
475
+ transport,
461
476
  build,
462
477
  types,
463
478
  }: {
464
479
  plan: TelemetryPlan;
465
480
  names: { writer: string; record: string; client: string };
466
481
  target: CodesysTypes;
467
- endpoint: HttpEndpoint;
468
- network: string;
482
+ transport: TelemetryTransport;
469
483
  build: string;
470
484
  types: ReadonlyMap<string, PlcType>;
471
485
  }): GeneratedObject[] {
@@ -623,18 +637,42 @@ export function telemetryObjects({
623
637
  const helpers = httpMethods(writer).filter((item) =>
624
638
  ["ByteLength", "Append", "WriteString"].includes(item.name),
625
639
  );
626
- const [client, ...clientLifecycle] = nativeHttp({
627
- id: telemetryClient,
628
- name: names.client,
629
- ports: `VAR_INPUT\nstart : BOOL;\ncancel : BOOL;\nEND_VAR\nVAR_IN_OUT\nbody : STRING(${plcBufferBytes});\nEND_VAR\nVAR_OUTPUT\nbusy : BOOL;\ndone : BOOL;\nerror : UDINT;\nEND_VAR`,
630
- port: (label) => label,
631
- endpoint,
632
- network,
633
- method: "POST",
634
- json: true,
635
- body: "Append(body);",
636
- decode: "",
637
- });
640
+ const clientPorts = `VAR_INPUT\nstart : BOOL;\ncancel : BOOL;\nEND_VAR\nVAR_IN_OUT\nbody : STRING(${plcBufferBytes});\nEND_VAR\nVAR_OUTPUT\nbusy : BOOL;\ndone : BOOL;\nerror : UDINT;\nEND_VAR`;
641
+ const clientObjects =
642
+ transport.kind === "opcua"
643
+ ? [
644
+ opcuaClient({
645
+ id: telemetryClient,
646
+ name: names.client,
647
+ ports: clientPorts,
648
+ port: (label) => label,
649
+ timeoutMs: transport.timeoutMs,
650
+ rpcGlobal: transport.rpcGlobal,
651
+ body: "Append(body);",
652
+ decode: "",
653
+ }),
654
+ ...httpMethods(telemetryClient, "opcua"),
655
+ ]
656
+ : [
657
+ ...nativeHttp({
658
+ id: telemetryClient,
659
+ name: names.client,
660
+ ports: clientPorts,
661
+ port: (label) => label,
662
+ endpoint: transport.endpoint,
663
+ network: transport.network,
664
+ method: "POST",
665
+ json: true,
666
+ body: "Append(body);",
667
+ decode: "",
668
+ }),
669
+ ...httpMethods(telemetryClient),
670
+ ...httpCertificateVerifier(
671
+ telemetryClient,
672
+ names.client,
673
+ transport.endpoint,
674
+ ),
675
+ ];
638
676
  return [
639
677
  {
640
678
  id: "tsplc:telemetryRecord",
@@ -772,9 +810,6 @@ WriteString(text);
772
810
  ...calls,
773
811
  ...failures,
774
812
  ...trace,
775
- client,
776
- ...clientLifecycle,
777
- ...httpMethods(telemetryClient),
778
- ...httpCertificateVerifier(telemetryClient, names.client, endpoint),
813
+ ...clientObjects,
779
814
  ];
780
815
  }
@@ -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);
@@ -375,6 +375,9 @@ function attachLowerings(
375
375
  if (elaboration.folded.length) {
376
376
  module.folded = elaboration.folded;
377
377
  }
378
+ if (elaboration.references?.fields.length) {
379
+ module.references = elaboration.references;
380
+ }
378
381
  for (const entry of module.programs) {
379
382
  const background = lowering.schedules.get(entry.name);
380
383
  if (background) {