@tsplc/compiler 0.2.14 → 0.2.17

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.
Files changed (54) hide show
  1. package/backends/codesys/debug.ts +509 -0
  2. package/backends/codesys/emit.ts +701 -9
  3. package/backends/codesys/http.ts +110 -34
  4. package/backends/codesys/index.ts +2 -1
  5. package/backends/codesys/io-paths.ts +3 -1
  6. package/backends/codesys/manifest.ts +312 -0
  7. package/backends/codesys/plan.ts +39 -9
  8. package/backends/codesys/publication.ts +2 -2
  9. package/backends/codesys/storage.ts +10 -3
  10. package/backends/codesys/task-access.ts +51 -1
  11. package/backends/codesys/telemetry.ts +593 -0
  12. package/backends/codesys/types.ts +2 -1
  13. package/dist/cli.js +190 -33
  14. package/dist/cli.js.map +6 -6
  15. package/dist/codesys.js +2148 -432
  16. package/dist/codesys.js.map +14 -11
  17. package/dist/elaborate-capture.js +7 -1
  18. package/dist/elaborate-capture.js.map +3 -3
  19. package/dist/index.js +877 -459
  20. package/dist/index.js.map +16 -15
  21. package/dist/ir.js +87 -23
  22. package/dist/ir.js.map +10 -9
  23. package/dist/project.js +42 -9
  24. package/dist/project.js.map +3 -3
  25. package/dist/telemetry.js +83 -0
  26. package/dist/telemetry.js.map +12 -0
  27. package/ir/core-model.ts +13 -0
  28. package/ir/core.ts +1 -0
  29. package/ir/errors.ts +20 -0
  30. package/ir/index.ts +1 -0
  31. package/ir/link.ts +17 -8
  32. package/ir/model.ts +39 -0
  33. package/ir/routine.ts +62 -29
  34. package/ir/types.ts +7 -1
  35. package/package.json +12 -6
  36. package/project/cli.ts +96 -6
  37. package/project/plant.ts +58 -9
  38. package/project/project.ts +56 -10
  39. package/src/frontend/async.ts +284 -195
  40. package/src/frontend/configuration.ts +7 -21
  41. package/src/frontend/const-functions.ts +44 -38
  42. package/src/frontend/elaborate/capture.ts +7 -0
  43. package/src/frontend/elaborate/index.ts +135 -61
  44. package/src/frontend/elaborate/layouts.ts +8 -0
  45. package/src/frontend/elaborate/model.ts +13 -0
  46. package/src/frontend/elaborate/specialize.ts +302 -111
  47. package/src/frontend/exposure.ts +28 -26
  48. package/src/frontend/positions.ts +272 -0
  49. package/src/frontend/promises.ts +52 -47
  50. package/src/frontend/services.ts +16 -26
  51. package/src/frontend/types.ts +14 -0
  52. package/src/frontend/typescript.ts +185 -65
  53. package/stdlib/telemetry.ts +72 -0
  54. package/types/telemetry.d.ts +44 -0
@@ -1,7 +1,8 @@
1
1
  import ts from "typescript";
2
+ import { copied, from, joined, mapped, type Mapped, type Part } from "../positions.ts";
2
3
  import { Layouts, type LiteralEnum } from "./layouts.ts";
3
4
  import type { CapturedValue } from "./graph.ts";
4
- import type { Model, ModelNode, Root, Step } from "./model.ts";
5
+ import { tsPath, type Model, type ModelNode, type Owner, type Root, type Step } from "./model.ts";
5
6
 
6
7
  type FunctionLike =
7
8
  | ts.FunctionDeclaration
@@ -23,7 +24,7 @@ export type Value =
23
24
  /** Code the PLC runs. `declared` is the storage's declared type, before narrowing. */
24
25
  | {
25
26
  kind: "code";
26
- text: string;
27
+ text: string | Mapped;
27
28
  declared?: ts.Type;
28
29
  place?: boolean;
29
30
  iec?: string;
@@ -53,19 +54,22 @@ export class SpecializeError extends Error {
53
54
 
54
55
  /** Indented lines of one generated routine, with the local names it has used. */
55
56
  class Emitter {
56
- readonly lines: string[] = [];
57
+ readonly lines: Mapped[] = [];
57
58
  private depth = 1;
58
59
  private readonly used = new Set<string>();
59
60
  private temporaries = 0;
60
61
 
61
- line(text: string): void {
62
- this.lines.push(`${" ".repeat(this.depth)}${text}`);
62
+ /** @param origin The source the next lines come from: the statement being specialized. */
63
+ constructor(public origin: ts.Node) {}
64
+
65
+ line(text: Part): void {
66
+ this.lines.push(from(this.origin, mapped`${" ".repeat(this.depth)}${text}`));
63
67
  }
64
- open(text: string): void {
68
+ open(text: Part): void {
65
69
  this.line(text);
66
70
  this.depth++;
67
71
  }
68
- close(text = "}"): void {
72
+ close(text: Part = "}"): void {
69
73
  this.depth--;
70
74
  this.line(text);
71
75
  }
@@ -96,7 +100,10 @@ interface Frame {
96
100
  */
97
101
  export class Specializer {
98
102
  readonly layouts: Layouts;
99
- readonly routines: string[] = [];
103
+ private readonly readConstants = new Set<string>();
104
+ readonly routines: Mapped[] = [];
105
+ /** Routines specialized from a class method, by routine name: `Class.method` and the TypeScript path of `this`. */
106
+ readonly origins = new Map<string, { name: string; instance?: string }>();
100
107
  /** Modules generated code reads through a namespace import, by import name. */
101
108
  readonly namespaces = new Map<string, string>();
102
109
  /** Value imports from kept modules, by file. */
@@ -229,15 +236,18 @@ export class Specializer {
229
236
  const namespace = this.namespace(owner.root);
230
237
  let text = this.flattened(owner.root) ? namespace : `${namespace}.${owner.root.name}`;
231
238
  owner.steps.forEach((step, index) => {
232
- const holder = this.at(owner.root, owner.steps.slice(0, index));
233
- if (step.kind === "index") text += `[${step.index}]`;
234
- else if (/^\d+$/.test(step.name) && holder?.type)
235
- text += `[${this.keyText(holder.type, step.name)}]`;
236
- else text += `.${step.name}`;
239
+ text += this.placeStep(this.at(owner.root, owner.steps.slice(0, index)), step);
237
240
  });
238
241
  return text;
239
242
  }
240
243
 
244
+ /** Dialect text for one step down from `holder`: a `Record<Enum, T>` key indexes by its enum member. */
245
+ private placeStep(holder: ModelNode | undefined, step: Step): string {
246
+ if (step.kind === "index") return `[${step.index}]`;
247
+ if (/^\d+$/.test(step.name) && holder?.type) return `[${this.keyText(holder.type, step.name)}]`;
248
+ return `.${step.name}`;
249
+ }
250
+
241
251
  /** The enum member naming a key of a `Record<Enum, T>`. */
242
252
  private keyText(type: ts.Type, key: string): string {
243
253
  const keyType = type.aliasSymbol?.name === "Record" ? type.aliasTypeArguments?.[0] : undefined;
@@ -552,9 +562,9 @@ export class Specializer {
552
562
  // ---- Routines ----
553
563
 
554
564
  /** Specializes the entry function, returning its body. */
555
- entry(declaration: ts.FunctionDeclaration | ts.ArrowFunction): string[] {
565
+ entry(declaration: ts.FunctionDeclaration | ts.ArrowFunction): Mapped[] {
556
566
  const frame: Frame = {
557
- emitter: new Emitter(),
567
+ emitter: new Emitter(declaration),
558
568
  env: new Map(),
559
569
  returns: undefined,
560
570
  async: false,
@@ -571,7 +581,7 @@ export class Specializer {
571
581
  closure?: Env,
572
582
  ): {
573
583
  name: string;
574
- args: string[];
584
+ args: (string | Mapped)[];
575
585
  returns: ts.Type | undefined;
576
586
  } {
577
587
  const signature = this.checker.getSignatureFromDeclaration(declaration);
@@ -583,14 +593,14 @@ export class Specializer {
583
593
  ?.some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword),
584
594
  );
585
595
  const frame: Frame = {
586
- emitter: new Emitter(),
596
+ emitter: new Emitter(declaration),
587
597
  env: new Map(closure),
588
598
  self,
589
599
  returns: returnType && (isAsync ? this.checker.getAwaitedType(returnType) : returnType),
590
600
  async: isAsync,
591
601
  };
592
602
  const parameters: string[] = [];
593
- const runtimeArgs: string[] = [];
603
+ const runtimeArgs: (string | Mapped)[] = [];
594
604
  const keys: string[] = [];
595
605
  const parameterList = ts.isGetAccessorDeclaration(declaration) ? [] : declaration.parameters;
596
606
  parameterList.forEach((parameter, index) => {
@@ -614,8 +624,9 @@ export class Specializer {
614
624
  const name = this.routineName(declaration, self);
615
625
  this.specialized.set(key, name);
616
626
  if (ts.isArrowFunction(declaration) && !ts.isBlock(declaration.body)) {
627
+ frame.emitter.origin = declaration.body;
617
628
  const result = this.expression(declaration.body, frame, frame.returns);
618
- frame.emitter.line(`return ${this.code(result, frame.returns, frame)};`);
629
+ frame.emitter.line(mapped`return ${this.code(result, frame.returns, frame)};`);
619
630
  } else this.body(declaration.body!, frame);
620
631
  const resultText =
621
632
  frame.returns && !(frame.returns.flags & ts.TypeFlags.Void)
@@ -624,10 +635,25 @@ export class Specializer {
624
635
  const head = `${frame.async ? "async " : ""}function ${name}(${parameters.join(", ")}): ${
625
636
  frame.async ? `Promise<${resultText}>` : resultText
626
637
  } {`;
627
- const where = self?.owner
628
- ? ` /* ${self.owner.root.name}${self.owner.steps.map(stepText).join("")} */`
629
- : "";
630
- this.routines.push([`${head}${where}`, ...frame.emitter.lines, "}"].join("\n"));
638
+ const instance = self?.owner && tsPath(self.owner);
639
+ if (
640
+ self?.captured.kind === "instance" &&
641
+ (ts.isMethodDeclaration(declaration) || ts.isGetAccessorDeclaration(declaration))
642
+ )
643
+ this.origins.set(name, {
644
+ name: `${self.captured.name}.${declaration.name.getText()}`,
645
+ ...(instance && { instance }),
646
+ });
647
+ this.routines.push(
648
+ joined(
649
+ [
650
+ from(declaration, `${head}${instance ? ` /* ${instance} */` : ""}`),
651
+ ...frame.emitter.lines,
652
+ from(closingBrace(declaration), "}"),
653
+ ],
654
+ "\n",
655
+ ),
656
+ );
631
657
  return { name, args: runtimeArgs, returns: frame.returns };
632
658
  }
633
659
 
@@ -655,7 +681,7 @@ export class Specializer {
655
681
  declared: ts.Type,
656
682
  frame: Frame,
657
683
  parameters: string[],
658
- runtimeArgs: string[],
684
+ runtimeArgs: (string | Mapped)[],
659
685
  keys: string[],
660
686
  ): void {
661
687
  if (ts.isObjectBindingPattern(name)) {
@@ -718,10 +744,20 @@ export class Specializer {
718
744
 
719
745
  private body(node: ts.ConciseBody, frame: Frame): void {
720
746
  if (ts.isBlock(node)) for (const statement of node.statements) this.statement(statement, frame);
721
- else frame.emitter.line(`${this.code(this.expression(node, frame), undefined, frame)};`);
747
+ else {
748
+ frame.emitter.origin = node;
749
+ frame.emitter.line(mapped`${this.code(this.expression(node, frame), undefined, frame)};`);
750
+ }
722
751
  }
723
752
 
724
753
  private statement(node: ts.Statement, frame: Frame): void {
754
+ const enclosing = frame.emitter.origin;
755
+ frame.emitter.origin = node;
756
+ this.specializeStatement(node, frame);
757
+ frame.emitter.origin = enclosing;
758
+ }
759
+
760
+ private specializeStatement(node: ts.Statement, frame: Frame): void {
725
761
  const { emitter } = frame;
726
762
  if (ts.isBlock(node)) {
727
763
  emitter.open("{");
@@ -751,7 +787,7 @@ export class Specializer {
751
787
  else if (node.elseStatement) this.statement(node.elseStatement, frame);
752
788
  return;
753
789
  }
754
- emitter.open(`if (${this.condition(condition, node.expression, frame)}) {`);
790
+ emitter.open(mapped`if (${this.condition(condition, node.expression, frame)}) {`);
755
791
  this.inner(node.thenStatement, frame);
756
792
  if (node.elseStatement) {
757
793
  emitter.close("} else {");
@@ -772,7 +808,7 @@ export class Specializer {
772
808
  return;
773
809
  }
774
810
  const value = this.expression(node.expression, frame, frame.returns);
775
- emitter.line(`return ${this.code(value, frame.returns, frame)};`);
811
+ emitter.line(mapped`return ${this.code(value, frame.returns, frame)};`);
776
812
  return;
777
813
  }
778
814
  if (ts.isForOfStatement(node)) {
@@ -797,18 +833,25 @@ export class Specializer {
797
833
  emitter.open("try {");
798
834
  for (const statement of node.tryBlock.statements) this.statement(statement, frame);
799
835
  if (node.catchClause) {
800
- emitter.close(
801
- `} catch${node.catchClause.variableDeclaration ? ` (${node.catchClause.variableDeclaration.name.getText()})` : ""} {`,
802
- );
836
+ const binding = node.catchClause.variableDeclaration?.name;
837
+ emitter.close(`} catch${binding ? ` (${binding.getText()})` : ""} {`);
803
838
  emitter.open("");
804
839
  emitter.lines.pop();
840
+ // The binding holds the error code, which a catch block can only pass on as it is.
841
+ if (binding && ts.isIdentifier(binding))
842
+ frame.env.set(this.checker.getSymbolAtLocation(binding)!, {
843
+ kind: "code",
844
+ text: binding.text,
845
+ declared: this.checker.getTypeAtLocation(binding),
846
+ place: true,
847
+ });
805
848
  for (const statement of node.catchClause.block.statements) this.statement(statement, frame);
806
849
  }
807
850
  emitter.close();
808
851
  return;
809
852
  }
810
853
  if (ts.isBreakStatement(node) || ts.isContinueStatement(node)) {
811
- emitter.line(node.getText());
854
+ emitter.line(copied(node));
812
855
  return;
813
856
  }
814
857
  if (ts.isEmptyStatement(node)) return;
@@ -903,7 +946,7 @@ export class Specializer {
903
946
  const local = frame.emitter.local(name.text);
904
947
  const type = value.kind === "code" && value.iec ? value.iec : this.localType(declared);
905
948
  frame.emitter.line(
906
- `${mutable ? "let" : "const"} ${local}: ${type} = ${this.code(value, declared, frame)};`,
949
+ mapped`${mutable ? "let" : "const"} ${local}: ${type} = ${this.code(value, declared, frame)};`,
907
950
  );
908
951
  frame.env.set(symbol, {
909
952
  kind: "code",
@@ -959,7 +1002,7 @@ export class Specializer {
959
1002
  if (!ts.isIdentifier(name))
960
1003
  throw new SpecializeError(name, "Destructure a runtime element inside the loop.");
961
1004
  const local = frame.emitter.local(name.text);
962
- frame.emitter.open(`for (const ${local} of ${iterable.text}) {`);
1005
+ frame.emitter.open(mapped`for (const ${local} of ${iterable.text}) {`);
963
1006
  frame.env.set(this.checker.getSymbolAtLocation(name)!, {
964
1007
  kind: "code",
965
1008
  text: local,
@@ -971,7 +1014,7 @@ export class Specializer {
971
1014
  }
972
1015
 
973
1016
  /** `for (const [index, item] of array.entries())` over a runtime array stays a loop, as the backend lowers it. */
974
- private forEntries(node: ts.ForOfStatement, array: string, frame: Frame): void {
1017
+ private forEntries(node: ts.ForOfStatement, array: string | Mapped, frame: Frame): void {
975
1018
  const declaration = node.initializer;
976
1019
  const binding =
977
1020
  ts.isVariableDeclarationList(declaration) && declaration.declarations.length === 1
@@ -1001,7 +1044,7 @@ export class Specializer {
1001
1044
  });
1002
1045
  return local;
1003
1046
  });
1004
- frame.emitter.open(`for (const [${index}, ${item}] of ${array}.entries()) {`);
1047
+ frame.emitter.open(mapped`for (const [${[index, item].join(", ")}] of ${array}.entries()) {`);
1005
1048
  this.inner(node.statement, frame);
1006
1049
  frame.emitter.close();
1007
1050
  }
@@ -1041,19 +1084,19 @@ export class Specializer {
1041
1084
  place: true,
1042
1085
  iec,
1043
1086
  });
1044
- const test = `${this.code(this.expression(condition.left, frame), declared, frame)} ${condition.operatorToken.getText()} ${this.code(this.expression(condition.right, frame), declared, frame)}`;
1045
- let step: string;
1087
+ const test = mapped`${this.code(this.expression(condition.left, frame), declared, frame)} ${condition.operatorToken.getText()} ${this.code(this.expression(condition.right, frame), declared, frame)}`;
1088
+ let step: Part;
1046
1089
  if (ts.isPrefixUnaryExpression(incrementor) || ts.isPostfixUnaryExpression(incrementor))
1047
1090
  step = `${local}${ts.tokenToString(incrementor.operator)}`;
1048
1091
  else if (ts.isBinaryExpression(incrementor))
1049
- step = `${local} ${incrementor.operatorToken.getText()} ${this.code(this.expression(incrementor.right, frame), declared, frame)}`;
1092
+ step = mapped`${local} ${incrementor.operatorToken.getText()} ${this.code(this.expression(incrementor.right, frame), declared, frame)}`;
1050
1093
  else
1051
1094
  throw new SpecializeError(
1052
1095
  incrementor,
1053
1096
  "Use i++, i--, i += step or i -= step in the for header.",
1054
1097
  );
1055
1098
  frame.emitter.open(
1056
- `for (let ${local}: ${iec ?? this.localType(declared)} = ${start}; ${test}; ${step}) {`,
1099
+ mapped`for (let ${local}: ${iec ?? this.localType(declared)} = ${start}; ${test}; ${step}) {`,
1057
1100
  );
1058
1101
  this.inner(node.statement, frame);
1059
1102
  frame.emitter.close();
@@ -1096,7 +1139,7 @@ export class Specializer {
1096
1139
  }
1097
1140
  return;
1098
1141
  }
1099
- frame.emitter.open(`switch (${this.code(subject, declared, frame)}) {`);
1142
+ frame.emitter.open(mapped`switch (${this.code(subject, declared, frame)}) {`);
1100
1143
  for (const clause of node.caseBlock.clauses) {
1101
1144
  if (ts.isDefaultClause(clause)) {
1102
1145
  const unreachable = clause.statements.some(
@@ -1118,7 +1161,7 @@ export class Specializer {
1118
1161
  continue;
1119
1162
  }
1120
1163
  const label = this.expression(clause.expression, frame, declared);
1121
- frame.emitter.open(`case ${this.code(label, declared, frame)}: {`);
1164
+ frame.emitter.open(mapped`case ${this.code(label, declared, frame)}: {`);
1122
1165
  for (const statement of clause.statements) this.statement(statement, frame);
1123
1166
  frame.emitter.close();
1124
1167
  }
@@ -1129,7 +1172,7 @@ export class Specializer {
1129
1172
  private effect(node: ts.Expression, frame: Frame): void {
1130
1173
  if (ts.isVoidExpression(node)) {
1131
1174
  const value = this.expression(node.expression, frame);
1132
- if (value.kind === "code") frame.emitter.line(`void ${value.text};`);
1175
+ if (value.kind === "code") frame.emitter.line(mapped`void ${value.text};`);
1133
1176
  return;
1134
1177
  }
1135
1178
  if (ts.isBinaryExpression(node) && isAssignment(node.operatorToken.kind)) {
@@ -1146,13 +1189,14 @@ export class Specializer {
1146
1189
  frame.emitter.line(
1147
1190
  this.store(
1148
1191
  target,
1149
- `${text} ${node.operator === ts.SyntaxKind.PlusPlusToken ? "+" : "-"} 1`,
1192
+ mapped`${text} ${node.operator === ts.SyntaxKind.PlusPlusToken ? "+" : "-"} 1`,
1150
1193
  ),
1151
1194
  );
1152
1195
  return;
1153
1196
  }
1154
1197
  const value = this.expression(node, frame);
1155
- if (value.kind === "code" && value.text.includes("(")) frame.emitter.line(`${value.text};`);
1198
+ if (value.kind === "code" && String(value.text).includes("("))
1199
+ frame.emitter.line(mapped`${value.text};`);
1156
1200
  }
1157
1201
 
1158
1202
  private assign(node: ts.BinaryExpression, frame: Frame): void {
@@ -1166,7 +1210,7 @@ export class Specializer {
1166
1210
  frame,
1167
1211
  declared && this.checker.getNonNullableType(declared),
1168
1212
  );
1169
- frame.emitter.open(`if (${this.isUndefinedText(text, declared)}) {`);
1213
+ frame.emitter.open(mapped`if (${this.isUndefinedText(text, declared)}) {`);
1170
1214
  frame.emitter.line(
1171
1215
  this.store(
1172
1216
  target,
@@ -1198,14 +1242,14 @@ export class Specializer {
1198
1242
  if (!binary)
1199
1243
  throw new SpecializeError(node, `${node.operatorToken.getText()} is not supported.`);
1200
1244
  frame.emitter.line(
1201
- this.store(target, `${text} ${binary} ${this.code(value, declared, frame)}`),
1245
+ this.store(target, mapped`${text} ${binary} ${this.code(value, declared, frame)}`),
1202
1246
  );
1203
1247
  }
1204
1248
 
1205
1249
  /** A statement storing `text` into a place, through its module's setter when it has one. */
1206
- private store(target: Value, text: string): string {
1250
+ private store(target: Value, text: Part): Mapped {
1207
1251
  if (target.kind !== "code") throw new Error("Not a place.");
1208
- return target.setter ? `${target.setter}(${text});` : `${target.text} = ${text};`;
1252
+ return target.setter ? mapped`${target.setter}(${text});` : mapped`${target.text} = ${text};`;
1209
1253
  }
1210
1254
 
1211
1255
  /** The text stored into a place of `declared` type, wrapping an optional's value. */
@@ -1214,12 +1258,12 @@ export class Specializer {
1214
1258
  declared: ts.Type | undefined,
1215
1259
  frame: Frame,
1216
1260
  iec?: string,
1217
- ): string {
1261
+ ): string | Mapped {
1218
1262
  const target = iec ?? (declared && declared.flags & ts.TypeFlags.Number ? "DINT" : undefined);
1219
1263
  if (target && value.kind === "code" && needsConversion(value.iec ?? "DINT", target)) {
1220
1264
  // A TypeScript number holds any of these; in the PLC a value converts as an IEC assignment does.
1221
1265
  this.typeImports.add("wrap");
1222
- return `wrap<${target}>(${this.code(value, undefined, frame)})`;
1266
+ return mapped`wrap<${target}>(${this.code(value, undefined, frame)})`;
1223
1267
  }
1224
1268
  if (declared && this.isOptionalRecord(declared)) {
1225
1269
  if (value.kind === "const" && value.value === undefined)
@@ -1234,18 +1278,20 @@ export class Specializer {
1234
1278
  return this.code(value, declared, frame);
1235
1279
  }
1236
1280
 
1237
- private wrapDefined(text: string, declared: ts.Type | undefined): string {
1238
- return declared && this.isOptionalRecord(declared) ? `{ has: true, value: ${text} }` : text;
1281
+ private wrapDefined(text: string | Mapped, declared: ts.Type | undefined): string | Mapped {
1282
+ return declared && this.isOptionalRecord(declared)
1283
+ ? mapped`{ has: true, value: ${text} }`
1284
+ : text;
1239
1285
  }
1240
1286
 
1241
- private isUndefinedText(text: string, declared: ts.Type | undefined): string {
1242
- if (declared && this.isOptionalRecord(declared)) return `!${text}.has`;
1287
+ private isUndefinedText(text: string | Mapped, declared: ts.Type | undefined): Mapped {
1288
+ if (declared && this.isOptionalRecord(declared)) return mapped`!${text}.has`;
1243
1289
  const literal = declared && this.layouts.literalEnum(declared);
1244
- if (literal) return `${text} === ${this.layouts.member(literal, undefined)}`;
1290
+ if (literal) return mapped`${text} === ${this.layouts.member(literal, undefined)}`;
1245
1291
  throw new Error("Only optional values can be undefined.");
1246
1292
  }
1247
1293
 
1248
- private placeText(value: Value, node: ts.Node): string {
1294
+ private placeText(value: Value, node: ts.Node): string | Mapped {
1249
1295
  if (value.kind === "code" && value.place) return value.text;
1250
1296
  throw new SpecializeError(node, "Assign to stored state: a field scan code owns, or a let.");
1251
1297
  }
@@ -1253,6 +1299,13 @@ export class Specializer {
1253
1299
  // ---- Expressions ----
1254
1300
 
1255
1301
  expression(node: ts.Expression, frame: Frame, expected?: ts.Type): Value {
1302
+ const value = this.evaluate(node, frame, expected);
1303
+ if (value.kind !== "code") return value;
1304
+ // A name maps to where it is read, not to where its value came from.
1305
+ return { ...value, text: from(node, ts.isIdentifier(node) ? String(value.text) : value.text) };
1306
+ }
1307
+
1308
+ private evaluate(node: ts.Expression, frame: Frame, expected?: ts.Type): Value {
1256
1309
  if (
1257
1310
  ts.isParenthesizedExpression(node) ||
1258
1311
  ts.isNonNullExpression(node) ||
@@ -1272,6 +1325,9 @@ export class Specializer {
1272
1325
  }
1273
1326
  if (ts.isIdentifier(node)) return this.identifier(node, frame);
1274
1327
  if (ts.isPropertyAccessExpression(node)) {
1328
+ const member = this.checker.getSymbolAtLocation(node.name)?.valueDeclaration;
1329
+ if (member && ts.isEnumMember(member))
1330
+ return constant(this.checker.getConstantValue(member) as number);
1275
1331
  const object = this.expression(node.expression, frame);
1276
1332
  if (node.questionDotToken && object.kind === "const" && object.value === undefined)
1277
1333
  return constant(undefined);
@@ -1287,7 +1343,7 @@ export class Specializer {
1287
1343
  const value = this.expression(node.expression, frame);
1288
1344
  return {
1289
1345
  kind: "code",
1290
- text: `await ${this.code(value, undefined, frame)}`,
1346
+ text: mapped`await ${this.code(value, undefined, frame)}`,
1291
1347
  declared: this.checker.getTypeAtLocation(node),
1292
1348
  };
1293
1349
  }
@@ -1302,7 +1358,7 @@ export class Specializer {
1302
1358
  const whenFalse = this.expression(node.whenFalse, frame, declared);
1303
1359
  return {
1304
1360
  kind: "code",
1305
- text: `(${this.condition(condition, node.condition, frame)} ? ${this.code(whenTrue, declared, frame)} : ${this.code(whenFalse, declared, frame)})`,
1361
+ text: mapped`(${this.condition(condition, node.condition, frame)} ? ${this.code(whenTrue, declared, frame)} : ${this.code(whenFalse, declared, frame)})`,
1306
1362
  declared,
1307
1363
  };
1308
1364
  }
@@ -1418,6 +1474,10 @@ export class Specializer {
1418
1474
  const stored =
1419
1475
  step.kind === "field" ? this.stored(holder, step.name) : this.storedArray(holder);
1420
1476
  if (stored) return this.storedField(holder, step);
1477
+ if (holder.owner)
1478
+ this.readConstants.add(
1479
+ tsPath({ root: holder.owner.root, steps: [...holder.owner.steps, step] }),
1480
+ );
1421
1481
  return this.capturedConstant(value, holder.type?.symbol?.valueDeclaration ?? this.sources[0]!);
1422
1482
  }
1423
1483
 
@@ -1445,13 +1505,75 @@ export class Specializer {
1445
1505
  return element ? this.layouts.iecName({ type: element } as unknown as ts.Node) : undefined;
1446
1506
  }
1447
1507
 
1448
- /** The IEC width of an array's elements, from the declaration holding the array. */
1449
- private arrayElementIec(array: ModelNode): string | undefined {
1508
+ /** The declaration of the field holding an array. */
1509
+ private arrayDeclaration(array: ModelNode): ts.Node | undefined {
1450
1510
  const owner = array.owner;
1451
1511
  const last = owner?.steps.at(-1);
1452
1512
  if (!owner || last?.kind !== "field") return undefined;
1453
1513
  const holder = this.at(owner.root, owner.steps.slice(0, -1));
1454
- return holder && this.elementIec(this.fieldDeclaration(holder, last.name));
1514
+ return holder && this.fieldDeclaration(holder, last.name);
1515
+ }
1516
+
1517
+ /** The IEC width of an array's elements, from the declaration holding the array. */
1518
+ private arrayElementIec(array: ModelNode): string | undefined {
1519
+ return this.elementIec(this.arrayDeclaration(array));
1520
+ }
1521
+
1522
+ /**
1523
+ * Primitives setup stored in fields and arrays that scan code only reads. Specialization folds
1524
+ * them into the code, so they have no storage; this is where their values remain known.
1525
+ */
1526
+ folded(): { path: string; value: CapturedValue; declaration: ts.Node; iec?: string }[] {
1527
+ const found: { path: string; value: CapturedValue; declaration: ts.Node; iec?: string }[] = [];
1528
+ const visit = (node: ModelNode, owner: Owner, whole: boolean): void => {
1529
+ const captured = node.captured;
1530
+ // A record or array stored as a whole stores everything in it; a flattened root stores fields.
1531
+ const stores =
1532
+ whole ||
1533
+ (captured.kind === "object" &&
1534
+ !(owner.steps.length === 0 && this.flattened(owner.root)) &&
1535
+ this.storedWhole(node)) ||
1536
+ (captured.kind === "array" && this.storedArray(node));
1537
+ const members: [Step, CapturedValue][] =
1538
+ captured.kind === "array"
1539
+ ? captured.items.map((item, index) => [{ kind: "index", index }, item])
1540
+ : captured.kind === "object" || captured.kind === "instance"
1541
+ ? Object.entries(captured.fields).map(([name, field]) => [
1542
+ { kind: "field", name },
1543
+ field,
1544
+ ])
1545
+ : [];
1546
+ for (const [step, value] of members) {
1547
+ const at: Owner = { root: owner.root, steps: [...owner.steps, step] };
1548
+ const inner = this.model.node(value);
1549
+ if (inner) {
1550
+ // Visit what this node owns; other places holding it refer to its owner.
1551
+ if (inner.owner?.root === at.root && tsPath(inner.owner) === tsPath(at))
1552
+ visit(inner, at, stores);
1553
+ continue;
1554
+ }
1555
+ if (value.kind === "undefined" || stores || !this.readConstants.has(tsPath(at))) continue;
1556
+ if (step.kind === "field" && this.stored(node, step.name)) continue;
1557
+ const declaration =
1558
+ step.kind === "field"
1559
+ ? this.fieldDeclaration(node, step.name)
1560
+ : this.arrayDeclaration(node);
1561
+ const iec =
1562
+ step.kind === "field" ? this.fieldIec(node, step.name) : this.arrayElementIec(node);
1563
+ found.push({
1564
+ path: tsPath(at),
1565
+ value,
1566
+ declaration: declaration ?? owner.root.declaration,
1567
+ ...(iec && { iec }),
1568
+ });
1569
+ }
1570
+ };
1571
+ for (const root of this.model.roots) {
1572
+ const node = this.model.node(this.model.rootValues.get(root)!);
1573
+ if (node?.owner?.root === root && !root.exported && !this.kept(root.file))
1574
+ visit(node, { root, steps: [] }, false);
1575
+ }
1576
+ return found;
1455
1577
  }
1456
1578
 
1457
1579
  private storedField(holder: ModelNode, step: Step): Value {
@@ -1470,7 +1592,7 @@ export class Specializer {
1470
1592
  this.flattened(holder.owner.root);
1471
1593
  return {
1472
1594
  kind: "code",
1473
- text: `${this.pathText(holder)}${step.kind === "index" ? `[${step.index}]` : `.${step.name}`}`,
1595
+ text: `${this.pathText(holder)}${this.placeStep(holder, step)}`,
1474
1596
  declared,
1475
1597
  place: true,
1476
1598
  ...(step.kind === "field"
@@ -1535,7 +1657,7 @@ export class Specializer {
1535
1657
  this.checker.getPropertyOfType(this.checker.getNonNullableType(object.declared), name);
1536
1658
  return {
1537
1659
  kind: "code",
1538
- text: `${object.text}.${name}`,
1660
+ text: mapped`${object.text}.${name}`,
1539
1661
  declared,
1540
1662
  place: object.place,
1541
1663
  iec: this.layouts.iecName(property?.valueDeclaration),
@@ -1561,7 +1683,7 @@ export class Specializer {
1561
1683
  if (type.flags & ts.TypeFlags.Undefined) return value;
1562
1684
  return {
1563
1685
  kind: "code",
1564
- text: `${value.text}.value`,
1686
+ text: mapped`${value.text}.value`,
1565
1687
  declared: this.checker.getNonNullableType(value.declared),
1566
1688
  place: value.place,
1567
1689
  };
@@ -1619,10 +1741,10 @@ export class Specializer {
1619
1741
  (node.captured.kind === "array"
1620
1742
  ? this.model.elementType(node.type)
1621
1743
  : this.recordElement(node.type));
1622
- const text = this.storedNode(node) ? this.pathText(node) : this.table(node);
1744
+ const text = this.storedNode(node) ? this.pathText(node) : this.table(node, at);
1623
1745
  return {
1624
1746
  kind: "code",
1625
- text: `${text}[${this.code(index, undefined, frame)}]`,
1747
+ text: mapped`${text}[${this.code(index, undefined, frame)}]`,
1626
1748
  declared,
1627
1749
  place: true,
1628
1750
  };
@@ -1633,7 +1755,7 @@ export class Specializer {
1633
1755
  (this.model.elementType(object.declared) ?? this.recordElement(object.declared));
1634
1756
  return {
1635
1757
  kind: "code",
1636
- text: `${object.text}[${this.code(index, undefined, frame)}]`,
1758
+ text: mapped`${object.text}[${this.code(index, undefined, frame)}]`,
1637
1759
  declared,
1638
1760
  place: object.place,
1639
1761
  iec: object.elementIec,
@@ -1643,7 +1765,7 @@ export class Specializer {
1643
1765
  const text = this.materialize(object, at, frame);
1644
1766
  return {
1645
1767
  kind: "code",
1646
- text: `${text}[${this.code(index, undefined, frame)}]`,
1768
+ text: mapped`${text}[${this.code(index, undefined, frame)}]`,
1647
1769
  declared: this.checker.getTypeAtLocation(at),
1648
1770
  };
1649
1771
  }
@@ -1659,9 +1781,9 @@ export class Specializer {
1659
1781
  }
1660
1782
 
1661
1783
  private readonly tables = new Map<number, string>();
1662
- readonly tableDeclarations: string[] = [];
1663
- /** A fixed table setup built, emitted once for scan code that indexes it at runtime. */
1664
- private table(node: ModelNode): string {
1784
+ readonly tableDeclarations: Mapped[] = [];
1785
+ /** A fixed table setup built, emitted once, where scan code first indexes it at runtime. */
1786
+ private table(node: ModelNode, at: ts.Node): string {
1665
1787
  const known = this.tables.get(node.id);
1666
1788
  if (known) return known;
1667
1789
  if (!node.type) throw new Error("A table needs a declared type.");
@@ -1669,7 +1791,10 @@ export class Specializer {
1669
1791
  this.tables.set(node.id, name);
1670
1792
  const type = this.layouts.text(node.type, { kind: "node", id: node.id });
1671
1793
  this.tableDeclarations.push(
1672
- `const ${name}: ${type} = ${this.valueText({ kind: "node", id: node.id }, node.type, type)};`,
1794
+ from(
1795
+ at,
1796
+ `const ${name}: ${type} = ${this.valueText({ kind: "node", id: node.id }, node.type, type)};`,
1797
+ ),
1673
1798
  );
1674
1799
  return name;
1675
1800
  }
@@ -1682,9 +1807,10 @@ export class Specializer {
1682
1807
  throw new SpecializeError(at, "Not an array.");
1683
1808
  const local = frame.emitter.temporary();
1684
1809
  frame.emitter.line(
1685
- `const ${local}: FixedArray<${this.layouts.text(element)}, ${Math.max(value.items.length, 1)}> = [${value.items
1686
- .map((item) => this.code(item, element, frame))
1687
- .join(", ")}];`,
1810
+ mapped`const ${local}: FixedArray<${this.layouts.text(element)}, ${Math.max(value.items.length, 1)}> = [${joined(
1811
+ value.items.map((item) => this.code(item, element, frame)),
1812
+ ", ",
1813
+ )}];`,
1688
1814
  );
1689
1815
  return local;
1690
1816
  }
@@ -1718,7 +1844,7 @@ export class Specializer {
1718
1844
  if (operand.kind === "static" || operand.kind === "function") return constant(false);
1719
1845
  return {
1720
1846
  kind: "code",
1721
- text: `!${this.condition(operand, node.operand, frame)}`,
1847
+ text: mapped`!${this.condition(operand, node.operand, frame)}`,
1722
1848
  declared: this.checker.getBooleanType(),
1723
1849
  };
1724
1850
  case ts.SyntaxKind.MinusToken:
@@ -1726,7 +1852,7 @@ export class Specializer {
1726
1852
  return constant(-operand.value);
1727
1853
  return {
1728
1854
  kind: "code",
1729
- text: `-${this.code(operand, undefined, frame)}`,
1855
+ text: mapped`-${this.code(operand, undefined, frame)}`,
1730
1856
  declared: this.checker.getTypeAtLocation(node),
1731
1857
  };
1732
1858
  case ts.SyntaxKind.PlusToken:
@@ -1759,7 +1885,7 @@ export class Specializer {
1759
1885
  }
1760
1886
  return {
1761
1887
  kind: "code",
1762
- text: `(${this.condition(left, node.left, frame)} ${and ? "&&" : "||"} ${this.condition(right, node.right, frame)})`,
1888
+ text: mapped`(${this.condition(left, node.left, frame)} ${and ? "&&" : "||"} ${this.condition(right, node.right, frame)})`,
1763
1889
  declared: this.checker.getBooleanType(),
1764
1890
  };
1765
1891
  }
@@ -1776,7 +1902,7 @@ export class Specializer {
1776
1902
  );
1777
1903
  return {
1778
1904
  kind: "code",
1779
- text: `(${this.isUndefinedText(this.code(left, declared, frame), declared)} ? ${this.code(right, declared && this.checker.getNonNullableType(declared), frame)} : ${this.code(left, undefined, frame)}${declared && this.isOptionalRecord(declared) ? ".value" : ""})`,
1905
+ text: mapped`(${this.isUndefinedText(this.code(left, declared, frame), declared)} ? ${this.code(right, declared && this.checker.getNonNullableType(declared), frame)} : ${this.code(left, undefined, frame)}${declared && this.isOptionalRecord(declared) ? ".value" : ""})`,
1780
1906
  declared: declared && this.checker.getNonNullableType(declared),
1781
1907
  };
1782
1908
  }
@@ -1804,14 +1930,14 @@ export class Specializer {
1804
1930
  const test = this.isUndefinedText(code.text, code.declared);
1805
1931
  return {
1806
1932
  kind: "code",
1807
- text: negate ? `!(${test})` : test,
1933
+ text: negate ? mapped`!(${test})` : test,
1808
1934
  declared: this.checker.getBooleanType(),
1809
1935
  };
1810
1936
  }
1811
1937
  const declared = code.kind === "code" ? code.declared : undefined;
1812
1938
  const [leftText, rightText] = this.comparable(left, right, declared, frame);
1813
- const text = `${leftText} ${negate ? "!==" : "==="} ${rightText}`;
1814
- return { kind: "code", text: `(${text})`, declared: this.checker.getBooleanType() };
1939
+ const text = mapped`${leftText} ${negate ? "!==" : "==="} ${rightText}`;
1940
+ return { kind: "code", text: mapped`(${text})`, declared: this.checker.getBooleanType() };
1815
1941
  }
1816
1942
  if (
1817
1943
  left.kind === "const" &&
@@ -1829,7 +1955,7 @@ export class Specializer {
1829
1955
  const [leftText, rightText] = ["<", "<=", ">", ">="].includes(operator)
1830
1956
  ? this.comparable(left, right, undefined, frame)
1831
1957
  : [this.code(left, undefined, frame), this.code(right, undefined, frame)];
1832
- return { kind: "code", text: `(${leftText} ${operator} ${rightText})`, declared };
1958
+ return { kind: "code", text: mapped`(${leftText} ${operator} ${rightText})`, declared };
1833
1959
  }
1834
1960
 
1835
1961
  /**
@@ -1841,7 +1967,7 @@ export class Specializer {
1841
1967
  right: Value,
1842
1968
  declared: ts.Type | undefined,
1843
1969
  frame: Frame,
1844
- ): [string, string] {
1970
+ ): [string | Mapped, string | Mapped] {
1845
1971
  const leftText = this.code(left, declared, frame),
1846
1972
  rightText = this.code(right, declared, frame);
1847
1973
  if (left.kind !== "code" || right.kind !== "code") return [leftText, rightText];
@@ -1849,7 +1975,7 @@ export class Specializer {
1849
1975
  to = right.iec ?? "DINT";
1850
1976
  if (!needsConversion(from, to) || !needsConversion(to, from)) return [leftText, rightText];
1851
1977
  this.typeImports.add("wrap");
1852
- return [`wrap<LINT>(${leftText})`, `wrap<LINT>(${rightText})`];
1978
+ return [mapped`wrap<LINT>(${leftText})`, mapped`wrap<LINT>(${rightText})`];
1853
1979
  }
1854
1980
 
1855
1981
  /** Equality known now: two known objects, or a known object against undefined. */
@@ -1865,15 +1991,16 @@ export class Specializer {
1865
1991
  }
1866
1992
 
1867
1993
  /** A boolean condition, including JavaScript truthiness of optionals and enums. */
1868
- private condition(value: Value, at: ts.Node, frame: Frame): string {
1994
+ private condition(value: Value, at: ts.Node, frame: Frame): string | Mapped {
1869
1995
  if (value.kind === "code" && value.declared) {
1870
1996
  const declared = value.declared;
1871
1997
  if (this.isOptionalRecord(declared) && !ts.isPrefixUnaryExpression(at)) {
1872
1998
  const type = this.checker.getTypeAtLocation(at);
1873
- if (!(type.flags & ts.TypeFlags.BooleanLike)) return `${value.text}.has`;
1999
+ if (!(type.flags & ts.TypeFlags.BooleanLike)) return mapped`${value.text}.has`;
1874
2000
  }
1875
2001
  const literal = this.layouts.literalEnum(declared);
1876
- if (literal?.optional) return `${value.text} !== ${this.layouts.member(literal, undefined)}`;
2002
+ if (literal?.optional)
2003
+ return mapped`${value.text} !== ${this.layouts.member(literal, undefined)}`;
1877
2004
  }
1878
2005
  return this.code(value, undefined, frame);
1879
2006
  }
@@ -1902,6 +2029,12 @@ export class Specializer {
1902
2029
  };
1903
2030
  throw new SpecializeError(node, "Object.values needs a record setup built.");
1904
2031
  }
2032
+ if (this.telemetryCall(callee))
2033
+ return {
2034
+ kind: "code",
2035
+ text: this.telemetry(node, callee, frame),
2036
+ declared: this.checker.getTypeAtLocation(node),
2037
+ };
1905
2038
  const receiver = this.expression(callee.expression, frame);
1906
2039
  const items = this.items(receiver);
1907
2040
  if (items && isArrayMethod(name)) return this.arrayMethod(name, items, node, frame);
@@ -1977,10 +2110,58 @@ export class Specializer {
1977
2110
  let symbol = this.checker.getSymbolAtLocation(callee);
1978
2111
  while (symbol && symbol.flags & ts.SymbolFlags.Alias)
1979
2112
  symbol = this.checker.getAliasedSymbol(symbol);
1980
- const file = symbol?.declarations?.[0]?.getSourceFile().fileName ?? "";
2113
+ return this.sdkFile(symbol?.declarations?.[0]?.getSourceFile().fileName ?? "");
2114
+ }
2115
+
2116
+ private sdkFile(file: string): boolean {
1981
2117
  return file.includes("/@tsplc/compiler/") || file.includes("/packages/compiler/");
1982
2118
  }
1983
2119
 
2120
+ /** A method of `@tsplc/compiler/telemetry`'s `telemetry`. */
2121
+ private telemetryCall(callee: ts.PropertyAccessExpression): boolean {
2122
+ const file =
2123
+ this.checker.getSymbolAtLocation(callee.name)?.declarations?.[0]?.getSourceFile().fileName ??
2124
+ "";
2125
+ return file.endsWith("/telemetry.d.ts") && this.sdkFile(file);
2126
+ }
2127
+
2128
+ /**
2129
+ * Keeps a telemetry call as written, with its values specialized: the analyzer checks and
2130
+ * lowers it, and needs its name, message and property names as they are.
2131
+ */
2132
+ private telemetry(
2133
+ node: ts.CallExpression,
2134
+ callee: ts.PropertyAccessExpression,
2135
+ frame: Frame,
2136
+ ): Mapped {
2137
+ const value = (argument: ts.Expression): Part =>
2138
+ ts.isCallExpression(argument) &&
2139
+ ts.isPropertyAccessExpression(argument.expression) &&
2140
+ this.telemetryCall(argument.expression)
2141
+ ? this.telemetry(argument, argument.expression, frame)
2142
+ : // A folded enum field keeps its type, so it is sent as its member's name.
2143
+ this.code(
2144
+ this.expression(argument, frame),
2145
+ this.checker.getTypeAtLocation(argument),
2146
+ frame,
2147
+ );
2148
+ const args = node.arguments.map((argument): Part => {
2149
+ if (ts.isStringLiteral(argument) || ts.isNoSubstitutionTemplateLiteral(argument))
2150
+ return copied(argument);
2151
+ if (!ts.isObjectLiteralExpression(argument)) return value(argument);
2152
+ const properties = argument.properties.map((property) => {
2153
+ if (ts.isShorthandPropertyAssignment(property))
2154
+ return mapped`${copied(property.name)}: ${value(property.name)}`;
2155
+ if (!ts.isPropertyAssignment(property))
2156
+ throw new SpecializeError(property, "Name each telemetry property.");
2157
+ return mapped`${copied(property.name)}: ${value(property.initializer)}`;
2158
+ });
2159
+ return mapped`{ ${joined(properties, ", ")} }`;
2160
+ });
2161
+ this.telemetryImport = true;
2162
+ return from(node, mapped`telemetry.${callee.name.text}(${joined(args, ", ")})`);
2163
+ }
2164
+
1984
2165
  private sdk(name: string, node: ts.CallExpression, frame: Frame): Value {
1985
2166
  const args = node.arguments.map((argument) =>
1986
2167
  this.code(this.expression(argument, frame), undefined, frame),
@@ -1988,12 +2169,14 @@ export class Specializer {
1988
2169
  this.sdkImports.add(name);
1989
2170
  return {
1990
2171
  kind: "code",
1991
- text: `${name}(${args.join(", ")})`,
2172
+ text: mapped`${name}(${joined(args, ", ")})`,
1992
2173
  declared: this.checker.getTypeAtLocation(node),
1993
2174
  };
1994
2175
  }
1995
2176
 
1996
2177
  readonly sdkImports = new Set<string>();
2178
+ /** Whether scan code calls `telemetry`, which generated code imports. */
2179
+ telemetryImport = false;
1997
2180
  /** Conversions generated code imports from `@tsplc/compiler/types`. */
1998
2181
  readonly typeImports = new Set<string>();
1999
2182
 
@@ -2011,7 +2194,7 @@ export class Specializer {
2011
2194
  switch (name) {
2012
2195
  case "abs": {
2013
2196
  const local = frame.emitter.temporary();
2014
- frame.emitter.line(`const ${local}: number = ${texts[0]};`);
2197
+ frame.emitter.line(mapped`const ${local}: number = ${texts[0]!};`);
2015
2198
  return { kind: "code", text: `(${local} < 0 ? 0 - ${local} : ${local})`, declared };
2016
2199
  }
2017
2200
  case "min":
@@ -2019,7 +2202,7 @@ export class Specializer {
2019
2202
  if (texts.length !== 2) throw new SpecializeError(node, `Math.${name} takes two values.`);
2020
2203
  return {
2021
2204
  kind: "code",
2022
- text: `(${texts[0]} ${name === "min" ? "<" : ">"} ${texts[1]} ? ${texts[0]} : ${texts[1]})`,
2205
+ text: mapped`(${texts[0]!} ${name === "min" ? "<" : ">"} ${texts[1]!} ? ${texts[0]!} : ${texts[1]!})`,
2023
2206
  declared,
2024
2207
  };
2025
2208
  default:
@@ -2046,7 +2229,7 @@ export class Specializer {
2046
2229
  );
2047
2230
  return {
2048
2231
  kind: "code",
2049
- text: `${client.name}.${path}(${args.join(", ")})`,
2232
+ text: mapped`${client.name}.${path}(${joined(args, ", ")})`,
2050
2233
  declared: this.checker.getTypeAtLocation(node),
2051
2234
  };
2052
2235
  }
@@ -2077,11 +2260,11 @@ export class Specializer {
2077
2260
  return this.expression(declaration.body, inline, expected);
2078
2261
  }
2079
2262
  const called = this.routine(declaration, target.self, args, target.env);
2080
- const text = `${called.name}(${called.args.join(", ")})`;
2263
+ const text = mapped`${called.name}(${joined(called.args, ", ")})`;
2081
2264
  const returns = called.returns;
2082
2265
  if (!returns || returns.flags & ts.TypeFlags.Void) {
2083
2266
  if (ts.isExpressionStatement(at.parent)) return { kind: "code", text, declared: returns };
2084
- frame.emitter.line(`${text};`);
2267
+ frame.emitter.line(mapped`${text};`);
2085
2268
  return constant(undefined);
2086
2269
  }
2087
2270
  return { kind: "code", text, declared: returns };
@@ -2089,10 +2272,10 @@ export class Specializer {
2089
2272
 
2090
2273
  /** A runtime value held in a const, so inlining doesn't evaluate it twice. */
2091
2274
  private temporaryOf(value: Value & { kind: "code" }, frame: Frame): Value {
2092
- if (/^[\w.[\]]+$/.test(value.text)) return value;
2275
+ if (/^[\w.[\]]+$/.test(String(value.text))) return value;
2093
2276
  const local = frame.emitter.temporary();
2094
2277
  const type = value.declared ? this.localType(value.declared) : "number";
2095
- frame.emitter.line(`const ${local}: ${type} = ${value.text};`);
2278
+ frame.emitter.line(mapped`const ${local}: ${type} = ${value.text};`);
2096
2279
  return { kind: "code", text: local, declared: value.declared, place: true };
2097
2280
  }
2098
2281
 
@@ -2135,14 +2318,14 @@ export class Specializer {
2135
2318
  case "forEach":
2136
2319
  items.forEach((item, index) => {
2137
2320
  const result = apply([item, constant(index)]);
2138
- if (result.kind === "code") frame.emitter.line(`${result.text};`);
2321
+ if (result.kind === "code") frame.emitter.line(mapped`${result.text};`);
2139
2322
  });
2140
2323
  return constant(undefined);
2141
2324
  case "some":
2142
2325
  case "every": {
2143
2326
  const some = name === "some";
2144
2327
  const tests = items.map((item, index) => apply([item, constant(index)]));
2145
- const runtime: string[] = [];
2328
+ const runtime: (string | Mapped)[] = [];
2146
2329
  for (const test of tests) {
2147
2330
  if (test.kind === "const") {
2148
2331
  if (Boolean(test.value) === some) return constant(some);
@@ -2153,7 +2336,7 @@ export class Specializer {
2153
2336
  if (!runtime.length) return constant(!some);
2154
2337
  return {
2155
2338
  kind: "code",
2156
- text: `(${runtime.join(some ? " || " : " && ")})`,
2339
+ text: mapped`(${joined(runtime, some ? " || " : " && ")})`,
2157
2340
  declared: this.checker.getBooleanType(),
2158
2341
  };
2159
2342
  }
@@ -2189,10 +2372,10 @@ export class Specializer {
2189
2372
 
2190
2373
  /** Keeps a runtime result in a local, so later code reads it rather than repeating it. */
2191
2374
  private settle(value: Value, frame: Frame): Value {
2192
- if (value.kind !== "code" || /^[\w.[\]]+$/.test(value.text)) return value;
2375
+ if (value.kind !== "code" || /^[\w.[\]]+$/.test(String(value.text))) return value;
2193
2376
  const local = frame.emitter.temporary();
2194
2377
  frame.emitter.line(
2195
- `const ${local}: ${value.declared ? this.localType(value.declared) : "boolean"} = ${value.text};`,
2378
+ mapped`const ${local}: ${value.declared ? this.localType(value.declared) : "boolean"} = ${value.text};`,
2196
2379
  );
2197
2380
  return { kind: "code", text: local, declared: value.declared, place: true };
2198
2381
  }
@@ -2200,7 +2383,7 @@ export class Specializer {
2200
2383
  // ---- Values as code ----
2201
2384
 
2202
2385
  /** Dialect text for a value, in a place of `expected` type when known. */
2203
- code(value: Value, expected: ts.Type | undefined, frame: Frame): string {
2386
+ code(value: Value, expected: ts.Type | undefined, frame: Frame): string | Mapped {
2204
2387
  switch (value.kind) {
2205
2388
  case "code":
2206
2389
  if (
@@ -2209,7 +2392,7 @@ export class Specializer {
2209
2392
  this.isOptionalRecord(value.declared) &&
2210
2393
  !this.isOptionalRecord(expected)
2211
2394
  )
2212
- return `${value.text}.value`;
2395
+ return mapped`${value.text}.value`;
2213
2396
  return value.text;
2214
2397
  case "const": {
2215
2398
  const literal = expected && this.layouts.literalEnum(expected);
@@ -2240,7 +2423,10 @@ export class Specializer {
2240
2423
  }
2241
2424
  if (value.items) {
2242
2425
  const element = expected && this.model.elementType(expected);
2243
- return `[${value.items.map((item) => this.code(item, element, frame)).join(", ")}]`;
2426
+ return mapped`[${joined(
2427
+ value.items.map((item) => this.code(item, element, frame)),
2428
+ ", ",
2429
+ )}]`;
2244
2430
  }
2245
2431
  throw new Error("Empty value.");
2246
2432
  }
@@ -2250,13 +2436,13 @@ export class Specializer {
2250
2436
  }
2251
2437
 
2252
2438
  /** A record literal of `type`, every field written; a tagged union fills the other variants' fields. */
2253
- private recordLiteral(fields: Map<string, Value>, type: ts.Type, frame: Frame): string {
2439
+ private recordLiteral(fields: Map<string, Value>, type: ts.Type, frame: Frame): Mapped {
2254
2440
  const tagged = this.layouts.tagged(type);
2255
2441
  const names = tagged
2256
2442
  ? this.taggedFields(tagged)
2257
2443
  : this.checker.getPropertiesOfType(type).map((property) => property.name);
2258
- return `{ ${names
2259
- .map((name) => {
2444
+ return mapped`{ ${joined(
2445
+ names.map((name) => {
2260
2446
  const fieldType = tagged
2261
2447
  ? name === tagged.tag
2262
2448
  ? this.tagType(type, tagged)
@@ -2265,9 +2451,10 @@ export class Specializer {
2265
2451
  const value = fields.get(name);
2266
2452
  if (!value) return `${name}: ${this.defaultOf(fieldType)}`;
2267
2453
  const property = this.checker.getPropertyOfType(type, name);
2268
- return `${name}: ${this.assignmentText(value, fieldType, frame, this.layouts.iecName(property?.valueDeclaration))}`;
2269
- })
2270
- .join(", ")} }`;
2454
+ return mapped`${name}: ${this.assignmentText(value, fieldType, frame, this.layouts.iecName(property?.valueDeclaration))}`;
2455
+ }),
2456
+ ", ",
2457
+ )} }`;
2271
2458
  }
2272
2459
  }
2273
2460
 
@@ -2308,6 +2495,10 @@ const isChild = (node: ModelNode, holder: ModelNode, field?: string): boolean =>
2308
2495
  return field === undefined || (last.kind === "field" && last.name === field);
2309
2496
  };
2310
2497
 
2498
+ /** Where a routine ends: the closing brace of its body, or the whole of a one-expression arrow. */
2499
+ export const closingBrace = (declaration: FunctionLike): ts.Node =>
2500
+ declaration.body && ts.isBlock(declaration.body) ? declaration.body.getLastToken()! : declaration;
2501
+
2311
2502
  /** The function a storage module exports to set one of its globals. */
2312
2503
  export const setterName = (name: string): string => `tsplcSet_${name}`;
2313
2504