@tsplc/typegen 0.5.14 → 0.5.16

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.
@@ -1,4 +1,3 @@
1
- // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
2
1
  export interface EdsParameter {
3
2
  id: string;
4
3
  name: string;
@@ -71,8 +70,30 @@ const cipTypes: Record<number, string> = {
71
70
  212: "LWORD",
72
71
  };
73
72
 
73
+ /** Field positions in a `[Connection Manager]` record; fields from the name on are strings. */
74
+ const connectionFields = {
75
+ transport: 0,
76
+ outputSize: 3,
77
+ outputFormat: 4,
78
+ inputSize: 6,
79
+ inputFormat: 7,
80
+ name: 12,
81
+ path: 14,
82
+ } as const;
83
+
84
+ /** Field positions in an `[Assembly]` record; members follow as pairs of bits and parameter. */
85
+ const assemblyFields = {
86
+ name: 0,
87
+ path: 1,
88
+ size: 2,
89
+ descriptor: 3,
90
+ firstMember: 6,
91
+ } as const;
92
+
93
+ const isConnection = (key: string) => /^Connection\d+$/.test(key);
94
+
74
95
  /** A record's fields, and where the record (key through semicolon) sits in the EDS text. */
75
- export interface EdsRecord {
96
+ interface EdsRecord {
76
97
  fields: string[];
77
98
  start: number;
78
99
  end: number;
@@ -141,7 +162,7 @@ function recordFields(body: string): string[] {
141
162
  * EDS records are comma separated, terminated by semicolons, with $ comments.
142
163
  * Sections and their records keep file order.
143
164
  */
144
- export function edsSections(text: string): Map<string, Map<string, EdsRecord>> {
165
+ function edsSections(text: string): Map<string, Map<string, EdsRecord>> {
145
166
  const { clean, offsets } = stripComments(text);
146
167
  const sections = new Map<string, Map<string, EdsRecord>>();
147
168
  let section: Map<string, EdsRecord> | undefined;
@@ -166,15 +187,20 @@ export function edsSections(text: string): Map<string, Map<string, EdsRecord>> {
166
187
  if (!section) {
167
188
  throw new Error("EDS record outside a section.");
168
189
  }
169
- // The pattern's record branch always captures a key and a (possibly empty) body.
170
- if (section.has(key!)) {
190
+ const start = offsets[match.index];
191
+ const last = offsets[end - 1];
192
+ if (
193
+ key === undefined ||
194
+ body === undefined ||
195
+ start === undefined ||
196
+ last === undefined
197
+ ) {
198
+ throw new Error("Malformed EDS record or section.");
199
+ }
200
+ if (section.has(key)) {
171
201
  throw new Error(`Duplicate EDS record ${key}.`);
172
202
  }
173
- section.set(key!, {
174
- fields: recordFields(body!),
175
- start: offsets[match.index]!,
176
- end: offsets[end - 1]! + 1,
177
- });
203
+ section.set(key, { fields: recordFields(body), start, end: last + 1 });
178
204
  }
179
205
  if (clean.slice(end).trim()) {
180
206
  throw new Error("Unterminated EDS record.");
@@ -182,7 +208,6 @@ export function edsSections(text: string): Map<string, Map<string, EdsRecord>> {
182
208
  return sections;
183
209
  }
184
210
 
185
- /** Each section's records, keyed by record name, as field lists. */
186
211
  export function readEdsRecords(
187
212
  text: string,
188
213
  ): Record<string, Record<string, string[]>> {
@@ -287,10 +312,7 @@ function logicalPath(
287
312
  const optionalNumber = (value: string | undefined) =>
288
313
  value?.trim() && Number.isFinite(Number(value)) ? Number(value) : undefined;
289
314
 
290
- export function parseEds(
291
- text: string,
292
- file = "device.eds",
293
- ): HardwareDescriptor {
315
+ export function parseEds(text: string, file: string): HardwareDescriptor {
294
316
  const records = readEdsRecords(text);
295
317
  const device = records.Device;
296
318
  if (!device?.ProdName?.[0]) {
@@ -338,12 +360,12 @@ export function parseEds(
338
360
  };
339
361
  };
340
362
  const connections = Object.entries(records["Connection Manager"] ?? {})
341
- .filter(([id]) => /^Connection\d+$/.test(id))
363
+ .filter(([id]) => isConnection(id))
342
364
  .map(([id, fields]): EdsConnection => {
343
- const path = fields[14] ?? "";
365
+ const path = fields[connectionFields.path] ?? "";
344
366
  const points = logicalPath(path, params).points;
345
- const outputSize = size(fields[3]);
346
- const inputSize = size(fields[6]);
367
+ const outputSize = size(fields[connectionFields.outputSize]);
368
+ const inputSize = size(fields[connectionFields.inputSize]);
347
369
  const assembly = (
348
370
  reference: string | undefined,
349
371
  point: number | undefined,
@@ -368,7 +390,9 @@ export function parseEds(
368
390
  if (!/^Assem\d+$/.test(reference) || !record) {
369
391
  throw new Error(`${file}: unknown connection assembly ${reference}.`);
370
392
  }
371
- const instance = point ?? logicalPath(record[1] ?? "", params).instance;
393
+ const instance =
394
+ point ??
395
+ logicalPath(record[assemblyFields.path] ?? "", params).instance;
372
396
  if (instance === undefined) {
373
397
  throw new Error(`${file}: no runtime instance for ${reference}.`);
374
398
  }
@@ -383,14 +407,22 @@ export function parseEds(
383
407
  };
384
408
  return {
385
409
  id,
386
- name: fields[12] || id,
410
+ name: fields[connectionFields.name] || id,
387
411
  // Trigger and transport bits 24-27 give the connection type; 4 is exclusive owner.
388
412
  owner:
389
- /^0x[\da-f]{8}$/i.test(fields[0] ?? "") &&
390
- ((Number(fields[0]) >>> 24) & 0xf) === 4,
413
+ /^0x[\da-f]{8}$/i.test(fields[connectionFields.transport] ?? "") &&
414
+ ((Number(fields[connectionFields.transport]) >>> 24) & 0xf) === 4,
391
415
  path,
392
- outputAssembly: assembly(fields[4], points.at(-2), outputSize),
393
- inputAssembly: assembly(fields[7], points.at(-1), inputSize),
416
+ outputAssembly: assembly(
417
+ fields[connectionFields.outputFormat],
418
+ points.at(-2),
419
+ outputSize,
420
+ ),
421
+ inputAssembly: assembly(
422
+ fields[connectionFields.inputFormat],
423
+ points.at(-1),
424
+ inputSize,
425
+ ),
394
426
  outputSize,
395
427
  inputSize,
396
428
  };
@@ -400,7 +432,11 @@ export function parseEds(
400
432
  .map(([id, fields]): EdsAssembly => {
401
433
  const members: EdsMember[] = [];
402
434
  let offsetBits = 0;
403
- for (let index = 6; index < fields.length; index += 2) {
435
+ for (
436
+ let index = assemblyFields.firstMember;
437
+ index < fields.length;
438
+ index += 2
439
+ ) {
404
440
  if (!fields[index] && !fields[index + 1]) {
405
441
  continue;
406
442
  }
@@ -425,8 +461,9 @@ export function parseEds(
425
461
  });
426
462
  offsetBits += bits;
427
463
  }
428
- const size = fields[2]
429
- ? integer(fields[2], `${id} size`, { minimum: 0 })
464
+ const declared = fields[assemblyFields.size];
465
+ const size = declared
466
+ ? integer(declared, `${id} size`, { minimum: 0 })
430
467
  : Math.ceil(offsetBits / 8);
431
468
  if (offsetBits > size * 8) {
432
469
  throw new Error(
@@ -434,10 +471,16 @@ export function parseEds(
434
471
  );
435
472
  }
436
473
  const instance =
437
- logicalPath(fields[1] ?? "", params).instance ?? instances.get(id);
438
- return { id, instance, name: fields[0] || id, size, members };
474
+ logicalPath(fields[assemblyFields.path] ?? "", params).instance ??
475
+ instances.get(id);
476
+ return {
477
+ id,
478
+ instance,
479
+ name: fields[assemblyFields.name] || id,
480
+ size,
481
+ members,
482
+ };
439
483
  });
440
- // A connection's raw payload, with no record to name its members.
441
484
  for (const [instance, payloadSize] of recordless) {
442
485
  if (!assemblies.some((assembly) => assembly.instance === instance)) {
443
486
  assemblies.push({
@@ -459,3 +502,94 @@ export function parseEds(
459
502
  connections,
460
503
  };
461
504
  }
505
+
506
+ const quoted = (value: string) => `"${value.replaceAll('"', '""')}"`;
507
+
508
+ /**
509
+ * Reduce an EDS to the selected connection with raw byte assemblies of the selected
510
+ * payload sizes. CODESYS's EDS import then creates one BYTE channel per payload
511
+ * byte, so each channel sits at its assembly offset. Member layouts would instead
512
+ * become typed channels that CODESYS packs independently, and it maps only the
513
+ * first byte of a multi-byte member such as a reader's result data.
514
+ */
515
+ export function normalizeEds(
516
+ text: string,
517
+ selection: { connection: string; inputSize?: number; outputSize?: number },
518
+ ): string {
519
+ const sections = edsSections(text);
520
+ const connections = [...(sections.get("Connection Manager") ?? [])].filter(
521
+ ([key]) => isConnection(key),
522
+ );
523
+ const selected = connections.find(
524
+ ([key]) => key === selection.connection,
525
+ )?.[1];
526
+ if (!selected) {
527
+ throw new Error(`EDS has no ${selection.connection}.`);
528
+ }
529
+ const fields = [...selected.fields];
530
+ const resized = new Map<string, number>();
531
+ for (const [sizeField, formatField, size] of [
532
+ [
533
+ connectionFields.outputSize,
534
+ connectionFields.outputFormat,
535
+ selection.outputSize,
536
+ ],
537
+ [
538
+ connectionFields.inputSize,
539
+ connectionFields.inputFormat,
540
+ selection.inputSize,
541
+ ],
542
+ ] as const) {
543
+ const assembly = fields[formatField];
544
+ if (!assembly) {
545
+ continue;
546
+ }
547
+ if (size === undefined) {
548
+ throw new Error(`Select a payload size for ${assembly}.`);
549
+ }
550
+ fields[sizeField] = String(size);
551
+ resized.set(assembly, size);
552
+ }
553
+ const edits = connections.map(([, record]) => ({
554
+ start: record.start,
555
+ end: record.end,
556
+ text:
557
+ record === selected
558
+ ? `Connection1 = ${fields.map((value, index) => (index >= connectionFields.name ? quoted(value) : value)).join(",")};`
559
+ : "",
560
+ }));
561
+ for (const [key, record] of sections.get("Assembly") ?? []) {
562
+ const size = resized.get(key);
563
+ if (size === undefined) {
564
+ continue;
565
+ }
566
+ const path = record.fields[assemblyFields.path] ?? "";
567
+ // One padding member spans the whole payload.
568
+ const rawBytes = [
569
+ quoted(record.fields[assemblyFields.name] ?? ""),
570
+ path && quoted(path),
571
+ size,
572
+ record.fields[assemblyFields.descriptor] ?? "",
573
+ "",
574
+ "",
575
+ size * 8,
576
+ "",
577
+ ];
578
+ edits.push({
579
+ start: record.start,
580
+ end: record.end,
581
+ text: `${key} = ${rawBytes.join(",")};`,
582
+ });
583
+ resized.delete(key);
584
+ }
585
+ if (resized.size) {
586
+ throw new Error(`EDS has no ${[...resized.keys()].join(", ")} assembly.`);
587
+ }
588
+ return edits
589
+ .sort((a, b) => b.start - a.start)
590
+ .reduce(
591
+ (result, edit) =>
592
+ result.slice(0, edit.start) + edit.text + result.slice(edit.end),
593
+ text,
594
+ );
595
+ }
@@ -1,7 +1,8 @@
1
- // biome-ignore-all lint/suspicious/noTemplateCurlyInString: These strings describe Docker or generated TypeScript interpolation, not JavaScript interpolation here.
2
- import { ioScalarBits } from "@tsplc/iec";
3
- import type { HardwareCatalog } from "../hardware";
4
- import { addressSize, ioLayout } from "./process-image";
1
+ // biome-ignore-all lint/suspicious/noTemplateCurlyInString: These strings are generated TypeScript template literal types, not JavaScript interpolation.
2
+ import { relative, sep } from "node:path";
3
+ import { sizePrefixes } from "@tsplc/iec";
4
+ import type { HardwareCatalog } from "./catalog";
5
+ import { addressSize, ioLayout, layoutBits } from "./process-image";
5
6
 
6
7
  /** A bindable `io` key with its layout; array indexes appear as the literal `${number}`. */
7
8
  export interface IoTarget {
@@ -14,18 +15,44 @@ export interface ProjectTargets {
14
15
  publication: readonly string[];
15
16
  }
16
17
 
17
- // Integer layouts are INTn and the others are named for their type.
18
+ const region = '${"I" | "Q"}';
19
+ const bitAddress = `\`%${region}X\${number}.\${0 | 1 | 2 | 3 | 4 | 5 | 6 | 7}\``;
20
+ const byteSizes = [...sizePrefixes]
21
+ .filter(
22
+ ([prefix, type]) => type.bits > 1 && addressSize(type.bits) === prefix,
23
+ )
24
+ .map(([prefix]) => JSON.stringify(prefix))
25
+ .join(" | ");
26
+ const addressBinding = (address: string) =>
27
+ `{ address: ${address}; type?: string }`;
28
+
18
29
  const directBinding = (layout: string): string | undefined => {
19
- const scalar = layout.replace(/^\d+x/, "");
20
- const integer = /^INT(\d+)$/.exec(scalar);
21
- const bits = integer ? Number(integer[1]) : ioScalarBits(scalar);
30
+ const bits = layoutBits(layout);
22
31
  const size = bits === undefined ? undefined : addressSize(bits);
23
32
  if (!size) {
24
33
  return undefined;
25
34
  }
26
- return size === "X"
27
- ? '{ address: `%${"I" | "Q"}X${number}.${0 | 1 | 2 | 3 | 4 | 5 | 6 | 7}`; type?: string }'
28
- : `{ address: \`%\${"I" | "Q"}${size}\${number}\`; type?: string }`;
35
+ return addressBinding(
36
+ size === "X" ? bitAddress : `\`%${region}${size}\${number}\``,
37
+ );
38
+ };
39
+
40
+ /** The catalog with its descriptor paths relative to the project, as the generated file carries it. */
41
+ const portableCatalog = (
42
+ catalog: HardwareCatalog,
43
+ root: string,
44
+ ): HardwareCatalog => {
45
+ const portable = (file: string) => relative(root, file).split(sep).join("/");
46
+ return {
47
+ descriptors: catalog.descriptors.map((descriptor) => ({
48
+ ...descriptor,
49
+ file: portable(descriptor.file),
50
+ })),
51
+ devices: catalog.devices.map((device) => ({
52
+ ...device,
53
+ descriptor: portable(device.descriptor),
54
+ })),
55
+ };
29
56
  };
30
57
 
31
58
  /**
@@ -35,13 +62,22 @@ const directBinding = (layout: string): string | undefined => {
35
62
  */
36
63
  export function generateHardwareTypes(
37
64
  catalog: HardwareCatalog,
38
- targets?: readonly IoTarget[],
39
- publication?: readonly string[],
40
- ioTypes = true,
65
+ {
66
+ root,
67
+ targets,
68
+ ioTypes,
69
+ }: {
70
+ /** The project root, which the generated catalog's descriptor paths are relative to. */
71
+ root: string;
72
+ targets: ProjectTargets | null;
73
+ /** Also emit the I/O binding types and the device catalog, not just the publication selectors. */
74
+ ioTypes: boolean;
75
+ },
41
76
  ): string {
42
77
  const selectors =
43
- publication?.map((selector) => JSON.stringify(selector)).join(" | ") ??
44
- "string";
78
+ targets?.publication
79
+ .map((selector) => JSON.stringify(selector))
80
+ .join(" | ") ?? "string";
45
81
  const publicationTypes = `// Generated by tsPLC. Run tsplc typegen after changing EDS files, device selections or PLC storage.\nexport type PublicationSelector = ${selectors || "never"};\nexport type PlcPublication = { readonly production: readonly PublicationSelector[]; readonly development: readonly PublicationSelector[] };\n`;
46
82
  if (!ioTypes) {
47
83
  return publicationTypes;
@@ -63,16 +99,17 @@ export function generateHardwareTypes(
63
99
  layout: ioLayout(item.type),
64
100
  })),
65
101
  );
66
- const direct =
67
- '{ address: `%${"I" | "Q"}${"B" | "W" | "D"}${number}` | `%${"I" | "Q"}X${number}.${0 | 1 | 2 | 3 | 4 | 5 | 6 | 7}`; type?: string }';
102
+ const direct = addressBinding(
103
+ `\`%${region}\${${byteSizes}}\${number}\` | ${bitAddress}`,
104
+ );
68
105
  const anyBinding = [...channels.map((item) => item.binding), direct].join(
69
106
  "\n | ",
70
107
  );
71
108
  const mapping = targets
72
- ? [...new Set(targets.map((target) => target.layout))]
109
+ ? [...new Set(targets.io.map((target) => target.layout))]
73
110
  .sort()
74
111
  .map((layout) => {
75
- const keys = targets
112
+ const keys = targets.io
76
113
  .filter((target) => target.layout === layout)
77
114
  .map((target) => `\`${target.key}\``);
78
115
  const bindings = [
@@ -85,5 +122,5 @@ export function generateHardwareTypes(
85
122
  })
86
123
  .join(" & ") || "Readonly<Record<string, never>>"
87
124
  : "Readonly<Record<string, HardwareIoBinding>>";
88
- return `${publicationTypes}export type HardwareIoBinding = ${anyBinding};\nexport type HardwareIoMapping = ${mapping};\nexport const hardware = ${JSON.stringify(catalog, null, 2)} as const;\n`;
125
+ return `${publicationTypes}export type HardwareIoBinding = ${anyBinding};\nexport type HardwareIoMapping = ${mapping};\nexport const hardware = ${JSON.stringify(portableCatalog(catalog, root), null, 2)} as const;\n`;
89
126
  }
@@ -1,9 +1,8 @@
1
- // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
2
1
  import type { IoChannel } from "./channels";
3
2
  import {
4
- byteOffset,
5
3
  directAddress,
6
4
  type ProcessImageRegion,
5
+ regionOf,
7
6
  } from "./process-image";
8
7
 
9
8
  export interface ModbusRegister {
@@ -15,6 +14,9 @@ export interface ModbusRegister {
15
14
  requests: string;
16
15
  }
17
16
 
17
+ /** The Modbus TCP server a generated device tree adds for a device's registers; `packages/build/python/hardware.py` names it the same way. */
18
+ export const modbusServerName = (device: string) => `${device}_Modbus`;
19
+
18
20
  /** Process-image bytes per register: its value and write trigger out, the client's status and answer count in. */
19
21
  const registerBytes = { Q: 4, I: 8 };
20
22
 
@@ -26,18 +28,22 @@ const registerBytes = { Q: 4, I: 8 };
26
28
  export function placeModbusRegisters(
27
29
  device: string,
28
30
  registers: Record<string, number>,
29
- place: (region: ProcessImageRegion) => string,
31
+ place: (region: ProcessImageRegion) => number,
30
32
  ): { register: ModbusRegister; channels: IoChannel[] }[] {
31
33
  const entries = Object.entries(registers);
32
34
  if (!entries.length) {
33
35
  return [];
34
36
  }
35
- const outputBase = byteOffset(
36
- place({ id: device, region: "Q", size: entries.length * registerBytes.Q }),
37
- );
38
- const inputBase = byteOffset(
39
- place({ id: device, region: "I", size: entries.length * registerBytes.I }),
40
- );
37
+ const outputBase = place({
38
+ id: device,
39
+ region: "Q",
40
+ size: entries.length * registerBytes.Q,
41
+ });
42
+ const inputBase = place({
43
+ id: device,
44
+ region: "I",
45
+ size: entries.length * registerBytes.I,
46
+ });
41
47
  return entries.map(([name, offset], index) => {
42
48
  const channel = (
43
49
  field: string,
@@ -46,25 +52,34 @@ export function placeModbusRegisters(
46
52
  bits: number,
47
53
  type: string,
48
54
  description: string,
49
- ): IoChannel => ({
50
- device,
51
- id: `modbus.${name}.${field}`,
52
- name: `${name} ${field}`,
53
- direction,
54
- offsetBits,
55
- bits,
56
- type,
57
- address: directAddress(
58
- direction === "input" ? "I" : "Q",
55
+ ): IoChannel & { address: string } => {
56
+ const address = directAddress(
57
+ regionOf(direction),
59
58
  direction === "input"
60
59
  ? inputBase + index * registerBytes.I
61
60
  : outputBase + index * registerBytes.Q,
62
61
  offsetBits,
63
62
  bits,
64
- ),
65
- unit: "",
66
- description,
67
- });
63
+ );
64
+ // Regions start on double words, so every field is directly addressable.
65
+ if (!address) {
66
+ throw new Error(
67
+ `${device}: Modbus register ${name} ${field} has no direct address.`,
68
+ );
69
+ }
70
+ return {
71
+ device,
72
+ id: `modbus.${name}.${field}`,
73
+ name: `${name} ${field}`,
74
+ direction,
75
+ offsetBits,
76
+ bits,
77
+ type,
78
+ address,
79
+ unit: "",
80
+ description,
81
+ };
82
+ };
68
83
  const value = channel("value", "output", 0, 16, "WORD", "Value to write");
69
84
  const write = channel(
70
85
  "write",
@@ -91,14 +106,13 @@ export function placeModbusRegisters(
91
106
  "Requests the device answered",
92
107
  );
93
108
  return {
94
- // Registers start on double words, so every field is directly addressable.
95
109
  register: {
96
110
  name,
97
111
  offset,
98
- value: value.address!,
99
- write: write.address!,
100
- status: status.address!,
101
- requests: requests.address!,
112
+ value: value.address,
113
+ write: write.address,
114
+ status: status.address,
115
+ requests: requests.address,
102
116
  },
103
117
  channels: [value, write, status, requests],
104
118
  };
@@ -1,4 +1,22 @@
1
- import { ioArray, ioScalar, sizePrefix } from "@tsplc/iec";
1
+ import {
2
+ elementaryTypes,
3
+ ioArray,
4
+ ioScalar,
5
+ isIntegerValued,
6
+ isWholeValue,
7
+ sizePrefix,
8
+ sizePrefixes,
9
+ type WholeValueType,
10
+ } from "@tsplc/iec";
11
+
12
+ const scalarLayout = (scalar: WholeValueType) =>
13
+ isIntegerValued(scalar) ? `INT${scalar.bits}` : scalar.name;
14
+
15
+ const scalarLayoutBits = new Map(
16
+ elementaryTypes
17
+ .filter(isWholeValue)
18
+ .map((scalar) => [scalarLayout(scalar), scalar.bits]),
19
+ );
2
20
 
3
21
  /**
4
22
  * Binding classes group integers and bit strings by width, BOOL, floats and time types
@@ -13,12 +31,13 @@ export function ioLayout(type: string): string | undefined {
13
31
  : undefined;
14
32
  }
15
33
  const scalar = ioScalar(type);
16
- if (scalar?.family === "integer" || scalar?.family === "bits") {
17
- return `INT${scalar.bits}`;
18
- }
19
- return scalar?.name;
34
+ return scalar && scalarLayout(scalar);
20
35
  }
21
36
 
37
+ /** The width each element of an `ioLayout` binds at. */
38
+ export const layoutBits = (layout: string) =>
39
+ scalarLayoutBits.get(layout.replace(/^\d+x/, ""));
40
+
22
41
  /** The size prefix a `bits`-wide scalar binds at; tsPLC binds nothing at 64-bit addresses. */
23
42
  export const addressSize = (bits: number) =>
24
43
  bits === 64 ? undefined : sizePrefix(bits);
@@ -44,15 +63,37 @@ export function directAddress(
44
63
  return `%${region}${size}${byte / (bits / 8)}`;
45
64
  }
46
65
 
47
- /** The byte offset of a `%IB` or `%QB` address. */
48
- export const byteOffset = (address: string) => Number(address.slice(3));
66
+ /** The region and bits a direct address names: `directAddress`'s inverse at base 0. */
67
+ export function addressBits(
68
+ address: string,
69
+ ): { region: "I" | "Q"; offsetBits: number; bits: number } | undefined {
70
+ const [, region, size, index, bit] =
71
+ /^%([IQ])([A-Z])(\d+)(?:\.([0-7]))?$/.exec(address) ?? [];
72
+ const bits = size === undefined ? undefined : sizePrefixes.get(size)?.bits;
73
+ if (
74
+ (region !== "I" && region !== "Q") ||
75
+ bits === undefined ||
76
+ addressSize(bits) !== size ||
77
+ (bits === 1) !== (bit !== undefined)
78
+ ) {
79
+ return undefined;
80
+ }
81
+ const offsetBits =
82
+ bits === 1 ? Number(index) * 8 + Number(bit) : Number(index) * bits;
83
+ return { region, offsetBits, bits };
84
+ }
85
+
86
+ export const regionOf = (direction: "input" | "output"): "I" | "Q" =>
87
+ direction === "input" ? "I" : "Q";
88
+
89
+ export const isOutputAddress = (address: string) => address.startsWith("%Q");
49
90
 
50
- /** A device's byte region of the %I or %Q process image, at `address` or still to be placed. */
91
+ /** A device's byte region of the %I or %Q process image, at byte `offset` or still to be placed. */
51
92
  export interface ProcessImageRegion {
52
93
  id: string;
53
94
  region: "I" | "Q";
54
95
  size: number;
55
- address?: string;
96
+ offset?: number;
56
97
  }
57
98
 
58
99
  /**
@@ -62,23 +103,15 @@ export interface ProcessImageRegion {
62
103
  export function regionPlacer(
63
104
  regions: readonly ProcessImageRegion[],
64
105
  { generatedTree }: { generatedTree: boolean },
65
- ): (region: ProcessImageRegion) => string {
66
- const taken = regions.flatMap(({ region, size, address }) =>
67
- address
68
- ? [
69
- {
70
- region,
71
- start: byteOffset(address),
72
- end: byteOffset(address) + size,
73
- },
74
- ]
75
- : [],
106
+ ): (region: ProcessImageRegion) => number {
107
+ const taken = regions.flatMap(({ region, size, offset }) =>
108
+ offset === undefined ? [] : [{ region, start: offset, end: offset + size }],
76
109
  );
77
110
  const cursors = { I: 0, Q: 0 };
78
111
  const aligned = (offset: number) => Math.ceil(offset / 4) * 4;
79
- return ({ id, region, size, address }) => {
80
- if (address) {
81
- return address;
112
+ return ({ id, region, size, offset }) => {
113
+ if (offset !== undefined) {
114
+ return offset;
82
115
  }
83
116
  if (!generatedTree) {
84
117
  throw new Error(
@@ -97,6 +130,6 @@ export function regionPlacer(
97
130
  const start = clear(aligned(cursors[region]));
98
131
  taken.push({ region, start, end: start + size });
99
132
  cursors[region] = start + size;
100
- return `%${region}B${start}`;
133
+ return start;
101
134
  };
102
135
  }