@tsplc/typegen 0.5.13 → 0.5.15

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,91 +1,107 @@
1
1
  // packages/typegen/src/codegen/declarations.ts
2
- import { readFile as readFile2 } from "node:fs/promises";
3
- import { basename as basename2 } from "node:path";
4
- import { blockCommentEnd as blockCommentEnd2, lineCommentEnd as lineCommentEnd2 } from "@tsplc/iec/st";
2
+ import { readFile as readFile3 } from "node:fs/promises";
5
3
 
6
- // packages/typegen/src/codegen/generate.ts
4
+ // packages/typegen/src/files.ts
7
5
  import { readdir, readFile } from "node:fs/promises";
8
- import { basename, join } from "node:path";
9
- import { elementaryTypesByName } from "@tsplc/iec";
10
- import { identifierPattern as identifierPattern2 } from "@tsplc/iec/st";
11
-
12
- // packages/typegen/src/codegen/constants.ts
13
- import {
14
- elementaryType,
15
- elementaryTypes,
16
- integerRange,
17
- isIntegerValued
18
- } from "@tsplc/iec";
19
- var integerRanges = new Map(elementaryTypes.filter(isIntegerValued).map((type) => [type.name, integerRange(type)]));
20
- 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");
6
+ import { join } from "node:path";
7
+ async function filesUnder(directory, extension, order) {
8
+ const pattern = new RegExp(`\\.${extension}$`, "i");
9
+ const entries = await readdir(directory, { withFileTypes: true });
10
+ const paths = await Promise.all(entries.sort((a, b) => order(a.name, b.name)).map(async (entry) => {
11
+ const path = join(directory, entry.name);
12
+ if (entry.isDirectory()) {
13
+ return filesUnder(path, extension, order);
14
+ }
15
+ return entry.isFile() && pattern.test(entry.name) ? [path] : [];
16
+ }));
17
+ return paths.flat();
18
+ }
19
+ var stFiles = (directory) => filesUnder(directory, "st", (a, b) => a < b ? -1 : 1);
21
20
 
22
21
  // packages/typegen/src/codegen/parser.ts
22
+ import { readFile as readFile2 } from "node:fs/promises";
23
+ import { basename } from "node:path";
24
+ import { defaultStringLength } from "@tsplc/iec";
23
25
  import {
24
26
  blockCommentEnd,
25
27
  directAddressEnd,
28
+ identifierPart,
26
29
  identifierPattern,
30
+ identifierStart,
27
31
  lineCommentEnd,
28
- qualifiers
32
+ qualifiers,
33
+ stringEnd
29
34
  } from "@tsplc/iec/st";
35
+ var pragmaEnd = (text, offset) => {
36
+ const next = text.slice(offset).search(/[}'"]/);
37
+ if (next < 0) {
38
+ return null;
39
+ }
40
+ const at = offset + next;
41
+ if (text[at] === "}") {
42
+ return at + 1;
43
+ }
44
+ const end = stringEnd(text, at);
45
+ return end === null ? null : pragmaEnd(text, end);
46
+ };
47
+ var codeToken = new RegExp(String.raw`^(?:\d[\d_]*#[\da-fA-F_]+|\d[\d_]*(?:\.(?!\.)[\d_]+)?(?:[eE][+-]?\d+)?|${identifierStart}${identifierPart}*|:=|\.\.|[[\]():;,.+\-*/#])`, "i");
48
+ function tokenAt(source, start) {
49
+ const { text } = source;
50
+ const offset = start + text.slice(start).search(/\S|$/);
51
+ if (offset === text.length) {
52
+ return;
53
+ }
54
+ const rest = text.slice(offset);
55
+ if (rest.startsWith("(*")) {
56
+ const end = blockCommentEnd(text, offset);
57
+ if (end === null) {
58
+ throw new Error(`${source.name}: unterminated comment`);
59
+ }
60
+ const comment = text.slice(offset + 2, end - 2).trim();
61
+ return { text: comment, offset, end, kind: "comment" };
62
+ }
63
+ if (rest.startsWith("//")) {
64
+ const end = lineCommentEnd(text, offset);
65
+ const comment = text.slice(offset + 2, end).trim();
66
+ return { text: comment, offset, end, kind: "comment" };
67
+ }
68
+ const code = (kind, end) => ({
69
+ text: text.slice(offset, end),
70
+ offset,
71
+ end,
72
+ kind
73
+ });
74
+ const attributeEnd = rest.startsWith("{") ? pragmaEnd(text, offset + 1) : null;
75
+ if (attributeEnd !== null) {
76
+ return code("attribute", attributeEnd);
77
+ }
78
+ const addressEnd = directAddressEnd(text, offset);
79
+ if (addressEnd !== null) {
80
+ return code("code", addressEnd);
81
+ }
82
+ const literalEnd = rest.startsWith("'") || rest.startsWith('"') ? stringEnd(text, offset) : null;
83
+ if (literalEnd !== null) {
84
+ return code("code", literalEnd);
85
+ }
86
+ const word = codeToken.exec(rest);
87
+ if (!word) {
88
+ throw new Error(`${source.name}:${text.slice(0, offset).split(`
89
+ `).length}: unsupported token ${JSON.stringify(rest.slice(0, 24))}`);
90
+ }
91
+ return code("code", offset + word[0].length);
92
+ }
30
93
  function tokenize(source) {
31
94
  const tokens = [];
32
- let offset = 0;
33
- while (offset < source.text.length) {
34
- const rest = source.text.slice(offset);
35
- const whitespace = /^\s+/.exec(rest);
36
- if (whitespace) {
37
- offset += whitespace[0].length;
38
- continue;
39
- }
40
- if (rest.startsWith("(*")) {
41
- const end = blockCommentEnd(source.text, offset);
42
- if (end === null) {
43
- throw new Error(`${source.name}: unterminated comment`);
44
- }
45
- tokens.push({
46
- text: source.text.slice(offset + 2, end - 2).trim(),
47
- offset,
48
- kind: "comment"
49
- });
50
- offset = end;
51
- continue;
52
- }
53
- if (rest.startsWith("//")) {
54
- const end = lineCommentEnd(source.text, offset);
55
- tokens.push({
56
- text: source.text.slice(offset + 2, end).trim(),
57
- offset,
58
- kind: "comment"
59
- });
60
- offset = end;
61
- continue;
62
- }
63
- const attribute = /^\{(?:[^}'"]|'(?:\$[\s\S]|''|[^'])*'|"(?:\$[\s\S]|""|[^"])*")*\}/.exec(rest);
64
- if (attribute) {
65
- tokens.push({ text: attribute[0], offset, kind: "attribute" });
66
- offset += attribute[0].length;
67
- continue;
68
- }
69
- const addressEnd = directAddressEnd(source.text, offset);
70
- if (addressEnd !== null) {
71
- tokens.push({
72
- text: source.text.slice(offset, addressEnd),
73
- offset,
74
- kind: "code"
75
- });
76
- offset = addressEnd;
77
- continue;
78
- }
79
- const code = /^(?:'(?:\$[\s\S]|''|[^'])*'|"(?:\$[\s\S]|""|[^"])*"|\d[\d_]*#[\da-fA-F_]+|\d[\d_]*(?:\.(?!\.)[\d_]+)?(?:[eE][+-]?\d+)?|[A-Za-z_]\w*|:=|\.\.|[[\]():;,.+\-*/#])/i.exec(rest);
80
- if (!code) {
81
- throw new Error(`${source.name}:${source.text.slice(0, offset).split(`
82
- `).length}: unsupported token ${JSON.stringify(rest.slice(0, 24))}`);
83
- }
84
- tokens.push({ text: code[0], offset, kind: "code" });
85
- offset += code[0].length;
95
+ for (let token = tokenAt(source, 0);token; token = tokenAt(source, token.end)) {
96
+ tokens.push(token);
86
97
  }
87
98
  return tokens;
88
99
  }
100
+ var codeTokenAt = (source, offset) => {
101
+ const token = tokenAt(source, offset);
102
+ return token && token.kind !== "code" ? codeTokenAt(source, token.end) : token;
103
+ };
104
+ var firstCodeToken = (source) => codeTokenAt(source, 0)?.text;
89
105
 
90
106
  class Parser {
91
107
  source;
@@ -187,7 +203,11 @@ class Parser {
187
203
  if (upper === "STRING" || upper === "WSTRING") {
188
204
  const opening = this.peek();
189
205
  if (opening !== "(" && opening !== "[") {
190
- return { kind: "string", name: upper, length: "80" };
206
+ return {
207
+ kind: "string",
208
+ name: upper,
209
+ length: String(defaultStringLength)
210
+ };
191
211
  }
192
212
  this.take();
193
213
  const closing = opening === "(" ? ")" : "]";
@@ -326,92 +346,211 @@ function parseDeclarations(source) {
326
346
  function parseGlobals(source, name) {
327
347
  return new Parser(source).globals(name);
328
348
  }
349
+ var readSource = async (name) => ({
350
+ name,
351
+ text: await readFile2(name, "utf8")
352
+ });
353
+ async function parseSources(files) {
354
+ return {
355
+ types: (await Promise.all(files.types.map(readSource))).flatMap(parseDeclarations),
356
+ globals: (await Promise.all(files.globals.map(readSource))).map((source) => parseGlobals(source, basename(source.name).replace(/\.st$/i, "")))
357
+ };
358
+ }
359
+
360
+ // packages/typegen/src/codegen/resolution.ts
361
+ import { elementaryType as elementaryType2 } from "@tsplc/iec";
329
362
 
330
- // packages/typegen/src/codegen/generate.ts
331
- var scalarType = (type) => {
332
- switch (type.family) {
333
- case "bool":
334
- return "boolean";
335
- case "integer":
336
- case "bits":
337
- return type.bits === 64 ? "bigint" : "number";
338
- case "real":
339
- return "number";
340
- case "duration":
341
- case "date":
342
- case "timeOfDay":
343
- case "dateTime":
344
- return type.bits === 32 ? "number" : undefined;
345
- case "char":
346
- case "string":
347
- return;
363
+ // packages/typegen/src/codegen/constants.ts
364
+ import {
365
+ elementaryType,
366
+ elementaryTypes,
367
+ fitsNumber,
368
+ integerRange,
369
+ isIntegerValued
370
+ } from "@tsplc/iec";
371
+ import { identifierPart as identifierPart2, identifierStart as identifierStart2, integerLiteral } from "@tsplc/iec/st";
372
+ var integerRanges = new Map(elementaryTypes.filter(isIntegerValued).map((type) => [type.name, integerRange(type)]));
373
+ var identifier = `${identifierStart2}${identifierPart2}*`;
374
+ var startsWithIdentifier = new RegExp(`^${identifierStart2}`);
375
+ 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_]*|${identifier}(?:\s*\.\s*${identifier})?|[()+\-*/]`, "g");
376
+ function integerExpression(text, lookup) {
377
+ const compact = text.replace(/\s+/g, "");
378
+ const tokens = (text.match(integerToken) ?? []).map((token) => token.replace(/\s+/g, ""));
379
+ if (tokens.join("") !== compact || !tokens.length) {
380
+ throw new Error(`unsupported integer expression: ${text}`);
348
381
  }
349
- };
350
- var scalars = Object.fromEntries([...elementaryTypesByName].flatMap(([name, type]) => {
351
- const typescript = scalarType(type);
352
- return typescript ? [[name, typescript]] : [];
353
- }));
354
- async function stFiles(directory) {
355
- const entries = await readdir(directory, { withFileTypes: true });
356
- const paths = await Promise.all(entries.sort((a, b) => {
357
- if (a.name === b.name) {
358
- return 0;
382
+ const safe = (value) => {
383
+ if (!Number.isSafeInteger(value)) {
384
+ throw new Error(`integer outside JavaScript's safe range: ${text}`);
359
385
  }
360
- return a.name < b.name ? -1 : 1;
361
- }).map(async (entry) => {
362
- const file = join(directory, entry.name);
363
- if (entry.isDirectory()) {
364
- return stFiles(file);
386
+ return value;
387
+ };
388
+ let position = 0;
389
+ function atom() {
390
+ const token = tokens[position++];
391
+ if (token === "+") {
392
+ return atom();
365
393
  }
366
- return entry.isFile() && /\.st$/i.test(file) ? [file] : [];
367
- }));
368
- return paths.flat();
369
- }
370
-
371
- // packages/typegen/src/codegen/declarations.ts
372
- var codeStart = (text, offset) => {
373
- const start = offset + text.slice(offset).search(/\S|$/);
374
- if (text.startsWith("(*", start)) {
375
- const end = blockCommentEnd2(text, start);
376
- return end === null ? start : codeStart(text, end);
394
+ if (token === "-") {
395
+ return -atom();
396
+ }
397
+ if (token === "(") {
398
+ const value = sum();
399
+ if (tokens[position++] !== ")") {
400
+ throw new Error(`unclosed integer expression: ${text}`);
401
+ }
402
+ return value;
403
+ }
404
+ const typed = token && [...integerRanges].find(([name]) => token.toUpperCase().startsWith(`${name}#`));
405
+ if (typed) {
406
+ const [name, [minimum, maximum]] = typed;
407
+ const value = integerExpression(token.slice(name.length + 1), lookup);
408
+ if (BigInt(value) < minimum || BigInt(value) > maximum) {
409
+ throw new Error(`typed integer outside ${name}: ${token}`);
410
+ }
411
+ return value;
412
+ }
413
+ if (token && /^\d/.test(token)) {
414
+ const literal = integerLiteral(token);
415
+ if (literal === undefined) {
416
+ throw new Error(`invalid integer literal: ${token}`);
417
+ }
418
+ return safe(Number(literal));
419
+ }
420
+ if (token && startsWithIdentifier.test(token)) {
421
+ return lookup(token);
422
+ }
423
+ throw new Error(`invalid integer expression: ${text}`);
377
424
  }
378
- if (text.startsWith("//", start)) {
379
- return codeStart(text, lineCommentEnd2(text, start));
425
+ function product() {
426
+ let value = atom();
427
+ while (tokens[position] === "*" || tokens[position] === "/") {
428
+ const operator = tokens[position++];
429
+ const right = atom();
430
+ if (operator === "/" && right === 0) {
431
+ throw new Error(`division by zero: ${text}`);
432
+ }
433
+ value = safe(operator === "*" ? value * right : Math.trunc(value / right));
434
+ }
435
+ return value;
380
436
  }
381
- if (text.startsWith("{", start)) {
382
- const end = text.indexOf("}", start);
383
- return end < 0 ? start : codeStart(text, end + 1);
437
+ function sum() {
438
+ let value = product();
439
+ while (tokens[position] === "+" || tokens[position] === "-") {
440
+ const operator = tokens[position++];
441
+ const right = product();
442
+ value = safe(operator === "+" ? value + right : value - right);
443
+ }
444
+ return value;
384
445
  }
385
- return start;
386
- };
446
+ const value = sum();
447
+ if (position !== tokens.length) {
448
+ throw new Error(`invalid integer expression: ${text}`);
449
+ }
450
+ return value;
451
+ }
452
+ var isIntegerConstant = (member) => member.type.kind === "named" && fitsNumber(elementaryType(member.type.name.toUpperCase()));
453
+ function constantResolver(lists) {
454
+ const values = new Map;
455
+ const resolving = new Set;
456
+ const definitions = lists.flatMap((list) => list.members.map((member) => ({
457
+ list,
458
+ member,
459
+ key: `${list.name}.${member.name}`.toUpperCase()
460
+ })));
461
+ const constant = (name, scope) => {
462
+ const key = name.toUpperCase();
463
+ const scoped = scope === null ? undefined : definitions.find((item) => item.key === `${scope}.${name}`.toUpperCase());
464
+ const [definition, ...others] = scoped ? [scoped] : definitions.filter((item) => item.key === key || !name.includes(".") && item.member.name.toUpperCase() === key);
465
+ if (!definition || others.length) {
466
+ throw new Error(`unknown or ambiguous constant ${name}`);
467
+ }
468
+ const cached = values.get(definition.key);
469
+ if (cached !== undefined) {
470
+ return cached;
471
+ }
472
+ if (resolving.has(definition.key)) {
473
+ throw new Error(`cyclic constant ${name}`);
474
+ }
475
+ const { member, list } = definition;
476
+ if (member.initial === undefined || !isIntegerConstant(member)) {
477
+ throw new Error(`${list.source}: constant ${member.name} must have an integer type and initializer`);
478
+ }
479
+ resolving.add(definition.key);
480
+ const value = integerExpression(member.initial, (reference) => constant(reference, list.name));
481
+ resolving.delete(definition.key);
482
+ values.set(definition.key, value);
483
+ return value;
484
+ };
485
+ return constant;
486
+ }
487
+
488
+ // packages/typegen/src/codegen/resolution.ts
489
+ function resolveDeclarations({
490
+ types,
491
+ globals
492
+ }) {
493
+ const declarations = new Map(types.map((declaration) => [declaration.name.toUpperCase(), declaration]));
494
+ const constant = constantResolver(globals.filter((list) => list.constant));
495
+ const integer = (expression) => integerExpression(expression, (name) => constant(name, null));
496
+ const declaration = (name) => {
497
+ const found = declarations.get(name.toUpperCase());
498
+ if (!found) {
499
+ throw new Error(`unknown IEC type ${name}`);
500
+ }
501
+ return found;
502
+ };
503
+ const aliasTarget = (reference) => {
504
+ if (reference.kind !== "named" || elementaryType2(reference.name.toUpperCase())) {
505
+ return reference;
506
+ }
507
+ const named = declaration(reference.name);
508
+ return named.kind === "alias" ? aliasTarget(named.type) : reference;
509
+ };
510
+ const bounds = (array) => array.dimensions.map(({ lower, upper }) => {
511
+ const start = integer(lower);
512
+ const end = integer(upper);
513
+ if (end < start || !Number.isSafeInteger(end - start + 1)) {
514
+ throw new Error(`invalid array bounds ${lower}..${upper}`);
515
+ }
516
+ return { start, end };
517
+ });
518
+ const enumMembers = (enumeration) => {
519
+ const members = [];
520
+ for (const member of enumeration.members) {
521
+ const value = member.value === undefined ? (members.at(-1)?.value ?? -1) + 1 : integerExpression(member.value, (name) => members.find((item) => item.name.toUpperCase() === name.toUpperCase())?.value ?? constant(name, null));
522
+ members.push({ name: member.name, value });
523
+ }
524
+ return members;
525
+ };
526
+ return { constant, integer, declaration, aliasTarget, bounds, enumMembers };
527
+ }
528
+
529
+ // packages/typegen/src/codegen/declarations.ts
387
530
  var declarationFiles = async (files) => {
388
531
  const sorted = {
389
532
  types: [],
390
533
  globals: []
391
534
  };
392
535
  for (const file of files) {
393
- const text = await readFile2(file, "utf8");
394
- const code = text.slice(codeStart(text, 0));
395
- if (/^TYPE\b/i.test(code)) {
536
+ const keyword = firstCodeToken({
537
+ name: file,
538
+ text: await readFile3(file, "utf8")
539
+ })?.toUpperCase();
540
+ if (keyword === "TYPE") {
396
541
  sorted.types.push(file);
397
- } else if (/^VAR_GLOBAL\b/i.test(code)) {
542
+ } else if (keyword === "VAR_GLOBAL") {
398
543
  sorted.globals.push(file);
399
544
  }
400
545
  }
401
546
  return sorted;
402
547
  };
403
- var readDeclarations = async (directory) => {
404
- const files = await declarationFiles(await stFiles(directory));
405
- const read = (file) => readFile2(file, "utf8").then((text) => ({ name: file, text }));
406
- return {
407
- types: (await Promise.all(files.types.map(read))).flatMap(parseDeclarations),
408
- globals: (await Promise.all(files.globals.map(read))).map((source) => parseGlobals(source, basename2(source.name).replace(/\.st$/i, "")))
409
- };
410
- };
548
+ var readDeclarations = async (directory) => parseSources(await declarationFiles(await stFiles(directory)));
411
549
  export {
412
550
  declarationFiles,
413
- readDeclarations
551
+ readDeclarations,
552
+ resolveDeclarations
414
553
  };
415
554
 
416
- //# debugId=8BB98AD7BD38EBD164756E2164756E21
555
+ //# debugId=0A40F9740E3E2EDE64756E2164756E21
417
556
  //# sourceMappingURL=declarations.js.map