@tsplc/compiler 0.6.0 → 0.6.2

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.
@@ -12,13 +12,7 @@ import { generatedDirectory } from "@tsplc/config/project-files";
12
12
  import ts from "typescript";
13
13
  import { modulePath } from "../lowering-key";
14
14
  import { plcSources } from "../module-graph";
15
- import {
16
- copied,
17
- from,
18
- joined,
19
- type Mapped,
20
- type Positions,
21
- } from "../positions";
15
+ import { from, joined, type Mapped, type Positions } from "../positions";
22
16
  import { inSdk, namesSdk, sdkModules, unaliased } from "../sdk";
23
17
  import { defaultNumericTypes } from "../types";
24
18
  import type { BoundPath, CompileDebug } from "../typescript";
@@ -26,10 +20,24 @@ import type { CapturedValue } from "./capture-protocol";
26
20
  import { GenericTypes } from "./generics";
27
21
  import { captureGraph } from "./graph";
28
22
  import { importPath } from "./imports";
29
- import { stringEnums, type TypeDeclarations } from "./layouts";
23
+ import {
24
+ plainName,
25
+ quotedField,
26
+ stringEnums,
27
+ type TypeDeclarations,
28
+ } from "./layouts";
30
29
  import { Model, type Root } from "./model";
30
+ import { unusedName } from "./names";
31
+ import {
32
+ constantInitializer,
33
+ definesTask,
34
+ Reduction,
35
+ serviceClients,
36
+ type Uncompiled,
37
+ } from "./reduce";
31
38
  import { Retention, retentionDeclarations } from "./retention";
32
39
  import { closingBrace, Specializer } from "./specialize";
40
+ import type { RootField } from "./storage";
33
41
  import { SpecializeError } from "./values";
34
42
 
35
43
  /**
@@ -185,70 +193,6 @@ const taskWork = (
185
193
  return work;
186
194
  };
187
195
 
188
- const constantInitializer = (
189
- node: ts.Expression,
190
- checker: ts.TypeChecker,
191
- sdk: string,
192
- ): boolean => {
193
- if (
194
- ts.isNumericLiteral(node) ||
195
- ts.isStringLiteral(node) ||
196
- ts.isNoSubstitutionTemplateLiteral(node) ||
197
- ts.isBigIntLiteral(node) ||
198
- node.kind === ts.SyntaxKind.TrueKeyword ||
199
- node.kind === ts.SyntaxKind.FalseKeyword
200
- ) {
201
- return true;
202
- }
203
- if (ts.isPrefixUnaryExpression(node)) {
204
- return constantInitializer(node.operand, checker, sdk);
205
- }
206
- if (
207
- ts.isAsExpression(node) ||
208
- ts.isSatisfiesExpression(node) ||
209
- ts.isParenthesizedExpression(node)
210
- ) {
211
- return constantInitializer(node.expression, checker, sdk);
212
- }
213
- if (ts.isPropertyAccessExpression(node)) {
214
- return ts.isIdentifier(node.expression);
215
- }
216
- if (ts.isIdentifier(node)) {
217
- return true;
218
- }
219
- if (ts.isObjectLiteralExpression(node)) {
220
- return node.properties.every(
221
- (property) =>
222
- (ts.isPropertyAssignment(property) &&
223
- constantInitializer(property.initializer, checker, sdk)) ||
224
- ts.isShorthandPropertyAssignment(property),
225
- );
226
- }
227
- if (ts.isArrayLiteralExpression(node)) {
228
- return node.elements.every((element) =>
229
- constantInitializer(element, checker, sdk),
230
- );
231
- }
232
- if (ts.isCallExpression(node)) {
233
- return (
234
- namesSdk(checker, sdk, node.expression, "createServiceClient") ||
235
- definesTask(node, checker, sdk)
236
- );
237
- }
238
- return false;
239
- };
240
-
241
- /** Whether `call` is `tasks.define(...)` or `backgroundTasks.define(...)`, which the async lowering compiles as written. */
242
- const definesTask = (
243
- call: ts.CallExpression,
244
- checker: ts.TypeChecker,
245
- sdk: string,
246
- ): boolean =>
247
- ts.isPropertyAccessExpression(call.expression) &&
248
- call.expression.name.text === "define" &&
249
- (namesSdk(checker, sdk, call.expression.expression, "tasks") ||
250
- namesSdk(checker, sdk, call.expression.expression, "backgroundTasks"));
251
-
252
196
  /**
253
197
  * Whether the program is plain TypeScript: it declares a class that is not a function block, one
254
198
  * extending the SDK's `FunctionBlock` however the module names it.
@@ -347,12 +291,15 @@ export const lowerElaboration = (
347
291
  references: NonNullable<PlcModule["references"]>;
348
292
  /** The string each member of a literal union's enum stands for, by `<types file>:<enum>`. */
349
293
  literals: Map<string, Record<string, string>>;
294
+ /** What of each module rewritten here the PLC compiles, where that is not all of it. */
295
+ reduced: Map<string, Uncompiled>;
350
296
  } => {
351
297
  const sources = new Map<string, Mapped>();
352
298
  const diagnostics: Diagnostic[] = [];
353
299
  const origins = new Map<string, { name: string; instance?: string }>();
354
300
  const folded: Folded[] = [];
355
301
  const literals = new Map<string, Record<string, string>>();
302
+ const reduced = new Map<string, Uncompiled>();
356
303
  const references: { id: number; path: string }[] = [];
357
304
  const referenceFields: string[] = [];
358
305
  const result = {
@@ -361,6 +308,7 @@ export const lowerElaboration = (
361
308
  origins,
362
309
  folded,
363
310
  literals,
311
+ reduced,
364
312
  references: { objects: references, fields: referenceFields },
365
313
  };
366
314
  const runtime = plcSources(program).filter(
@@ -417,7 +365,7 @@ export const lowerElaboration = (
417
365
  if (refused.length) {
418
366
  throw new AggregateError(refused);
419
367
  }
420
- const declarations = retentionDeclarations(runtime, checker, sdk);
368
+ const retained = retentionDeclarations(runtime, checker, sdk);
421
369
  const graph = captureGraph(entryFile, runtime, checker, configuration);
422
370
  // Generic classes specialize per instance, through a checker that knows each one's type arguments.
423
371
  const generics = new GenericTypes(checker);
@@ -425,18 +373,35 @@ export const lowerElaboration = (
425
373
  bound,
426
374
  inputs,
427
375
  });
428
- const rootModule = rootModules(model.roots, { directory, root, bound });
376
+ const generated = generatedModules(model.roots, { directory, root, bound });
377
+ const rootModule = generated.root;
429
378
  // A module that also holds state keeps its client and types, which a reply's type may need: the
430
379
  // router's types have no layout of their own.
431
380
  const named = (source: ts.SourceFile) =>
432
381
  isKept(source.fileName) ||
433
382
  serviceClients(source, checker, sdk).length > 0;
383
+ const reduction = new Reduction(checker, sdk, {
384
+ runtime,
385
+ kept: isKept,
386
+ entry: entrySource,
387
+ written,
388
+ bound,
389
+ });
390
+ // What the entry module declares for other modules to import, beside its code.
391
+ const declarations = reduction.entry();
434
392
  const specializer = new Specializer(
435
393
  model,
436
394
  generics,
437
395
  sdk,
438
396
  runtime,
439
- { kept: isKept, named },
397
+ {
398
+ kept: isKept,
399
+ named,
400
+ enumRefusal: (declaration) =>
401
+ reduction.sharesEnum(declaration)
402
+ ? undefined
403
+ : reduction.enumRefusal(declaration),
404
+ },
440
405
  rootModule,
441
406
  );
442
407
  const scans = scanFunctions.map((name) => {
@@ -473,20 +438,34 @@ export const lowerElaboration = (
473
438
  for (const name of specializer.initializers.takeSdkCalls()) {
474
439
  specializer.imports.addSdk(sdkModules.types, name);
475
440
  }
476
- const retention = new Retention(model, specializer.storage, declarations);
477
- const globals = new Map(
478
- [...specializer.storage.roots].map((item) => [
479
- item,
480
- storageGlobals(specializer, retention, item),
481
- ]),
482
- );
441
+ const retention = new Retention(model, specializer.storage, retained);
442
+ const stored = [...specializer.storage.roots].map((item) => ({
443
+ item,
444
+ ...storageGlobals(specializer, retention, item),
445
+ }));
483
446
  const unretained = retention.unclaimed();
484
447
  if (unretained) {
485
448
  throw unretained;
486
449
  }
487
450
  // Writing the globals declared the types they use.
488
451
  const types = specializer.layouts.snapshot();
489
- const typesFile = `${directory}/types.ts`;
452
+ // A storage module imports the generated types, so none of its variables can have a type's name.
453
+ const misnamed = stored.flatMap(({ item, fields }) =>
454
+ fields.flatMap(({ name, declaration }) =>
455
+ types.declarations.has(name)
456
+ ? [
457
+ new SpecializeError(
458
+ declaration ?? item.declaration,
459
+ `${item.name}.${name}: each field of ${item.name} becomes a PLC variable of the field's name, and the generated code already names a type ${name}. Rename the field.`,
460
+ ),
461
+ ]
462
+ : [],
463
+ ),
464
+ );
465
+ if (misnamed.length) {
466
+ throw new AggregateError(misnamed);
467
+ }
468
+ const typesFile = generated.types;
490
469
  const typeImports = (file: string) => [
491
470
  ...specializer.layouts.imports.lines(file, "import"),
492
471
  ...specializer.layouts.typeImports.lines(file, "import type"),
@@ -497,7 +476,7 @@ export const lowerElaboration = (
497
476
  typesFile,
498
477
  joined([...typeImports(typesFile), ...types.declarations.values()], "\n"),
499
478
  );
500
- for (const [item, lines] of globals) {
479
+ for (const { item, lines } of stored) {
501
480
  const file = rootModule(item);
502
481
  const imports = [...typeImports(file), ...importTypes(file)];
503
482
  sources.set(
@@ -514,11 +493,35 @@ export const lowerElaboration = (
514
493
  ...importTypes(entryFile),
515
494
  ...specializer.imports.lines(entryFile),
516
495
  ];
496
+ // An enum the generated code stores is declared before the code that reads it. What the entry
497
+ // declares for other modules only comes last, where it moves nothing the program compiled to,
498
+ // and is left out where the generated code already has the name for something of its own.
499
+ const storesEnum = (name: string) =>
500
+ specializer.layouts.imports.has(entryFile, name);
501
+ const free = ({ name }: { name: string }) =>
502
+ !storesEnum(name) &&
503
+ !specializer.named(name) &&
504
+ !types.declarations.has(name);
505
+ const declared = [
506
+ ...declarations.enums.filter(free),
507
+ ...declarations.constants.filter(free),
508
+ ];
509
+ reduction.declaredByEntry(
510
+ new Set(
511
+ [
512
+ ...declarations.enums.filter(({ name }) => storesEnum(name)),
513
+ ...declared,
514
+ ].map(({ name }) => name),
515
+ ),
516
+ );
517
517
  sources.set(
518
518
  entryFile,
519
519
  joined(
520
520
  [
521
521
  ...header.map((line) => from(main, line)),
522
+ ...declarations.enums
523
+ .filter(({ name }) => storesEnum(name))
524
+ .map(({ line }) => line),
522
525
  ...specializer.expressions.tableDeclarations,
523
526
  ...specializer.routines,
524
527
  ...scans.flatMap(({ name, declaration, body }) => [
@@ -526,6 +529,7 @@ export const lowerElaboration = (
526
529
  ...body,
527
530
  from(closingBrace(declaration), "}"),
528
531
  ]),
532
+ ...declared.map(({ line }) => line),
529
533
  ],
530
534
  "\n",
531
535
  ),
@@ -549,12 +553,17 @@ export const lowerElaboration = (
549
553
  });
550
554
  }
551
555
  }
552
- // The plain modules now live in the generated code; keep only their types for type importers.
553
- for (const source of runtime) {
554
- if (source.fileName !== entryFile && !isKept(source.fileName)) {
555
- sources.set(source.fileName, typesOnly(source, checker, sdk));
556
- }
556
+ for (const source of reduction.modules) {
557
+ sources.set(source.fileName, reduction.module(source));
558
+ reduced.set(source.fileName, { compiled: reduction.compiled(source) });
557
559
  }
560
+ reduced.set(entryFile, {
561
+ declared: new Set(
562
+ [...declarations.enums, ...declarations.constants].map(
563
+ ({ name }) => name,
564
+ ),
565
+ ),
566
+ });
558
567
  } catch (cause) {
559
568
  const causes = cause instanceof AggregateError ? cause.errors : [cause];
560
569
  diagnostics.push(
@@ -600,12 +609,13 @@ const typesModuleImports = (
600
609
  /**
601
610
  * The globals of a root's storage module: one per stored field of a record or instance, or the
602
611
  * root itself. The entry module assigns them through its namespace import of this module.
612
+ * `fields` are the fields that became globals, each of which must be able to name a variable.
603
613
  */
604
614
  const storageGlobals = (
605
615
  specializer: Specializer,
606
616
  retention: Retention,
607
617
  item: Root,
608
- ): Mapped[] => {
618
+ ): { lines: Mapped[]; fields: RootField[] } => {
609
619
  const { model, checker, layouts, storage, initializers } = specializer;
610
620
  const lines: Mapped[] = [];
611
621
  /** The SDK calls the globals' initializers are wrapped in, `retain` or `persist`. */
@@ -650,7 +660,7 @@ const storageGlobals = (
650
660
  initial: initializers.valueText(item.value, declared, layout),
651
661
  declaration: item.declaration,
652
662
  });
653
- return [...sdkImports(), ...lines];
663
+ return { lines: [...sdkImports(), ...lines], fields: [] };
654
664
  }
655
665
  const fieldInitializer = (name: string, layout: string): string => {
656
666
  if (node.captured.kind === "instance") {
@@ -662,74 +672,80 @@ const storageGlobals = (
662
672
  }
663
673
  return initializers.valueText(model.field(node, name), declared, layout);
664
674
  };
665
- for (const field of storage.rootFields(item)) {
675
+ const fields = storage.rootFields(item);
676
+ for (const field of fields) {
677
+ const origin = field.declaration ?? item.declaration;
678
+ if (!plainName(field.name)) {
679
+ throw quotedField(origin, field.name);
680
+ }
681
+ if (reservedWords.has(field.name)) {
682
+ throw new SpecializeError(
683
+ origin,
684
+ `${item.name}.${field.name}: each field of ${item.name} becomes a PLC variable of the field's name, and "${field.name}" is a word TypeScript reserves, so no variable can have it. Rename the field.`,
685
+ );
686
+ }
666
687
  global({
667
688
  ...field,
668
689
  initial: fieldInitializer(field.name, field.layout),
669
690
  });
670
691
  }
671
- return [...sdkImports(), ...lines];
692
+ return { lines: [...sdkImports(), ...lines], fields };
672
693
  };
673
694
 
674
695
  /**
675
- * A plain module reduced to the types other modules may import from it, and the service client it
676
- * creates, which scan code calls through this module as it does through a module of constants.
696
+ * The words no variable of a module can be named, exactly: every other word TypeScript knows,
697
+ * such as `out`, `type` and `of`, names a variable as any name does.
677
698
  */
678
- const typesOnly = (
679
- source: ts.SourceFile,
680
- checker: ts.TypeChecker,
681
- sdk: string,
682
- ): Mapped => {
683
- const clients = serviceClients(source, checker, sdk);
684
- return joined(
685
- [
686
- ...source.statements
687
- .filter(
688
- (statement) =>
689
- ts.isInterfaceDeclaration(statement) ||
690
- ts.isTypeAliasDeclaration(statement) ||
691
- (ts.isImportDeclaration(statement) &&
692
- (statement.importClause?.isTypeOnly ||
693
- (clients.length > 0 && importsSdk(statement)))) ||
694
- clients.includes(statement),
695
- )
696
- .map(copied),
697
- "export {};",
698
- ],
699
- "\n",
700
- );
701
- };
702
-
703
- /** A module's statements that create the service client. */
704
- const serviceClients = (
705
- source: ts.SourceFile,
706
- checker: ts.TypeChecker,
707
- sdk: string,
708
- ): ts.Statement[] =>
709
- source.statements.filter(
710
- (statement) =>
711
- ts.isVariableStatement(statement) &&
712
- statement.declarationList.declarations.every(
713
- (declaration) =>
714
- declaration.initializer &&
715
- ts.isCallExpression(declaration.initializer) &&
716
- namesSdk(
717
- checker,
718
- sdk,
719
- declaration.initializer.expression,
720
- "createServiceClient",
721
- ),
722
- ),
723
- );
724
-
725
- /** Whether an import names one of the SDK's modules, which every module can import. */
726
- const importsSdk = (statement: ts.ImportDeclaration): boolean => {
727
- const specifier = statement.moduleSpecifier;
728
- return (
729
- ts.isStringLiteral(specifier) &&
730
- Object.values(sdkModules).some((module) => module === specifier.text)
731
- );
732
- };
699
+ const reservedWords: ReadonlySet<string> = new Set([
700
+ "arguments",
701
+ "await",
702
+ "break",
703
+ "case",
704
+ "catch",
705
+ "class",
706
+ "const",
707
+ "continue",
708
+ "debugger",
709
+ "default",
710
+ "delete",
711
+ "do",
712
+ "else",
713
+ "enum",
714
+ "eval",
715
+ "export",
716
+ "extends",
717
+ "false",
718
+ "finally",
719
+ "for",
720
+ "function",
721
+ "if",
722
+ "implements",
723
+ "import",
724
+ "in",
725
+ "instanceof",
726
+ "interface",
727
+ "let",
728
+ "new",
729
+ "null",
730
+ "package",
731
+ "private",
732
+ "protected",
733
+ "public",
734
+ "return",
735
+ "static",
736
+ "super",
737
+ "switch",
738
+ "this",
739
+ "throw",
740
+ "true",
741
+ "try",
742
+ "typeof",
743
+ "var",
744
+ "void",
745
+ "while",
746
+ "with",
747
+ "yield",
748
+ ]);
733
749
 
734
750
  /** An elaboration failure as a diagnostic, at the node specialization stopped at when it knows one. */
735
751
  const failure = (
@@ -778,23 +794,22 @@ const findEntry = (
778
794
  };
779
795
 
780
796
  /**
781
- * Each root's storage module. Roots in different modules can share a name, up to case, and would
782
- * then share one module and its list; each of them is qualified by its own module instead. The
783
- * config's `io` names a root by its binding name, which then names none of them, so that is refused.
797
+ * The generated modules: each root's storage module, and the module of generated types. A root's
798
+ * module has the root's name, which io and the HMI reach its storage by, so the types module is
799
+ * the one that gives way to a root named like it.
800
+ *
801
+ * Roots in different modules can share a name, up to case, and would then share one module and its
802
+ * list; each of them is qualified by its own module instead. The config's `io` names a root by its
803
+ * binding name, which then names none of them, so that is refused.
784
804
  */
785
- const rootModules = (
805
+ const generatedModules = (
786
806
  roots: readonly Root[],
787
807
  {
788
808
  directory,
789
809
  root: projectRoot,
790
810
  bound,
791
811
  }: { directory: string; root: string; bound: ReadonlySet<string> },
792
- ): ((item: Root) => string) => {
793
- const counts = new Map<string, number>();
794
- for (const item of roots) {
795
- const key = item.name.toLowerCase();
796
- counts.set(key, (counts.get(key) ?? 0) + 1);
797
- }
812
+ ): { root: (item: Root) => string; types: string } => {
798
813
  const shareName = (item: Root) =>
799
814
  roots.filter(
800
815
  (other) => other.name.toLowerCase() === item.name.toLowerCase(),
@@ -815,11 +830,22 @@ const rootModules = (
815
830
  }),
816
831
  );
817
832
  }
818
- return (item) => {
819
- const shared = (counts.get(item.name.toLowerCase()) ?? 0) > 1;
820
- const name = shared
821
- ? `${item.name}_${identityDigest(modulePath(projectRoot, item.file))}`
822
- : item.name;
823
- return `${directory}/${name}.ts`;
833
+ const qualified = (item: Root): string => {
834
+ const module = modulePath(projectRoot, item.file);
835
+ const sharing = shareName(item);
836
+ if (sharing.length === 1) {
837
+ return item.name;
838
+ }
839
+ // Two roots of one module differ only in their capitals, which a file's name can't tell apart.
840
+ // The last of them keeps the name the module alone gives, as it always had; the others add their own.
841
+ const twins = sharing.filter((other) => other.file === item.file);
842
+ return twins.at(-1) === item
843
+ ? `${item.name}_${identityDigest(module)}`
844
+ : `${item.name}_${identityDigest(`${module}\0${item.name}`)}`;
845
+ };
846
+ const taken = new Set(roots.map((item) => qualified(item).toLowerCase()));
847
+ return {
848
+ root: (item) => `${directory}/${qualified(item)}.ts`,
849
+ types: `${directory}/${unusedName("types", (name) => taken.has(name))}.ts`,
824
850
  };
825
851
  };
@@ -10,6 +10,7 @@ import {
10
10
  import type { CapturedValue } from "./capture-protocol";
11
11
  import { ModuleImports } from "./imports";
12
12
  import { isExported, type Model, type ModelNode, unionMembers } from "./model";
13
+ import { type Names, rootFieldNames } from "./names";
13
14
  import { SpecializeError } from "./values";
14
15
 
15
16
  /** IEC names a program can write as types; they keep their width rather than becoming DINT. */
@@ -95,10 +96,10 @@ export class Layouts {
95
96
  * may import beside the generated ones, and the namespaces storage modules are imported as.
96
97
  */
97
98
  private readonly takenNames: Set<string>;
98
- /** Enums the declarations need from kept modules. */
99
- readonly imports = new ModuleImports();
99
+ /** Enums the declarations need from the program's modules. */
100
+ readonly imports: ModuleImports;
100
101
  /** Types the declarations need from kept modules. */
101
- readonly typeImports = new ModuleImports();
102
+ readonly typeImports: ModuleImports;
102
103
  private readonly enums = new Map<string, LiteralEnum>();
103
104
  private readonly records = new Map<string, string>();
104
105
  private readonly names = new Map<string, number>();
@@ -120,7 +121,16 @@ export class Layouts {
120
121
  keptSources: readonly ts.SourceFile[],
121
122
  /** The stored layout of a class instance or an array of them, which storage, built on these layouts, gives. */
122
123
  private readonly instanceState: (node: ModelNode) => string | undefined,
124
+ private readonly moduleNames: Names,
125
+ /** Why the generated modules can't import an enum from the module that declares it; undefined when they can. */
126
+ private readonly enumRefusal: (
127
+ declaration: ts.EnumDeclaration,
128
+ ) => string | undefined,
123
129
  ) {
130
+ // Each is imported into every root's storage module, beside that root's fields.
131
+ const fields = rootFieldNames(model);
132
+ this.imports = new ModuleImports(moduleNames, fields);
133
+ this.typeImports = new ModuleImports(moduleNames, fields);
124
134
  // Storage imports a root's module under its capitalized name, unless the program names a type so.
125
135
  const typeNames = new Set(
126
136
  model.program
@@ -174,9 +184,15 @@ export class Layouts {
174
184
  const count = this.names.get(base) ?? 0;
175
185
  this.names.set(base, count + 1);
176
186
  const name = count ? `${base}_${count + 1}` : base;
177
- return this.declarations.has(name) || this.takenNames.has(name)
178
- ? this.unique(base)
179
- : name;
187
+ if (
188
+ this.declarations.has(name) ||
189
+ this.takenNames.has(name) ||
190
+ this.moduleNames.importedAs(name)
191
+ ) {
192
+ return this.unique(base);
193
+ }
194
+ this.moduleNames.declare(name);
195
+ return name;
180
196
  }
181
197
 
182
198
  /**
@@ -627,14 +643,19 @@ export class Layouts {
627
643
  return this.typeImports.add(file, symbol.name);
628
644
  }
629
645
 
646
+ /**
647
+ * The name generated code reads a TypeScript enum by: its own, imported from the module that
648
+ * declares it, so the PLC, the server and the program's own modules share one enum.
649
+ */
630
650
  private enumName(declaration: ts.EnumDeclaration): string {
631
- const file = declaration.getSourceFile().fileName;
632
- if (!this.kept(file)) {
633
- throw new Error(
634
- `${declaration.name.text}: declare PLC enums in a module of enums and constants, so the server and PLC share them.`,
635
- );
651
+ const refusal = this.enumRefusal(declaration);
652
+ if (refusal) {
653
+ throw new SpecializeError(declaration.name, refusal);
636
654
  }
637
- return this.imports.add(file, declaration.name.text);
655
+ return this.imports.add(
656
+ declaration.getSourceFile().fileName,
657
+ declaration.name.text,
658
+ );
638
659
  }
639
660
 
640
661
  /** `Record<Enum, T>`: an object type whose properties are exactly an enum's members. */
@@ -793,10 +814,12 @@ export class Layouts {
793
814
  ): string {
794
815
  return this.checker
795
816
  .getPropertiesOfType(type)
796
- .map(
797
- (property) =>
798
- `${property.name}: ${this.declaredText(property.valueDeclaration, this.checker.getTypeOfSymbol(property), captured(property.name) ?? this.fieldSample(property), pascalCase(property.name))};`,
799
- )
817
+ .map((property) => {
818
+ if (!plainName(property.name)) {
819
+ throw quotedField(property.valueDeclaration, property.name);
820
+ }
821
+ return `${property.name}: ${this.declaredText(property.valueDeclaration, this.checker.getTypeOfSymbol(property), captured(property.name) ?? this.fieldSample(property), pascalCase(property.name))};`;
822
+ })
800
823
  .join(" ");
801
824
  }
802
825
  }
@@ -958,20 +981,24 @@ const isReadonlyArray = (type: ts.Type): boolean =>
958
981
  const enumKey = (members: readonly string[]): string =>
959
982
  [...members].sort().join("|");
960
983
 
961
- /** `base`, or else the first of `base_2`, `base_3`… that `taken` does not hold. */
962
- export const unusedName = (
963
- base: string,
964
- taken: (name: string) => boolean,
965
- ): string => {
966
- if (!taken(base)) {
967
- return base;
968
- }
969
- for (let index = 2; ; index++) {
970
- const name = `${base}_${index}`;
971
- if (!taken(name)) {
972
- return name;
973
- }
974
- }
984
+ /** Whether a field's name is one a PLC variable or record field can have: a plain name, or a table's number. */
985
+ export const plainName = (name: string): boolean =>
986
+ /^(\d+|[\p{ID_Start}_$][\p{ID_Continue}$]*)$/u.test(name);
987
+
988
+ /** The refusal of a field whose name had to be quoted, at the field. */
989
+ export const quotedField = (
990
+ declaration: ts.Node | undefined,
991
+ name: string,
992
+ ): Error => {
993
+ const plain = name
994
+ .replace(/[^A-Za-z0-9_$]+(.)?/g, (_, next: string | undefined) =>
995
+ next ? next.toUpperCase() : "",
996
+ )
997
+ .replace(/^\d/, "_$&");
998
+ const message = `"${name}" can't name a field the PLC stores, which needs a plain name such as ${plain || "field"}. Rename the field.`;
999
+ return declaration
1000
+ ? new SpecializeError(declaration, message)
1001
+ : new Error(message);
975
1002
  };
976
1003
 
977
1004
  /** A string literal as an enum member name. */