@tsplc/typegen 0.2.16 → 0.2.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,408 @@
1
+ export interface EdsParameter {
2
+ id: string;
3
+ name: string;
4
+ type: string;
5
+ size: number;
6
+ unit: string;
7
+ description: string;
8
+ minimum?: number;
9
+ maximum?: number;
10
+ default?: number;
11
+ }
12
+ export interface EdsMember {
13
+ parameter?: string;
14
+ name: string;
15
+ offsetBits: number;
16
+ bits: number;
17
+ type: string;
18
+ unit: string;
19
+ description: string;
20
+ }
21
+ export interface EdsAssembly {
22
+ id: string;
23
+ instance?: number;
24
+ name: string;
25
+ size: number;
26
+ members: EdsMember[];
27
+ }
28
+ export interface EdsConnection {
29
+ id: string;
30
+ name: string;
31
+ /** Exclusive owner: the scanner both produces and controls the connection's data. */
32
+ owner: boolean;
33
+ outputAssembly?: number;
34
+ inputAssembly?: number;
35
+ path: string;
36
+ inputSize?: EdsSize;
37
+ outputSize?: EdsSize;
38
+ }
39
+ export interface EdsSize {
40
+ value: number;
41
+ parameter?: string;
42
+ minimum?: number;
43
+ maximum?: number;
44
+ }
45
+ export interface HardwareDescriptor {
46
+ file: string;
47
+ name: string;
48
+ vendor: string;
49
+ productCode: string;
50
+ parameters: EdsParameter[];
51
+ assemblies: EdsAssembly[];
52
+ connections: EdsConnection[];
53
+ }
54
+
55
+ const cipTypes: Record<number, string> = {
56
+ 0xc1: "BOOL",
57
+ 0xc2: "SINT",
58
+ 0xc3: "INT",
59
+ 0xc4: "DINT",
60
+ 0xc5: "LINT",
61
+ 0xc6: "USINT",
62
+ 0xc7: "UINT",
63
+ 0xc8: "UDINT",
64
+ 0xc9: "ULINT",
65
+ 0xca: "REAL",
66
+ 0xcb: "LREAL",
67
+ 0xd1: "BYTE",
68
+ 0xd2: "WORD",
69
+ 0xd3: "DWORD",
70
+ 0xd4: "LWORD",
71
+ };
72
+
73
+ /** A record's fields, and where the record (key through semicolon) sits in the EDS text. */
74
+ export interface EdsRecord {
75
+ fields: string[];
76
+ start: number;
77
+ end: number;
78
+ }
79
+
80
+ /** The text without its $ comments, and the offset in `text` of each character kept. */
81
+ function stripComments(text: string): { clean: string; offsets: number[] } {
82
+ let clean = "";
83
+ const offsets: number[] = [];
84
+ let quote = false;
85
+ let comment = false;
86
+ for (let i = 0; i < text.length; i++) {
87
+ const c = text.charAt(i);
88
+ if (comment && c !== "\n") {
89
+ continue;
90
+ }
91
+ comment = false;
92
+ if (c === '"' && quote && text.charAt(i + 1) === '"') {
93
+ clean += '""';
94
+ offsets.push(i, i + 1);
95
+ i++;
96
+ continue;
97
+ }
98
+ if (c === '"') {
99
+ quote = !quote;
100
+ }
101
+ if (c === "$" && !quote) {
102
+ comment = true;
103
+ continue;
104
+ }
105
+ clean += c;
106
+ offsets.push(i);
107
+ }
108
+ if (quote) {
109
+ throw new Error("Unterminated EDS string.");
110
+ }
111
+ return { clean, offsets };
112
+ }
113
+
114
+ /** Comma-separated fields; inside quotes a comma is text and `""` is a quote. */
115
+ function recordFields(body: string): string[] {
116
+ const fields: string[] = [];
117
+ let field = "";
118
+ let quoted = false;
119
+ for (let i = 0; i < body.length; i++) {
120
+ const c = body.charAt(i);
121
+ if (c === '"') {
122
+ if (quoted && body.charAt(i + 1) === '"') {
123
+ field += '"';
124
+ i++;
125
+ } else {
126
+ quoted = !quoted;
127
+ }
128
+ } else if (c === "," && !quoted) {
129
+ fields.push(field.trim());
130
+ field = "";
131
+ } else {
132
+ field += c;
133
+ }
134
+ }
135
+ fields.push(field.trim());
136
+ return fields;
137
+ }
138
+
139
+ /**
140
+ * EDS records are comma separated, terminated by semicolons, with $ comments.
141
+ * Sections and their records keep file order.
142
+ */
143
+ export function edsSections(text: string): Map<string, Map<string, EdsRecord>> {
144
+ const { clean, offsets } = stripComments(text);
145
+ const sections = new Map<string, Map<string, EdsRecord>>();
146
+ let section: Map<string, EdsRecord> | undefined;
147
+ let end = 0;
148
+ for (const match of clean.matchAll(
149
+ /\[([^\]\r\n]+)\]|([A-Za-z_][\w]*)\s*=\s*((?:"(?:[^"]|"")*"|[^;])*)\s*;/g,
150
+ )) {
151
+ if (clean.slice(end, match.index).trim()) {
152
+ throw new Error("Malformed EDS record or section.");
153
+ }
154
+ end = match.index + match[0].length;
155
+ const [, header, key, body] = match;
156
+ if (header) {
157
+ const name = header.trim();
158
+ if (sections.has(name)) {
159
+ throw new Error(`Duplicate EDS section ${name}.`);
160
+ }
161
+ section = new Map();
162
+ sections.set(name, section);
163
+ continue;
164
+ }
165
+ if (!section) {
166
+ throw new Error("EDS record outside a section.");
167
+ }
168
+ // The pattern's record branch always captures a key and a (possibly empty) body.
169
+ if (section.has(key!)) {
170
+ throw new Error(`Duplicate EDS record ${key}.`);
171
+ }
172
+ section.set(key!, {
173
+ fields: recordFields(body!),
174
+ start: offsets[match.index]!,
175
+ end: offsets[end - 1]! + 1,
176
+ });
177
+ }
178
+ if (clean.slice(end).trim()) {
179
+ throw new Error("Unterminated EDS record.");
180
+ }
181
+ return sections;
182
+ }
183
+
184
+ /** Each section's records, keyed by record name, as field lists. */
185
+ export function readEdsRecords(
186
+ text: string,
187
+ ): Record<string, Record<string, string[]>> {
188
+ return Object.fromEntries(
189
+ [...edsSections(text)].map(([name, records]) => [
190
+ name,
191
+ Object.fromEntries(
192
+ [...records].map(([key, record]) => [key, record.fields]),
193
+ ),
194
+ ]),
195
+ );
196
+ }
197
+
198
+ function integer(
199
+ value: string | undefined,
200
+ label: string,
201
+ { minimum }: { minimum: 0 | 1 },
202
+ ): number {
203
+ if (!value || !/^(?:\d+|0x[\da-f]+)$/i.test(value)) {
204
+ throw new Error(`Invalid EDS ${label}: ${value ?? "missing"}.`);
205
+ }
206
+ const n = Number(value);
207
+ if (!Number.isSafeInteger(n) || n < minimum || n > 16_777_216) {
208
+ throw new Error(`Unsupported EDS ${label}: ${value}.`);
209
+ }
210
+ return n;
211
+ }
212
+
213
+ /** Logical segments in path order: the segment's type bits, without its width, and its value. */
214
+ function logicalSegments(bytes: number[]): { type: number; value: number }[] {
215
+ const [segment, ...rest] = bytes;
216
+ if (segment === undefined) {
217
+ return [];
218
+ }
219
+ const width = segment & 3;
220
+ if ((segment & 0xe0) !== 0x20 || width > 2) {
221
+ throw new Error(
222
+ `Unsupported EDS logical path segment ${segment.toString(16)}.`,
223
+ );
224
+ }
225
+ // A 16- or 32-bit value follows a pad byte.
226
+ if (width && rest[0] !== 0) {
227
+ throw new Error("Invalid EDS logical path padding.");
228
+ }
229
+ const data = width ? rest.slice(1) : rest;
230
+ const length = 1 << width;
231
+ if (length > data.length) {
232
+ throw new Error("Truncated EDS logical path.");
233
+ }
234
+ const value = data
235
+ .slice(0, length)
236
+ .reduce((sum, byte, index) => sum + byte * 2 ** (index * 8), 0);
237
+ return [
238
+ { type: segment & 0xfc, value },
239
+ ...logicalSegments(data.slice(length)),
240
+ ];
241
+ }
242
+
243
+ // EPATH logical segments encode class, instance, attribute and connection-point
244
+ // IDs. Record names such as Assem1 are format references, not runtime instances.
245
+ function logicalPath(path: string): { instance?: number; points: number[] } {
246
+ const bytes = path.trim()
247
+ ? path
248
+ .trim()
249
+ .split(/\s+/)
250
+ .map((token) => {
251
+ if (!/^[0-9a-f]{2}$/i.test(token)) {
252
+ throw new Error(`Unsupported EDS path token ${token}.`);
253
+ }
254
+ return parseInt(token, 16);
255
+ })
256
+ : [];
257
+ const segments = logicalSegments(bytes);
258
+ return {
259
+ instance: segments.filter(({ type }) => type === 0x24).at(-1)?.value,
260
+ points: segments
261
+ .filter(({ type }) => type === 0x2c)
262
+ .map(({ value }) => value),
263
+ };
264
+ }
265
+ const optionalNumber = (value: string | undefined) =>
266
+ value?.trim() && Number.isFinite(Number(value)) ? Number(value) : undefined;
267
+
268
+ export function parseEds(
269
+ text: string,
270
+ file = "device.eds",
271
+ ): HardwareDescriptor {
272
+ const records = readEdsRecords(text);
273
+ const device = records.Device;
274
+ if (!device?.ProdName?.[0]) {
275
+ throw new Error(`${file}: missing EDS Device.ProdName.`);
276
+ }
277
+ const parameters = Object.entries(records.Params ?? {})
278
+ .filter(([id]) => /^Param\d+$/.test(id))
279
+ .map(([id, fields]): EdsParameter => ({
280
+ id,
281
+ name: fields[6] || id,
282
+ type: cipTypes[Number(fields[4])] ?? "opaque",
283
+ size: integer(fields[5], `${id} data size`, { minimum: 1 }),
284
+ unit: fields[7] ?? "",
285
+ description: fields[8] ?? "",
286
+ minimum: optionalNumber(fields[9]),
287
+ maximum: optionalNumber(fields[10]),
288
+ default: optionalNumber(fields[11]),
289
+ }));
290
+ const params = new Map(
291
+ parameters.map((parameter) => [parameter.id, parameter]),
292
+ );
293
+ const instances = new Map<string, number>();
294
+ const size = (value: string | undefined): EdsSize | undefined => {
295
+ if (!value) {
296
+ return;
297
+ }
298
+ if (!value.startsWith("Param")) {
299
+ return { value: integer(value, "connection size", { minimum: 0 }) };
300
+ }
301
+ const parameter = params.get(value);
302
+ if (!parameter || parameter.default === undefined) {
303
+ throw new Error(
304
+ `${file}: connection size ${value} has no numeric default.`,
305
+ );
306
+ }
307
+ return {
308
+ value: parameter.default,
309
+ parameter: value,
310
+ minimum: parameter.minimum,
311
+ maximum: parameter.maximum,
312
+ };
313
+ };
314
+ const connections = Object.entries(records["Connection Manager"] ?? {})
315
+ .filter(([id]) => /^Connection\d+$/.test(id))
316
+ .map(([id, fields]): EdsConnection => {
317
+ const path = fields[14] ?? "";
318
+ const points = logicalPath(path).points;
319
+ const assembly = (
320
+ reference: string | undefined,
321
+ point: number | undefined,
322
+ ): number | undefined => {
323
+ if (!reference) {
324
+ return;
325
+ }
326
+ const record = records.Assembly?.[reference];
327
+ if (!/^Assem\d+$/.test(reference) || !record) {
328
+ throw new Error(`${file}: unknown connection assembly ${reference}.`);
329
+ }
330
+ const instance = point ?? logicalPath(record[1] ?? "").instance;
331
+ if (instance === undefined) {
332
+ throw new Error(`${file}: no runtime instance for ${reference}.`);
333
+ }
334
+ const previous = instances.get(reference);
335
+ if (previous !== undefined && previous !== instance) {
336
+ throw new Error(
337
+ `${file}: ${reference} has conflicting runtime instances.`,
338
+ );
339
+ }
340
+ instances.set(reference, instance);
341
+ return instance;
342
+ };
343
+ return {
344
+ id,
345
+ name: fields[12] || id,
346
+ // Trigger and transport bits 24-27 give the connection type; 4 is exclusive owner.
347
+ owner:
348
+ /^0x[\da-f]{8}$/i.test(fields[0] ?? "") &&
349
+ ((Number(fields[0]) >>> 24) & 0xf) === 4,
350
+ path,
351
+ outputAssembly: assembly(fields[4], points.at(-2)),
352
+ inputAssembly: assembly(fields[7], points.at(-1)),
353
+ outputSize: size(fields[3]),
354
+ inputSize: size(fields[6]),
355
+ };
356
+ });
357
+ const assemblies = Object.entries(records.Assembly ?? {})
358
+ .filter(([id]) => /^Assem\d+$/.test(id))
359
+ .map(([id, fields]): EdsAssembly => {
360
+ const members: EdsMember[] = [];
361
+ let offsetBits = 0;
362
+ for (let index = 6; index < fields.length; index += 2) {
363
+ if (!fields[index] && !fields[index + 1]) {
364
+ continue;
365
+ }
366
+ const bits = integer(fields[index], `${id} member bits`, {
367
+ minimum: 1,
368
+ });
369
+ const reference = fields[index + 1];
370
+ const parameter = reference ? params.get(reference) : undefined;
371
+ if (reference && !parameter) {
372
+ throw new Error(
373
+ `${file}: ${id} references unknown parameter ${reference}.`,
374
+ );
375
+ }
376
+ members.push({
377
+ ...(reference ? { parameter: reference } : {}),
378
+ name: parameter?.name ?? "Padding",
379
+ offsetBits,
380
+ bits,
381
+ type: parameter?.type ?? "padding",
382
+ unit: parameter?.unit ?? "",
383
+ description: parameter?.description ?? "",
384
+ });
385
+ offsetBits += bits;
386
+ }
387
+ const size = fields[2]
388
+ ? integer(fields[2], `${id} size`, { minimum: 0 })
389
+ : Math.ceil(offsetBits / 8);
390
+ if (offsetBits > size * 8) {
391
+ throw new Error(
392
+ `${file}: ${id} members exceed its ${size} byte payload.`,
393
+ );
394
+ }
395
+ const instance =
396
+ logicalPath(fields[1] ?? "").instance ?? instances.get(id);
397
+ return { id, instance, name: fields[0] || id, size, members };
398
+ });
399
+ return {
400
+ file,
401
+ name: device.ProdName[0],
402
+ vendor: device.VendName?.[0] ?? "",
403
+ productCode: device.ProdCode?.[0] ?? "",
404
+ parameters,
405
+ assemblies,
406
+ connections,
407
+ };
408
+ }
@@ -0,0 +1,88 @@
1
+ import type { HardwareCatalog } from "../hardware.ts";
2
+ import { ioScalarBits } from "@tsplc/iec";
3
+ import { addressSize, ioLayout } from "./process-image.ts";
4
+
5
+ /** A bindable `io` key with its layout; array indexes appear as the literal `${number}`. */
6
+ export interface IoTarget {
7
+ key: string;
8
+ layout: string;
9
+ }
10
+
11
+ export interface ProjectTargets {
12
+ io: readonly IoTarget[];
13
+ publication: readonly string[];
14
+ }
15
+
16
+ // Integer layouts are INTn and the others are named for their type.
17
+ const directBinding = (layout: string): string | undefined => {
18
+ const scalar = layout.replace(/^\d+x/, "");
19
+ const integer = /^INT(\d+)$/.exec(scalar);
20
+ const bits = integer ? Number(integer[1]) : ioScalarBits(scalar);
21
+ const size = bits === undefined ? undefined : addressSize(bits);
22
+ if (!size) {
23
+ return undefined;
24
+ }
25
+ return size === "X"
26
+ ? '{ address: `%${"I" | "Q"}X${number}.${0 | 1 | 2 | 3 | 4 | 5 | 6 | 7}`; type?: string }'
27
+ : `{ address: \`%\${"I" | "Q"}${size}\${number}\`; type?: string }`;
28
+ };
29
+
30
+ /**
31
+ * With `targets` from a compiled TS project, `HardwareIoMapping` accepts only those
32
+ * keys, each with channels or direct addresses of a compatible layout. Without them
33
+ * (raw ST projects) any key is accepted and the build checks it.
34
+ */
35
+ export function generateHardwareTypes(
36
+ catalog: HardwareCatalog,
37
+ targets?: readonly IoTarget[],
38
+ publication?: readonly string[],
39
+ ioTypes = true,
40
+ ): string {
41
+ const selectors =
42
+ publication?.map((selector) => JSON.stringify(selector)).join(" | ") ??
43
+ "string";
44
+ 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`;
45
+ if (!ioTypes) {
46
+ return publicationTypes;
47
+ }
48
+ // Spelled per member: intersecting the whole union makes TypeScript distribute it over every channel.
49
+ const channel = (device: string, id: string, options: string) =>
50
+ `{ device: ${JSON.stringify(device)}; channel: ${JSON.stringify(id)}${options} }`;
51
+ const channels = catalog.devices.flatMap((device) =>
52
+ device.channels
53
+ .filter((item) => item.address)
54
+ .map((item) => ({
55
+ binding: channel(
56
+ device.id,
57
+ item.id,
58
+ item.direction === "input" && item.type === "BOOL"
59
+ ? "; inverted?: boolean; shared?: boolean"
60
+ : "",
61
+ ),
62
+ layout: ioLayout(item.type),
63
+ })),
64
+ );
65
+ const direct =
66
+ '{ address: `%${"I" | "Q"}${"B" | "W" | "D"}${number}` | `%${"I" | "Q"}X${number}.${0 | 1 | 2 | 3 | 4 | 5 | 6 | 7}`; type?: string }';
67
+ const anyBinding = [...channels.map((item) => item.binding), direct].join(
68
+ "\n | ",
69
+ );
70
+ const mapping = targets
71
+ ? [...new Set(targets.map((target) => target.layout))]
72
+ .sort()
73
+ .map((layout) => {
74
+ const keys = targets
75
+ .filter((target) => target.layout === layout)
76
+ .map((target) => `\`${target.key}\``);
77
+ const bindings = [
78
+ ...channels
79
+ .filter((item) => item.layout === layout)
80
+ .map((item) => item.binding),
81
+ directBinding(layout),
82
+ ].filter(Boolean);
83
+ return `{\n readonly [K in ${keys.join(" | ")}]?: ${bindings.join(" | ") || "never"};\n}`;
84
+ })
85
+ .join(" & ") || "Readonly<Record<string, never>>"
86
+ : "Readonly<Record<string, HardwareIoBinding>>";
87
+ return `${publicationTypes}export type HardwareIoBinding = ${anyBinding};\nexport type HardwareIoMapping = ${mapping};\nexport const hardware = ${JSON.stringify(catalog, null, 2)} as const;\n`;
88
+ }
@@ -0,0 +1,105 @@
1
+ import type { IoChannel } from "./channels.ts";
2
+ import {
3
+ type ProcessImageRegion,
4
+ byteOffset,
5
+ directAddress,
6
+ } from "./process-image.ts";
7
+
8
+ export interface ModbusRegister {
9
+ name: string;
10
+ offset: number;
11
+ value: string;
12
+ write: string;
13
+ status: string;
14
+ requests: string;
15
+ }
16
+
17
+ /** Process-image bytes per register: its value and write trigger out, the client's status and answer count in. */
18
+ const registerBytes = { Q: 4, I: 8 };
19
+
20
+ /**
21
+ * Places a device's registers, one output and one input region for all of them, and
22
+ * returns each register's addresses and channels: its value and write trigger, then
23
+ * the Modbus client's status and answer count.
24
+ */
25
+ export function placeModbusRegisters(
26
+ device: string,
27
+ registers: Record<string, number>,
28
+ place: (region: ProcessImageRegion) => string,
29
+ ): { register: ModbusRegister; channels: IoChannel[] }[] {
30
+ const entries = Object.entries(registers);
31
+ if (!entries.length) {
32
+ return [];
33
+ }
34
+ const outputBase = byteOffset(
35
+ place({ id: device, region: "Q", size: entries.length * registerBytes.Q }),
36
+ );
37
+ const inputBase = byteOffset(
38
+ place({ id: device, region: "I", size: entries.length * registerBytes.I }),
39
+ );
40
+ return entries.map(([name, offset], index) => {
41
+ const channel = (
42
+ field: string,
43
+ direction: "input" | "output",
44
+ offsetBits: number,
45
+ bits: number,
46
+ type: string,
47
+ description: string,
48
+ ): IoChannel => ({
49
+ device,
50
+ id: `modbus.${name}.${field}`,
51
+ name: `${name} ${field}`,
52
+ direction,
53
+ offsetBits,
54
+ bits,
55
+ type,
56
+ address: directAddress(
57
+ direction === "input" ? "I" : "Q",
58
+ direction === "input"
59
+ ? inputBase + index * registerBytes.I
60
+ : outputBase + index * registerBytes.Q,
61
+ offsetBits,
62
+ bits,
63
+ ),
64
+ unit: "",
65
+ description,
66
+ });
67
+ const value = channel("value", "output", 0, 16, "WORD", "Value to write");
68
+ const write = channel(
69
+ "write",
70
+ "output",
71
+ 16,
72
+ 1,
73
+ "BOOL",
74
+ "Writes the value when it rises",
75
+ );
76
+ const status = channel(
77
+ "status",
78
+ "input",
79
+ 0,
80
+ 8,
81
+ "BYTE",
82
+ "The last answer: 0 accepted, otherwise the exception code",
83
+ );
84
+ const requests = channel(
85
+ "requests",
86
+ "input",
87
+ 32,
88
+ 32,
89
+ "UDINT",
90
+ "Requests the device answered",
91
+ );
92
+ return {
93
+ // Registers start on double words, so every field is directly addressable.
94
+ register: {
95
+ name,
96
+ offset,
97
+ value: value.address!,
98
+ write: write.address!,
99
+ status: status.address!,
100
+ requests: requests.address!,
101
+ },
102
+ channels: [value, write, status, requests],
103
+ };
104
+ });
105
+ }
@@ -0,0 +1,102 @@
1
+ import { ioArray, ioScalar, sizePrefix } from "@tsplc/iec";
2
+
3
+ /**
4
+ * Binding classes group integers and bit strings by width, BOOL, floats and time types
5
+ * by domain, and non-BOOL arrays by element class and length.
6
+ */
7
+ export function ioLayout(type: string): string | undefined {
8
+ const array = ioArray(type.trim());
9
+ if (array) {
10
+ const element = ioLayout(array.element);
11
+ return element && element !== "BOOL"
12
+ ? `${array.length}x${element}`
13
+ : undefined;
14
+ }
15
+ const scalar = ioScalar(type);
16
+ if (scalar?.family === "integer" || scalar?.family === "bits") {
17
+ return `INT${scalar.bits}`;
18
+ }
19
+ return scalar?.name;
20
+ }
21
+
22
+ /** The size prefix a `bits`-wide scalar binds at; tsPLC binds nothing at 64-bit addresses. */
23
+ export const addressSize = (bits: number) =>
24
+ bits === 64 ? undefined : sizePrefix(bits);
25
+
26
+ /** Bits, bytes, words and dwords are directly addressable when aligned to their own width. */
27
+ export function directAddress(
28
+ region: "I" | "Q",
29
+ base: number,
30
+ offsetBits: number,
31
+ bits: number,
32
+ ): string | undefined {
33
+ const size = addressSize(bits);
34
+ if (!size) {
35
+ return undefined;
36
+ }
37
+ const byte = base + Math.floor(offsetBits / 8);
38
+ if (bits === 1) {
39
+ return `%${region}X${byte}.${offsetBits % 8}`;
40
+ }
41
+ if ((base * 8 + offsetBits) % bits) {
42
+ return undefined;
43
+ }
44
+ return `%${region}${size}${byte / (bits / 8)}`;
45
+ }
46
+
47
+ /** The byte offset of a `%IB` or `%QB` address. */
48
+ export const byteOffset = (address: string) => Number(address.slice(3));
49
+
50
+ /** A device's byte region of the %I or %Q process image, at `address` or still to be placed. */
51
+ export interface ProcessImageRegion {
52
+ id: string;
53
+ region: "I" | "Q";
54
+ size: number;
55
+ address?: string;
56
+ }
57
+
58
+ /**
59
+ * Bases for regions without an address: each region continues after the
60
+ * previous device, aligned to a double word and clear of explicit placements.
61
+ */
62
+ export function regionPlacer(
63
+ regions: readonly ProcessImageRegion[],
64
+ { 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
+ : [],
76
+ );
77
+ const cursors = { I: 0, Q: 0 };
78
+ const aligned = (offset: number) => Math.ceil(offset / 4) * 4;
79
+ return ({ id, region, size, address }) => {
80
+ if (address) {
81
+ return address;
82
+ }
83
+ if (!generatedTree) {
84
+ throw new Error(
85
+ `${id}: set the %${region}B address the template assigns to this assembly, or let codesys.deviceTree place it.`,
86
+ );
87
+ }
88
+ const clear = (start: number): number => {
89
+ const overlap = taken.find(
90
+ (item) =>
91
+ item.region === region &&
92
+ item.start < start + size &&
93
+ start < item.end,
94
+ );
95
+ return overlap ? clear(aligned(overlap.end)) : start;
96
+ };
97
+ const start = clear(aligned(cursors[region]));
98
+ taken.push({ region, start, end: start + size });
99
+ cursors[region] = start + size;
100
+ return `%${region}B${start}`;
101
+ };
102
+ }