@tsplc/typegen 0.2.17 → 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.
package/dist/codegen.js CHANGED
@@ -3,62 +3,65 @@ import { readdir, readFile } from "node:fs/promises";
3
3
  import { basename, join } from "node:path";
4
4
 
5
5
  // packages/typegen/src/codegen/constants.ts
6
- var iecTypeBits = {
7
- BOOL: 1,
8
- SINT: 8,
9
- USINT: 8,
10
- BYTE: 8,
11
- INT: 16,
12
- UINT: 16,
13
- WORD: 16,
14
- DINT: 32,
15
- UDINT: 32,
16
- DWORD: 32,
17
- REAL: 32,
18
- LINT: 64,
19
- ULINT: 64,
20
- LWORD: 64,
21
- LREAL: 64
6
+ import {
7
+ elementaryType,
8
+ elementaryTypes,
9
+ integerRange,
10
+ isIntegerValued
11
+ } from "@tsplc/iec";
12
+ var isNumberInteger = (name) => {
13
+ const type = elementaryType(name);
14
+ return isIntegerValued(type) && type.bits <= 32;
22
15
  };
16
+ var integerRanges = new Map(elementaryTypes.filter(isIntegerValued).map((type) => [type.name, integerRange(type)]));
17
+ var integerToken = new RegExp(String.raw`(?:${[...integerRanges.keys()].join("|")})\s*#\s*[+-]?(?:(?:2|8|16)#[\da-fA-F_]+|\d[\d_]*)|(?:2|8|16)#[\da-fA-F_]+|\d[\d_]*|[A-Za-z_]\w*(?:\s*\.\s*[A-Za-z_]\w*)?|[()+\-*/]`, "g");
23
18
  function integerExpression(text, lookup) {
24
19
  const compact = text.replace(/\s+/g, "");
25
- const tokens = (text.match(/(?:U?S?INT|U?DINT|U?LINT|BYTE|WORD|DWORD|LWORD)\s*#\s*[+-]?(?:(?:2|8|16)#[\da-fA-F_]+|\d[\d_]*)|(?:2|8|16)#[\da-fA-F_]+|\d[\d_]*|[A-Za-z_]\w*(?:\s*\.\s*[A-Za-z_]\w*)?|[()+\-*/]/g) ?? []).map((token) => token.replace(/\s+/g, ""));
26
- if (tokens.join("") !== compact || !tokens.length)
20
+ const tokens = (text.match(integerToken) ?? []).map((token) => token.replace(/\s+/g, ""));
21
+ if (tokens.join("") !== compact || !tokens.length) {
27
22
  throw new Error(`unsupported integer expression: ${text}`);
23
+ }
24
+ const safe = (value) => {
25
+ if (!Number.isSafeInteger(value)) {
26
+ throw new Error(`integer outside JavaScript's safe range: ${text}`);
27
+ }
28
+ return value;
29
+ };
28
30
  let position = 0;
29
31
  function atom() {
30
32
  const token = tokens[position++];
31
- if (token === "+")
33
+ if (token === "+") {
32
34
  return atom();
33
- if (token === "-")
35
+ }
36
+ if (token === "-") {
34
37
  return -atom();
38
+ }
35
39
  if (token === "(") {
36
40
  const value = sum();
37
- if (tokens[position++] !== ")")
41
+ if (tokens[position++] !== ")") {
38
42
  throw new Error(`unclosed integer expression: ${text}`);
43
+ }
39
44
  return value;
40
45
  }
41
- const typed = token && /^(U?S?INT|U?DINT|U?LINT|BYTE|WORD|DWORD|LWORD)#(.*)$/i.exec(token);
46
+ const typed = token && [...integerRanges].find(([name]) => token.toUpperCase().startsWith(`${name}#`));
42
47
  if (typed) {
43
- const value = integerExpression(typed[2], lookup);
44
- const name = typed[1].toUpperCase(), bits = iecTypeBits[name];
45
- const signed = ["SINT", "INT", "DINT", "LINT"].includes(name);
46
- const limit = 1n << BigInt(bits - (signed ? 1 : 0));
47
- if (BigInt(value) < (signed ? -limit : 0n) || BigInt(value) >= limit)
48
+ const [name, [minimum, maximum]] = typed;
49
+ const value = integerExpression(token.slice(name.length + 1), lookup);
50
+ if (BigInt(value) < minimum || BigInt(value) > maximum) {
48
51
  throw new Error(`typed integer outside ${name}: ${token}`);
52
+ }
49
53
  return value;
50
54
  }
51
55
  if (token && /^\d/.test(token)) {
52
56
  const [base, digits] = token.replace(/_/g, "").split("#");
53
- if (digits !== undefined && ![...digits].every((digit) => parseInt(digit, 16) < Number(base)))
57
+ if (digits !== undefined && ![...digits].every((digit) => parseInt(digit, 16) < Number(base))) {
54
58
  throw new Error(`invalid base-${base} literal: ${token}`);
55
- const value = digits === undefined ? Number(base) : parseInt(digits, Number(base));
56
- if (!Number.isSafeInteger(value))
57
- throw new Error(`integer outside JavaScript's safe range: ${text}`);
58
- return value;
59
+ }
60
+ return safe(digits === undefined ? Number(base) : parseInt(digits, Number(base)));
59
61
  }
60
- if (token && /^[A-Za-z_]/.test(token))
62
+ if (token && /^[A-Za-z_]/.test(token)) {
61
63
  return lookup(token);
64
+ }
62
65
  throw new Error(`invalid integer expression: ${text}`);
63
66
  }
64
67
  function product() {
@@ -66,11 +69,10 @@ function integerExpression(text, lookup) {
66
69
  while (tokens[position] === "*" || tokens[position] === "/") {
67
70
  const operator = tokens[position++];
68
71
  const right = atom();
69
- if (operator === "/" && right === 0)
72
+ if (operator === "/" && right === 0) {
70
73
  throw new Error(`division by zero: ${text}`);
71
- value = operator === "*" ? value * right : Math.trunc(value / right);
72
- if (!Number.isSafeInteger(value))
73
- throw new Error(`integer outside JavaScript's safe range: ${text}`);
74
+ }
75
+ value = safe(operator === "*" ? value * right : Math.trunc(value / right));
74
76
  }
75
77
  return value;
76
78
  }
@@ -79,19 +81,63 @@ function integerExpression(text, lookup) {
79
81
  while (tokens[position] === "+" || tokens[position] === "-") {
80
82
  const operator = tokens[position++];
81
83
  const right = product();
82
- value = operator === "+" ? value + right : value - right;
83
- if (!Number.isSafeInteger(value))
84
- throw new Error(`integer outside JavaScript's safe range: ${text}`);
84
+ value = safe(operator === "+" ? value + right : value - right);
85
85
  }
86
86
  return value;
87
87
  }
88
88
  const value = sum();
89
- if (position !== tokens.length || !Number.isSafeInteger(value))
89
+ if (position !== tokens.length || !Number.isSafeInteger(value)) {
90
90
  throw new Error(`invalid or unsafe integer expression: ${text}`);
91
+ }
91
92
  return value;
92
93
  }
94
+ function constantResolver(lists) {
95
+ const values = new Map;
96
+ const resolving = new Set;
97
+ const definitions = lists.flatMap((list) => list.members.map((member) => ({
98
+ list,
99
+ member,
100
+ key: `${list.name}.${member.name}`.toUpperCase()
101
+ })));
102
+ const constant = (name, scope) => {
103
+ const key = name.toUpperCase();
104
+ const scoped = scope === null ? undefined : definitions.find((item) => item.key === `${scope}.${name}`.toUpperCase());
105
+ const [definition, ...others] = scoped ? [scoped] : definitions.filter((item) => item.key === key || !name.includes(".") && item.member.name.toUpperCase() === key);
106
+ if (!definition || others.length) {
107
+ throw new Error(`unknown or ambiguous constant ${name}`);
108
+ }
109
+ const cached = values.get(definition.key);
110
+ if (cached !== undefined) {
111
+ return cached;
112
+ }
113
+ if (resolving.has(definition.key)) {
114
+ throw new Error(`cyclic constant ${name}`);
115
+ }
116
+ const { member, list } = definition;
117
+ if (member.initial === undefined || member.type.kind !== "named" || !isNumberInteger(member.type.name.toUpperCase())) {
118
+ throw new Error(`${list.source}: constant ${member.name} must have an integer type and initializer`);
119
+ }
120
+ resolving.add(definition.key);
121
+ const value = integerExpression(member.initial, (reference) => constant(reference, list.name));
122
+ resolving.delete(definition.key);
123
+ values.set(definition.key, value);
124
+ return value;
125
+ };
126
+ return constant;
127
+ }
128
+
129
+ // packages/typegen/src/codegen/generate.ts
130
+ import { elementaryTypesByName } from "@tsplc/iec";
131
+ import { identifierPattern as identifierPattern2 } from "@tsplc/iec/st";
93
132
 
94
133
  // packages/typegen/src/codegen/parser.ts
134
+ import {
135
+ blockCommentEnd,
136
+ directAddressEnd,
137
+ identifierPattern,
138
+ lineCommentEnd,
139
+ qualifiers
140
+ } from "@tsplc/iec/st";
95
141
  function tokenize(source) {
96
142
  const tokens = [];
97
143
  let offset = 0;
@@ -103,34 +149,26 @@ function tokenize(source) {
103
149
  continue;
104
150
  }
105
151
  if (rest.startsWith("(*")) {
106
- const start = offset;
107
- let depth = 1;
108
- offset += 2;
109
- while (depth && offset < source.text.length) {
110
- const pair = source.text.slice(offset, offset + 2);
111
- if (pair === "(*" || pair === "*)") {
112
- depth += pair === "(*" ? 1 : -1;
113
- offset += 2;
114
- } else
115
- offset++;
116
- }
117
- if (depth)
152
+ const end = blockCommentEnd(source.text, offset);
153
+ if (end === null) {
118
154
  throw new Error(`${source.name}: unterminated comment`);
155
+ }
119
156
  tokens.push({
120
- text: source.text.slice(start + 2, offset - 2).trim(),
121
- offset: start,
157
+ text: source.text.slice(offset + 2, end - 2).trim(),
158
+ offset,
122
159
  kind: "comment"
123
160
  });
161
+ offset = end;
124
162
  continue;
125
163
  }
126
- const comment = /^\/\/[^\r\n]*/.exec(rest);
127
- if (comment) {
164
+ if (rest.startsWith("//")) {
165
+ const end = lineCommentEnd(source.text, offset);
128
166
  tokens.push({
129
- text: comment[0].slice(2).trim(),
167
+ text: source.text.slice(offset + 2, end).trim(),
130
168
  offset,
131
169
  kind: "comment"
132
170
  });
133
- offset += comment[0].length;
171
+ offset = end;
134
172
  continue;
135
173
  }
136
174
  const attribute = /^\{(?:[^}'"]|'(?:\$[\s\S]|''|[^'])*'|"(?:\$[\s\S]|""|[^"])*")*\}/.exec(rest);
@@ -139,10 +177,21 @@ function tokenize(source) {
139
177
  offset += attribute[0].length;
140
178
  continue;
141
179
  }
142
- const code = /^(?:%[IQM](?:[XBWDL])?(?:\d+(?:\.\d+)*|\*)|'(?:\$[\s\S]|''|[^'])*'|"(?:\$[\s\S]|""|[^"])*"|\d[\d_]*#[\da-fA-F_]+|\d[\d_]*(?:\.(?!\.)[\d_]+)?(?:[eE][+-]?\d+)?|[A-Za-z_]\w*|:=|\.\.|[[\]():;,.+\-*/#])/i.exec(rest);
143
- if (!code)
180
+ const addressEnd = directAddressEnd(source.text, offset);
181
+ if (addressEnd !== null) {
182
+ tokens.push({
183
+ text: source.text.slice(offset, addressEnd),
184
+ offset,
185
+ kind: "code"
186
+ });
187
+ offset = addressEnd;
188
+ continue;
189
+ }
190
+ const code = /^(?:'(?:\$[\s\S]|''|[^'])*'|"(?:\$[\s\S]|""|[^"])*"|\d[\d_]*#[\da-fA-F_]+|\d[\d_]*(?:\.(?!\.)[\d_]+)?(?:[eE][+-]?\d+)?|[A-Za-z_]\w*|:=|\.\.|[[\]():;,.+\-*/#])/i.exec(rest);
191
+ if (!code) {
144
192
  throw new Error(`${source.name}:${source.text.slice(0, offset).split(`
145
193
  `).length}: unsupported token ${JSON.stringify(rest.slice(0, 24))}`);
194
+ }
146
195
  tokens.push({ text: code[0], offset, kind: "code" });
147
196
  offset += code[0].length;
148
197
  }
@@ -159,8 +208,9 @@ class Parser {
159
208
  }
160
209
  nextIndex() {
161
210
  let index = this.position;
162
- while (this.tokens[index] && this.tokens[index].kind !== "code")
211
+ while (index < this.tokens.length && this.tokens[index]?.kind !== "code") {
163
212
  index++;
213
+ }
164
214
  return index;
165
215
  }
166
216
  peek() {
@@ -174,24 +224,28 @@ class Parser {
174
224
  take() {
175
225
  this.position = this.nextIndex();
176
226
  const token = this.tokens[this.position++];
177
- if (!token)
227
+ if (!token) {
178
228
  this.error("unexpected end of declaration");
229
+ }
179
230
  return token.text;
180
231
  }
181
232
  accept(value) {
182
- if (this.peek() !== value)
233
+ if (this.peek() !== value) {
183
234
  return false;
235
+ }
184
236
  this.take();
185
237
  return true;
186
238
  }
187
239
  expect(value) {
188
- if (!this.accept(value))
240
+ if (!this.accept(value)) {
189
241
  this.error(`expected ${value}, found ${this.peek() || "end of file"}`);
242
+ }
190
243
  }
191
244
  identifier() {
192
245
  const name = this.take();
193
- if (!/^[A-Za-z_]\w*$/.test(name))
246
+ if (!identifierPattern.test(name)) {
194
247
  this.error(`expected identifier, found ${name}`);
248
+ }
195
249
  return name;
196
250
  }
197
251
  documentation() {
@@ -206,16 +260,19 @@ class Parser {
206
260
  const closing = [];
207
261
  while (this.peek() && (closing.length || !stops.includes(this.peek()))) {
208
262
  const token = this.take();
209
- if (token === "(" || token === "[")
263
+ if (token === "(" || token === "[") {
210
264
  closing.push(token === "(" ? ")" : "]");
265
+ }
211
266
  if (token === ")" || token === "]") {
212
- if (closing.pop() !== token)
267
+ if (closing.pop() !== token) {
213
268
  this.error(`unmatched ${token}`);
269
+ }
214
270
  }
215
271
  values.push(token);
216
272
  }
217
- if (!values.length || closing.length)
273
+ if (!values.length || closing.length) {
218
274
  this.error("incomplete expression");
275
+ }
219
276
  return values.join(" ");
220
277
  }
221
278
  reference() {
@@ -233,14 +290,16 @@ class Parser {
233
290
  return { kind: "array", dimensions, element: this.reference() };
234
291
  }
235
292
  const parts = [this.identifier()];
236
- while (this.accept("."))
293
+ while (this.accept(".")) {
237
294
  parts.push(this.identifier());
295
+ }
238
296
  const name = parts.join(".");
239
297
  const upper = name.toUpperCase();
240
298
  if (upper === "STRING" || upper === "WSTRING") {
241
299
  const opening = this.peek();
242
- if (opening !== "(" && opening !== "[")
300
+ if (opening !== "(" && opening !== "[") {
243
301
  return { kind: "string", name: upper, length: "80" };
302
+ }
244
303
  this.take();
245
304
  const closing = opening === "(" ? ")" : "]";
246
305
  const length = this.expression([closing]);
@@ -255,20 +314,23 @@ class Parser {
255
314
  const published = this.tokens.slice(this.position, this.nextIndex()).some((token) => token.kind === "attribute" && /^\{\s*attribute\s+'symbol'\s*:=\s*'(?:read|write|readwrite)'\s*\}$/i.test(token.text));
256
315
  const description = this.documentation();
257
316
  const names = [this.identifier()];
258
- while (this.accept(","))
317
+ while (this.accept(",")) {
259
318
  names.push(this.identifier());
319
+ }
260
320
  if (this.accept("AT")) {
261
321
  const address = this.take();
262
- if (!/^%[IQM](?:[XBWDL])?(?:\d+(?:\.\d+)*|\*)$/i.test(address))
322
+ if (directAddressEnd(address, 0) !== address.length) {
263
323
  this.error(`expected direct address after AT, found ${address}`);
324
+ }
264
325
  }
265
326
  this.expect(":");
266
327
  const type = this.reference();
267
328
  const initial = this.accept(":=") ? this.expression([";"]) : undefined;
268
329
  this.expect(";");
269
330
  for (const name of names) {
270
- if (members.some((member) => member.name.toUpperCase() === name.toUpperCase()))
331
+ if (members.some((member) => member.name.toUpperCase() === name.toUpperCase())) {
271
332
  this.error(`duplicate member ${name}`);
333
+ }
272
334
  members.push({
273
335
  name,
274
336
  description,
@@ -302,8 +364,9 @@ class Parser {
302
364
  do {
303
365
  const member = this.identifier();
304
366
  const value = this.accept(":=") ? this.expression([",", ")"]) : undefined;
305
- if (members.some((item) => item.name.toUpperCase() === member.toUpperCase()))
367
+ if (members.some((item) => item.name.toUpperCase() === member.toUpperCase())) {
306
368
  this.error(`duplicate enum member ${member}`);
369
+ }
307
370
  members.push({ name: member, value });
308
371
  } while (this.accept(",") && this.peek() !== ")");
309
372
  this.expect(")");
@@ -313,33 +376,44 @@ class Parser {
313
376
  } else {
314
377
  const type = this.reference();
315
378
  this.expect(";");
316
- declarations.push({ ...common, kind: "alias", type, ...keyed ? { keyed } : {} });
379
+ declarations.push({
380
+ ...common,
381
+ kind: "alias",
382
+ type,
383
+ ...keyed ? { keyed } : {}
384
+ });
317
385
  }
318
386
  this.expect("END_TYPE");
319
387
  this.accept(";");
320
388
  }
321
- if (!declarations.length)
389
+ if (!declarations.length) {
322
390
  this.error("no TYPE declarations found");
391
+ }
323
392
  return declarations;
324
393
  }
325
394
  globals(name) {
326
395
  const description = this.documentation();
327
396
  this.expect("VAR_GLOBAL");
328
- let constant = false;
329
- const qualifiers = new Set;
330
- while (["CONSTANT", "RETAIN", "PERSISTENT"].includes(this.peek())) {
397
+ const written = new Set;
398
+ while (qualifiers.has(this.peek())) {
331
399
  const qualifier = this.take().toUpperCase();
332
- if (qualifiers.has(qualifier))
400
+ if (written.has(qualifier)) {
333
401
  this.error(`duplicate ${qualifier} qualifier`);
334
- qualifiers.add(qualifier);
335
- if (qualifier === "CONSTANT")
336
- constant = true;
402
+ }
403
+ written.add(qualifier);
337
404
  }
338
405
  const members = this.members("END_VAR");
339
406
  this.accept(";");
340
- if (this.peek())
407
+ if (this.peek()) {
341
408
  this.error("only one VAR_GLOBAL block per file is supported");
342
- return { name, description, source: this.source.name, constant, members };
409
+ }
410
+ return {
411
+ name,
412
+ description,
413
+ source: this.source.name,
414
+ constant: written.has("CONSTANT"),
415
+ members
416
+ };
343
417
  }
344
418
  }
345
419
  function parseDeclarations(source) {
@@ -350,40 +424,41 @@ function parseGlobals(source, name) {
350
424
  }
351
425
 
352
426
  // packages/typegen/src/codegen/generate.ts
353
- var integerTypePattern = /^(?:U?S?INT|U?DINT|BYTE|WORD|DWORD)$/;
354
- var scalars = {
355
- BOOL: "boolean",
356
- BYTE: "number",
357
- WORD: "number",
358
- DWORD: "number",
359
- LWORD: "bigint",
360
- SINT: "number",
361
- INT: "number",
362
- DINT: "number",
363
- LINT: "bigint",
364
- USINT: "number",
365
- UINT: "number",
366
- UDINT: "number",
367
- ULINT: "bigint",
368
- REAL: "number",
369
- LREAL: "number",
370
- TIME: "number",
371
- TOD: "number",
372
- TIME_OF_DAY: "number",
373
- DATE: "number",
374
- DT: "number",
375
- DATE_AND_TIME: "number"
427
+ var scalarType = (type) => {
428
+ switch (type.family) {
429
+ case "bool":
430
+ return "boolean";
431
+ case "integer":
432
+ case "bits":
433
+ return type.bits === 64 ? "bigint" : "number";
434
+ case "real":
435
+ return "number";
436
+ case "duration":
437
+ case "date":
438
+ case "timeOfDay":
439
+ case "dateTime":
440
+ return type.bits === 32 ? "number" : undefined;
441
+ case "char":
442
+ case "string":
443
+ return;
444
+ }
376
445
  };
446
+ var scalars = Object.fromEntries([...elementaryTypesByName].flatMap(([name, type]) => {
447
+ const typescript = scalarType(type);
448
+ return typescript ? [[name, typescript]] : [];
449
+ }));
377
450
  async function stFiles(directory) {
378
451
  const entries = await readdir(directory, { withFileTypes: true });
379
452
  const paths = await Promise.all(entries.sort((a, b) => {
380
- if (a.name === b.name)
453
+ if (a.name === b.name) {
381
454
  return 0;
455
+ }
382
456
  return a.name < b.name ? -1 : 1;
383
457
  }).map(async (entry) => {
384
458
  const file = join(directory, entry.name);
385
- if (entry.isDirectory())
459
+ if (entry.isDirectory()) {
386
460
  return stFiles(file);
461
+ }
387
462
  return entry.isFile() && /\.st$/i.test(file) ? [file] : [];
388
463
  }));
389
464
  return paths.flat();
@@ -396,85 +471,68 @@ function unique(items) {
396
471
  const result = new Map;
397
472
  for (const item of items) {
398
473
  const key = item.name.toUpperCase();
399
- if (result.has(key))
474
+ if (result.has(key)) {
400
475
  throw new Error(`${item.source}: duplicate declaration ${item.name} (also in ${result.get(key)?.source})`);
476
+ }
401
477
  result.set(key, item);
402
478
  }
403
479
  return result;
404
480
  }
481
+ var readSources = (files) => Promise.all(files.map(async (name) => ({ name, text: await readFile(name, "utf8") })));
405
482
  async function generateTypes(options) {
406
483
  const typeFiles = typeof options.types === "string" ? await stFiles(options.types) : options.types;
407
- const declarations = (await Promise.all(typeFiles.map(async (name) => parseDeclarations({ name, text: await readFile(name, "utf8") })))).flat();
484
+ const declarations = (await readSources(typeFiles)).flatMap((source) => parseDeclarations(source));
408
485
  const globalFiles = typeof options.globals === "string" ? await stFiles(options.globals) : options.globals ?? [];
409
- if (!typeFiles.length && !globalFiles.length && (typeof options.types === "string" || typeof options.globals === "string"))
486
+ if (!typeFiles.length && !globalFiles.length && (typeof options.types === "string" || typeof options.globals === "string")) {
410
487
  throw new Error(`no .st declarations found in ${typeof options.types === "string" ? options.types : "the selected source files"}`);
411
- let globals = await Promise.all(globalFiles.map(async (name) => parseGlobals({ name, text: await readFile(name, "utf8") }, basename(name).replace(/\.st$/i, ""))));
412
- if (options.publishedGlobalsOnly)
413
- globals = globals.map((list) => list.constant ? list : {
414
- ...list,
415
- members: list.members.filter((member) => options.publication ? [
416
- ...options.publication.production,
417
- ...options.publication.development
418
- ].includes(`${list.name}.${member.name}`) : member.published)
419
- }).filter((list) => list.constant || list.members.length);
420
- const contract = emit(declarations, globals, options.publishedGlobalsOnly ?? false, options.declarations ?? true);
488
+ }
489
+ const globals = (await readSources(globalFiles)).map((source) => parseGlobals(source, basename(source.name).replace(/\.st$/i, "")));
490
+ const publishedGlobalsOnly = options.publishedGlobalsOnly ?? false;
491
+ const contract = emit(declarations, publishedGlobalsOnly ? published(globals, options.publication) : globals, { publishedGlobalsOnly, emitDeclarations: options.declarations ?? true });
421
492
  return options.publication ? `${contract}
422
493
  export const publication = ${JSON.stringify(options.publication, null, 2)} as const;
423
494
  ` : contract;
424
495
  }
425
- function emit(declarations, globals, publishedGlobalsOnly, emitDeclarations) {
496
+ function published(globals, publication) {
497
+ return globals.map((list) => list.constant ? list : {
498
+ ...list,
499
+ members: list.members.filter((member) => publication ? [
500
+ ...publication.production,
501
+ ...publication.development
502
+ ].includes(`${list.name}.${member.name}`) : member.published)
503
+ }).filter((list) => list.constant || list.members.length);
504
+ }
505
+ function emit(declarations, globals, {
506
+ publishedGlobalsOnly,
507
+ emitDeclarations
508
+ }) {
426
509
  const types = unique(declarations);
427
510
  unique(globals);
428
511
  const constants = globals.filter((list) => list.constant);
429
512
  const constantLists = publishedGlobalsOnly ? constants.map((list) => ({
430
513
  ...list,
431
- members: list.members.filter((member) => member.type.kind === "named" && integerTypePattern.test(member.type.name.toUpperCase()))
514
+ members: list.members.filter((member) => member.type.kind === "named" && isNumberInteger(member.type.name.toUpperCase()))
432
515
  })).filter((list) => list.members.length) : constants;
433
516
  const variableLists = globals.filter((list) => !list.constant);
434
- const constantValues = new Map;
435
- const resolvingConstants = new Set;
436
- const constantDefinitions = constants.flatMap((list) => list.members.map((member) => ({
437
- list,
438
- member,
439
- key: `${list.name}.${member.name}`.toUpperCase()
440
- })));
441
- function constant(name, scope) {
442
- const key = name.toUpperCase();
443
- const scoped = constantDefinitions.find((item) => item.key === `${scope}.${name}`.toUpperCase());
444
- const candidates = scoped ? [scoped] : constantDefinitions.filter((item) => item.key === key || !name.includes(".") && item.member.name.toUpperCase() === key);
445
- if (candidates.length !== 1)
446
- throw new Error(`unknown or ambiguous constant ${name}`);
447
- const definition = candidates[0];
448
- const cached = constantValues.get(definition.key);
449
- if (cached !== undefined)
450
- return cached;
451
- if (resolvingConstants.has(definition.key))
452
- throw new Error(`cyclic constant ${name}`);
453
- const { member, list } = definition;
454
- if (member.initial === undefined || member.type.kind !== "named" || !integerTypePattern.test(member.type.name.toUpperCase()))
455
- throw new Error(`${list.source}: constant ${member.name} must have an integer type and initializer`);
456
- resolvingConstants.add(definition.key);
457
- const value = integerExpression(member.initial, (reference) => constant(reference, list.name));
458
- resolvingConstants.delete(definition.key);
459
- constantValues.set(definition.key, value);
460
- return value;
461
- }
517
+ const constant = constantResolver(constants);
462
518
  function bound(expression) {
463
- return integerExpression(expression, (name) => constant(name));
519
+ return integerExpression(expression, (name) => constant(name, null));
464
520
  }
465
521
  function dimensions(type) {
466
522
  return type.dimensions.map(({ lower, upper }) => {
467
523
  const start = bound(lower);
468
524
  const end = bound(upper);
469
- if (end < start || !Number.isSafeInteger(end - start + 1))
525
+ if (end < start || !Number.isSafeInteger(end - start + 1)) {
470
526
  throw new Error(`invalid array bounds ${lower}..${upper}`);
527
+ }
471
528
  return { start, end };
472
529
  });
473
530
  }
474
531
  function declaration(name) {
475
532
  const found = types.get(name.toUpperCase());
476
- if (!found)
533
+ if (!found) {
477
534
  throw new Error(`unknown IEC type ${name}`);
535
+ }
478
536
  return found;
479
537
  }
480
538
  function tsType(type) {
@@ -484,49 +542,61 @@ function emit(declarations, globals, publishedGlobalsOnly, emitDeclarations) {
484
542
  }
485
543
  if (type.kind === "string") {
486
544
  const length = bound(type.length);
487
- if (length < 1)
545
+ if (length < 1) {
488
546
  throw new Error(`invalid ${type.name} length ${length}`);
547
+ }
489
548
  return "string";
490
549
  }
491
550
  return scalars[type.name.toUpperCase()] ?? declaration(type.name).name;
492
551
  }
493
552
  function resolved(type) {
494
- if (type.kind !== "named" || scalars[type.name.toUpperCase()])
553
+ if (type.kind !== "named" || scalars[type.name.toUpperCase()]) {
495
554
  return type;
555
+ }
496
556
  const definition = declaration(type.name);
497
- if (definition.kind === "alias")
557
+ if (definition.kind === "alias") {
498
558
  return resolved(definition.type);
499
- if (definition.kind === "enum")
559
+ }
560
+ if (definition.kind === "enum") {
500
561
  return { kind: "named", name: definition.base };
562
+ }
501
563
  return type;
502
564
  }
503
565
  function iecType(type) {
504
566
  const actual = resolved(type);
505
- if (actual.kind === "string")
567
+ if (actual.kind === "string") {
506
568
  return `${actual.name}(${bound(actual.length)})`;
507
- if (actual.kind === "array")
569
+ }
570
+ if (actual.kind === "array") {
508
571
  return `ARRAY[${dimensions(actual).map(({ start, end }) => `${start}..${end}`).join(", ")}] OF ${iecType(actual.element)}`;
572
+ }
509
573
  return scalars[actual.name.toUpperCase()] ? actual.name.toUpperCase() : declaration(actual.name).name;
510
574
  }
511
575
  const ordered = [];
512
576
  const visiting = new Set;
513
577
  const visited = new Set;
514
578
  function visitReference(type) {
515
- if (type.kind === "array")
579
+ if (type.kind === "array") {
516
580
  return visitReference(type.element);
517
- if (type.kind === "named" && !scalars[type.name.toUpperCase()])
581
+ }
582
+ if (type.kind === "named" && !scalars[type.name.toUpperCase()]) {
518
583
  visit(declaration(type.name));
584
+ }
519
585
  }
520
586
  function visit(type) {
521
- if (visited.has(type.name))
587
+ if (visited.has(type.name)) {
522
588
  return;
523
- if (visiting.has(type.name))
589
+ }
590
+ if (visiting.has(type.name)) {
524
591
  throw new Error(`${type.source}: cyclic type reference involving ${type.name}`);
592
+ }
525
593
  visiting.add(type.name);
526
- if (type.kind === "struct")
594
+ if (type.kind === "struct") {
527
595
  type.members.forEach((member) => visitReference(member.type));
528
- if (type.kind === "alias")
596
+ }
597
+ if (type.kind === "alias") {
529
598
  visitReference(type.type);
599
+ }
530
600
  visiting.delete(type.name);
531
601
  visited.add(type.name);
532
602
  ordered.push(type);
@@ -537,20 +607,23 @@ function emit(declarations, globals, publishedGlobalsOnly, emitDeclarations) {
537
607
  ...declarations.map((type) => type.name),
538
608
  ...constantLists.map((list) => list.name)
539
609
  ]) {
540
- if (!/^[A-Za-z_]\w*$/.test(name) || reserved.has(name) || /^_fields\d+$/.test(name))
610
+ if (!identifierPattern2.test(name) || reserved.has(name) || /^_fields\d+$/.test(name)) {
541
611
  throw new Error(`name cannot be exported to TypeScript: ${name}`);
612
+ }
542
613
  reserved.add(name);
543
614
  }
544
615
  const indexes = new Map(ordered.map((type, index) => [type.name, index]));
545
616
  function complex(type) {
546
617
  const actual = resolved(type);
547
- if (actual.kind === "array")
618
+ if (actual.kind === "array") {
548
619
  return complex(actual.element);
620
+ }
549
621
  return actual.kind === "named" && !scalars[actual.name.toUpperCase()];
550
622
  }
551
623
  function keyed(type) {
552
- if (type.kind !== "named" || scalars[type.name.toUpperCase()])
624
+ if (type.kind !== "named" || scalars[type.name.toUpperCase()]) {
553
625
  return false;
626
+ }
554
627
  const definition = declaration(type.name);
555
628
  return definition.kind === "alias" && (!!definition.keyed || keyed(definition.type));
556
629
  }
@@ -558,8 +631,9 @@ function emit(declarations, globals, publishedGlobalsOnly, emitDeclarations) {
558
631
  const actual = resolved(type);
559
632
  if (actual.kind === "named" && complex(actual)) {
560
633
  const children = `_fields${indexes.get(declaration(actual.name).name)}`;
561
- if (path === '""')
634
+ if (path === '""') {
562
635
  return children;
636
+ }
563
637
  return `${children}.map((member) => ({ ...member, field: ${path} + "." + member.field }))`;
564
638
  }
565
639
  if (actual.kind === "array" && (complex(actual.element) || keyed(type))) {
@@ -597,12 +671,13 @@ ${type.members.map((member) => `...${fields(member.type, quote(member.name), mem
597
671
  output.push(`const _fields${indexes.get(type.name)}: PlcField[] = ${fields({ kind: "named", name: type.name }, '""', type.description)};
598
672
  `);
599
673
  } else {
600
- if (!integerTypePattern.test(type.base))
674
+ if (!isNumberInteger(type.base)) {
601
675
  throw new Error(`unsupported enum base ${type.base}`);
676
+ }
602
677
  const entries = new Map;
603
678
  for (const member of type.members) {
604
679
  const previous = [...entries.values()].at(-1) ?? -1;
605
- const value = member.value === undefined ? previous + 1 : integerExpression(member.value, (name) => entries.get(name.toUpperCase()) ?? constant(name));
680
+ const value = member.value === undefined ? previous + 1 : integerExpression(member.value, (name) => entries.get(name.toUpperCase()) ?? constant(name, null));
606
681
  entries.set(member.name.toUpperCase(), value);
607
682
  }
608
683
  output.push(...declare(`${doc}export const ${type.name} = { ${type.members.map((member) => `${quote(member.name)}: ${entries.get(member.name.toUpperCase())}`).join(", ")} } as const;
@@ -622,7 +697,7 @@ ${ordered.map((type) => `${quote(type.name)}: _fields${indexes.get(type.name)},`
622
697
  `);
623
698
  for (const list of emitDeclarations ? constantLists : []) {
624
699
  output.push(`${documentation(list.description)}export const ${list.name} = {
625
- ${list.members.map((member) => `${documentation(member.description)}${quote(member.name)}: ${constant(`${list.name}.${member.name}`)},`).join(`
700
+ ${list.members.map((member) => `${documentation(member.description)}${quote(member.name)}: ${constant(`${list.name}.${member.name}`, null)},`).join(`
626
701
  `)}
627
702
  } as const;
628
703
  `);
@@ -652,5 +727,5 @@ export {
652
727
  stFiles
653
728
  };
654
729
 
655
- //# debugId=AF0D1B3E4A91B54A64756E2164756E21
730
+ //# debugId=AF7163667E33A4BF64756E2164756E21
656
731
  //# sourceMappingURL=codegen.js.map