@tsplc/compiler 0.2.13 → 0.2.16

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 +205 -36
  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 +74 -15
  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
@@ -2,6 +2,7 @@ import { runtimeSources } from "./module-graph.ts";
2
2
  import ts from "typescript";
3
3
  import { dirname } from "node:path";
4
4
  import { error, type Diagnostic } from "@tsplc/compiler/ir";
5
+ import { edited, type Edit, type Mapped, type Positions } from "./positions.ts";
5
6
 
6
7
  const symbolAt = (checker: ts.TypeChecker, node: ts.Node) => {
7
8
  let symbol = checker.getSymbolAtLocation(node);
@@ -9,13 +10,13 @@ const symbolAt = (checker: ts.TypeChecker, node: ts.Node) => {
9
10
  return symbol;
10
11
  };
11
12
 
12
- export const lowerEnvironment = (program: ts.Program, sdk: string) => {
13
+ export const lowerEnvironment = (program: ts.Program, sdk: string, positions: Positions) => {
13
14
  const checker = program.getTypeChecker();
14
- const sources = new Map<string, string>();
15
+ const sources = new Map<string, Mapped>();
15
16
  const diagnostics: Diagnostic[] = [];
16
17
  for (const source of runtimeSources(program)) {
17
18
  if (source.isDeclarationFile) continue;
18
- const edits: { start: number; end: number; text: string }[] = [];
19
+ const edits: Edit[] = [];
19
20
  const visit = (node: ts.Node): void => {
20
21
  if (ts.isCallExpression(node)) {
21
22
  const symbol = symbolAt(checker, node.expression);
@@ -51,19 +52,8 @@ export const lowerEnvironment = (program: ts.Program, sdk: string) => {
51
52
  message = `Required environment value ${name.text} is missing.`;
52
53
  else if (value.includes("\0"))
53
54
  message = `Environment value ${name.text} contains an unsupported NUL byte.`;
54
- if (message) {
55
- const start = node.getStart(source),
56
- position = source.getLineAndCharacterOfPosition(start);
57
- diagnostics.push(
58
- error("PLC1011", message, {
59
- file: source.fileName,
60
- start,
61
- end: node.end,
62
- line: position.line + 1,
63
- column: position.character + 1,
64
- }),
65
- );
66
- } else if (value !== undefined)
55
+ if (message) diagnostics.push(error("PLC1011", message, positions.node(node)));
56
+ else if (value !== undefined)
67
57
  edits.push({
68
58
  start: node.getStart(source),
69
59
  end: node.end,
@@ -75,11 +65,7 @@ export const lowerEnvironment = (program: ts.Program, sdk: string) => {
75
65
  ts.forEachChild(node, visit);
76
66
  };
77
67
  visit(source);
78
- if (!edits.length) continue;
79
- let text = source.text;
80
- for (const edit of edits.sort((a, b) => b.start - a.start))
81
- text = text.slice(0, edit.start) + edit.text + text.slice(edit.end);
82
- sources.set(source.fileName, text);
68
+ if (edits.length) sources.set(source.fileName, edited(source, edits));
83
69
  }
84
70
  return { sources, diagnostics };
85
71
  };
@@ -1,17 +1,27 @@
1
1
  import { runtimeSources } from "./module-graph.ts";
2
2
  import ts from "typescript";
3
3
  import { error, type Diagnostic } from "@tsplc/compiler/ir";
4
+ import {
5
+ copied,
6
+ edited,
7
+ from,
8
+ joined,
9
+ mapped,
10
+ type Edit,
11
+ type Mapped,
12
+ type Positions,
13
+ } from "./positions.ts";
4
14
 
5
15
  /** Normalize static arrow bindings so all routine forms use the same PLC analysis. */
6
- export const lowerConstFunctions = (program: ts.Program) => {
16
+ export const lowerConstFunctions = (program: ts.Program, positions: Positions) => {
7
17
  const checker = program.getTypeChecker();
8
18
  const printer = ts.createPrinter();
9
- const sources = new Map<string, string>();
19
+ const sources = new Map<string, Mapped>();
10
20
  const diagnostics: Diagnostic[] = [];
11
21
 
12
22
  for (const source of runtimeSources(program)) {
13
23
  if (source.isDeclarationFile) continue;
14
- const edits: { start: number; end: number; text: string }[] = [];
24
+ const edits: Edit[] = [];
15
25
  for (const statement of source.statements) {
16
26
  const routines = ts.isClassDeclaration(statement)
17
27
  ? statement.members.filter(ts.isMethodDeclaration)
@@ -29,7 +39,7 @@ export const lowerConstFunctions = (program: ts.Program) => {
29
39
  signature && checker.getAwaitedType(checker.getReturnTypeOfSignature(signature));
30
40
  if (result && result.flags & ts.TypeFlags.Void) {
31
41
  const position = routine.body.getStart(source);
32
- edits.push({ start: position, end: position, text: ":Promise<void> " });
42
+ edits.push({ start: position, end: position, text: from(routine, ":Promise<void> ") });
33
43
  }
34
44
  }
35
45
  }
@@ -42,15 +52,23 @@ export const lowerConstFunctions = (program: ts.Program) => {
42
52
  )
43
53
  continue;
44
54
 
45
- const declarations: ts.Statement[] = [];
55
+ const print = (node: ts.Node) => printer.printNode(ts.EmitHint.Unspecified, node, source);
56
+ const declarations: Mapped[] = [];
46
57
  for (const declaration of statement.declarationList.declarations) {
47
58
  const arrow = declaration.initializer;
48
59
  if (!arrow || !ts.isArrowFunction(arrow)) {
49
60
  declarations.push(
50
- ts.factory.updateVariableStatement(
51
- statement,
52
- statement.modifiers,
53
- ts.factory.updateVariableDeclarationList(statement.declarationList, [declaration]),
61
+ from(
62
+ declaration,
63
+ print(
64
+ ts.factory.updateVariableStatement(
65
+ statement,
66
+ statement.modifiers,
67
+ ts.factory.updateVariableDeclarationList(statement.declarationList, [
68
+ declaration,
69
+ ]),
70
+ ),
71
+ ),
54
72
  ),
55
73
  );
56
74
  continue;
@@ -59,19 +77,11 @@ export const lowerConstFunctions = (program: ts.Program) => {
59
77
  !(statement.declarationList.flags & ts.NodeFlags.Const) ||
60
78
  !ts.isIdentifier(declaration.name)
61
79
  ) {
62
- const start = declaration.getStart(source);
63
- const position = source.getLineAndCharacterOfPosition(start);
64
80
  diagnostics.push(
65
81
  error(
66
82
  "PLC1007",
67
83
  "PLC routines require named const bindings; mutable function values are unsupported.",
68
- {
69
- file: source.fileName,
70
- start,
71
- end: declaration.end,
72
- line: position.line + 1,
73
- column: position.character + 1,
74
- },
84
+ positions.node(declaration),
75
85
  ),
76
86
  );
77
87
  continue;
@@ -113,17 +123,8 @@ export const lowerConstFunctions = (program: ts.Program) => {
113
123
  parameter.initializer,
114
124
  ),
115
125
  );
116
- const body = ts.isBlock(arrow.body)
117
- ? arrow.body
118
- : ts.factory.createBlock(
119
- [
120
- result?.kind === ts.SyntaxKind.VoidKeyword
121
- ? ts.factory.createExpressionStatement(arrow.body)
122
- : ts.factory.createReturnStatement(arrow.body),
123
- ],
124
- true,
125
- );
126
- declarations.push(
126
+ // The header is printed; the body stays the user's text, so its positions map exactly.
127
+ const head = print(
127
128
  ts.factory.createFunctionDeclaration(
128
129
  [...(statement.modifiers ?? []), ...(arrow.modifiers ?? [])],
129
130
  undefined,
@@ -131,23 +132,28 @@ export const lowerConstFunctions = (program: ts.Program) => {
131
132
  arrow.typeParameters ?? contextual?.typeParameters,
132
133
  parameters,
133
134
  result,
134
- body,
135
+ ts.factory.createBlock([]),
136
+ ),
137
+ ).replace(/\{\s*\}$/, "");
138
+ const body = copied(arrow.body);
139
+ declarations.push(
140
+ from(
141
+ declaration,
142
+ ts.isBlock(arrow.body)
143
+ ? mapped`${head}${body}`
144
+ : result?.kind === ts.SyntaxKind.VoidKeyword
145
+ ? mapped`${head}{ ${body}; }`
146
+ : mapped`${head}{ return ${body}; }`,
135
147
  ),
136
148
  );
137
149
  }
138
150
  edits.push({
139
151
  start: statement.getStart(source),
140
152
  end: statement.end,
141
- text: declarations
142
- .map((declaration) => printer.printNode(ts.EmitHint.Unspecified, declaration, source))
143
- .join("\n"),
153
+ text: joined(declarations, "\n"),
144
154
  });
145
155
  }
146
- if (!edits.length) continue;
147
- let text = source.text;
148
- for (const edit of edits.reverse())
149
- text = text.slice(0, edit.start) + edit.text + text.slice(edit.end);
150
- sources.set(source.fileName, text);
156
+ if (edits.length) sources.set(source.fileName, edited(source, edits));
151
157
  }
152
158
  return { sources, diagnostics };
153
159
  };
@@ -54,6 +54,13 @@ plugin({
54
54
  contents: "export const now = () => 0;",
55
55
  loader: "js",
56
56
  }));
57
+ // Records describe scans, so setup has none to make.
58
+ build.module("@tsplc/compiler/telemetry", () => ({
59
+ contents: `const unsupported = (name) => () => { throw new Error("telemetry." + name + " cannot run during PLC setup."); };
60
+ export const telemetry = Object.fromEntries(["capture", "info", "warn", "error", "captureException", "text"].map((name) => [name, unsupported(name)]));
61
+ export const onTelemetry = () => () => {};`,
62
+ loader: "js",
63
+ }));
57
64
  build.module("@tsplc/compiler/async", () => ({
58
65
  contents: `export const createServiceClient = () => globalThis.__tsplcService([]);
59
66
  const unsupported = (name) => () => { throw new Error(name + " cannot run during PLC setup."); };
@@ -1,10 +1,17 @@
1
1
  import ts from "typescript";
2
2
  import { dirname, join, relative, resolve } from "node:path";
3
- import { error, type Diagnostic } from "@tsplc/compiler/ir";
3
+ import {
4
+ error,
5
+ type Constant,
6
+ type Diagnostic,
7
+ type SourceSpan,
8
+ type TypeId,
9
+ } from "@tsplc/compiler/ir";
4
10
  import { runtimeSources } from "../module-graph.ts";
5
- import { captureGraph } from "./graph.ts";
11
+ import { copied, from, joined, type Mapped, type Positions } from "../positions.ts";
12
+ import { captureGraph, type CapturedValue } from "./graph.ts";
6
13
  import { Model, type Root } from "./model.ts";
7
- import { setterName, Specializer, SpecializeError } from "./specialize.ts";
14
+ import { closingBrace, setterName, Specializer, SpecializeError } from "./specialize.ts";
8
15
 
9
16
  /** Directory of the modules elaboration generates, beside the entry module. */
10
17
  const generatedDirectory = ".tsplc";
@@ -84,6 +91,32 @@ const importPath = (from: string, to: string): string => {
84
91
  return path.startsWith("./") || path.startsWith("../") ? path : `./${path}`;
85
92
  };
86
93
 
94
+ type Folded = { path: string; value: Constant; type?: TypeId; span: SourceSpan };
95
+
96
+ /**
97
+ * A folded primitive as a PLC constant, with its scalar type: the IEC width its declaration
98
+ * names, or the one a TypeScript number of that value gets. Strings, often enum members, have none.
99
+ */
100
+ const constant = (
101
+ value: CapturedValue,
102
+ iec: string | undefined,
103
+ ): Pick<Folded, "value" | "type"> | undefined => {
104
+ switch (value.kind) {
105
+ case "number":
106
+ return Number.isInteger(value.value)
107
+ ? { value: { kind: "integer", value: String(value.value) }, type: iec ?? "DINT" }
108
+ : { value: { kind: "float", value: value.value }, type: iec ?? "LREAL" };
109
+ case "bigint":
110
+ return { value: { kind: "integer", value: value.value }, type: iec ?? "LINT" };
111
+ case "boolean":
112
+ return { value: { kind: "bool", value: value.value }, type: "BOOL" };
113
+ case "string":
114
+ return { value: { kind: "string", value: value.value } };
115
+ default:
116
+ return undefined;
117
+ }
118
+ };
119
+
87
120
  /**
88
121
  * Compiles a plain TypeScript program: runs its setup, then specializes its scan code against
89
122
  * the objects setup built. The result is tsPLC dialect source the rest of the compiler reads.
@@ -93,27 +126,38 @@ export const lowerElaboration = (
93
126
  sdk: string,
94
127
  entries: Readonly<Record<string, { module: string; export: string }>>,
95
128
  root: string,
96
- ): { sources: Map<string, string>; diagnostics: Diagnostic[] } => {
97
- const sources = new Map<string, string>();
129
+ positions: Positions,
130
+ ): {
131
+ sources: Map<string, Mapped>;
132
+ diagnostics: Diagnostic[];
133
+ /** Routines specialized from class methods, by `<entry file>:<routine>`. */
134
+ origins: Map<string, { name: string; instance?: string }>;
135
+ folded: Folded[];
136
+ /** The string each member of a literal union's enum stands for, by `<types file>:<enum>`. */
137
+ literals: Map<string, Record<string, string>>;
138
+ } => {
139
+ const sources = new Map<string, Mapped>();
98
140
  const diagnostics: Diagnostic[] = [];
141
+ const origins = new Map<string, { name: string; instance?: string }>();
142
+ const folded: Folded[] = [];
143
+ const literals = new Map<string, Record<string, string>>();
144
+ const result = { sources, diagnostics, origins, folded, literals };
99
145
  const runtime = runtimeSources(program).filter(
100
146
  (source) => !source.isDeclarationFile && !source.fileName.startsWith(`${dirname(sdk)}/`),
101
147
  );
102
- if (!needsElaboration(runtime, sdk)) return { sources, diagnostics };
148
+ if (!needsElaboration(runtime, sdk)) return result;
103
149
  const programEntries = Object.values(entries);
104
- if (programEntries.length !== 1)
105
- return {
106
- sources,
107
- diagnostics: [error("PLC1001", "A plain TypeScript program has one entry function.")],
108
- };
150
+ if (programEntries.length !== 1) {
151
+ diagnostics.push(error("PLC1001", "A plain TypeScript program has one entry function."));
152
+ return result;
153
+ }
109
154
  const [entry] = programEntries as [{ module: string; export: string }];
110
155
  const entryFile = resolve(root, entry.module).replace(/\\/g, "/");
111
156
  const entrySource = program.getSourceFile(entryFile);
112
- if (!entrySource)
113
- return {
114
- sources,
115
- diagnostics: [error("PLC1001", `${entry.module} is not part of the program.`)],
116
- };
157
+ if (!entrySource) {
158
+ diagnostics.push(error("PLC1001", `${entry.module} is not part of the program.`));
159
+ return result;
160
+ }
117
161
  const checker = program.getTypeChecker();
118
162
  const kept = new Set(
119
163
  runtime.filter((source) => keptModule(source, sdk)).map((source) => source.fileName),
@@ -134,22 +178,36 @@ export const lowerElaboration = (
134
178
  if (item.exported && !isKept(item.file) && item.file === entryFile) specializer.use(item);
135
179
 
136
180
  const typesFile = `${directory}/types.ts`;
137
- const storage = new Map<string, string[]>();
181
+ const storage = new Map<Root, Mapped[]>();
138
182
  for (const item of specializer.roots) {
139
183
  const value = model.rootValues.get(item)!;
140
184
  const node = model.node(value)!;
141
- const lines: string[] = [];
185
+ const lines: Mapped[] = [];
142
186
  // Other modules can't assign an imported binding, so each global comes with a setter.
143
- const global = (name: string, layout: string, initial: string) =>
187
+ const global = (
188
+ name: string,
189
+ layout: string,
190
+ initial: string,
191
+ declaration: ts.Node = item.declaration,
192
+ ) =>
144
193
  lines.push(
145
- `export let ${name}: ${layout} = ${initial};`,
146
- `export function ${setterName(name)}(value: ${layout}): void { ${name} = value; }`,
194
+ from(declaration, `export let ${name}: ${layout} = ${initial};`),
195
+ from(
196
+ declaration,
197
+ `export function ${setterName(name)}(value: ${layout}): void { ${name} = value; }`,
198
+ ),
147
199
  );
148
200
  if (specializer.flattened(item)) {
149
201
  const captured = node.captured;
150
202
  if (captured.kind === "instance") {
203
+ const declaration = model.classOf(node);
151
204
  for (const [name, layout] of specializer.instanceFields(node))
152
- global(name, layout, specializer.instanceFieldInitializer(node, name, layout));
205
+ global(
206
+ name,
207
+ layout,
208
+ specializer.instanceFieldInitializer(node, name, layout),
209
+ model.member(declaration, name),
210
+ );
153
211
  } else if (captured.kind === "object") {
154
212
  for (const [name, field] of Object.entries(captured.fields)) {
155
213
  const inner = model.node(field);
@@ -167,7 +225,12 @@ export const lowerElaboration = (
167
225
  name.charAt(0).toUpperCase() + name.slice(1),
168
226
  );
169
227
  if (!layout) continue;
170
- global(name, layout, specializer.valueText(field, declared, layout));
228
+ global(
229
+ name,
230
+ layout,
231
+ specializer.valueText(field, declared, layout),
232
+ node.type?.getProperty(name)?.valueDeclaration,
233
+ );
171
234
  }
172
235
  }
173
236
  } else {
@@ -175,7 +238,7 @@ export const lowerElaboration = (
175
238
  const layout = specializer.layouts.declaredText(item.declaration, declared, value);
176
239
  global(item.name, layout, specializer.valueText(value, declared, layout));
177
240
  }
178
- storage.set(rootModule(item), lines);
241
+ storage.set(item, lines);
179
242
  }
180
243
 
181
244
  const typeImports = (file: string) => [
@@ -202,10 +265,16 @@ export const lowerElaboration = (
202
265
  ];
203
266
  sources.set(
204
267
  typesFile,
205
- [...typeImports(typesFile), ...specializer.layouts.declarations.values()].join("\n"),
268
+ joined([...typeImports(typesFile), ...specializer.layouts.declarations.values()], "\n"),
206
269
  );
207
- for (const [file, lines] of storage)
208
- sources.set(file, [...typeImports(file), ...importTypes(file), ...lines].join("\n"));
270
+ for (const [item, lines] of storage) {
271
+ const file = rootModule(item);
272
+ const imports = [...typeImports(file), ...importTypes(file)];
273
+ sources.set(
274
+ file,
275
+ joined([...imports.map((line) => from(item.declaration, line)), ...lines], "\n"),
276
+ );
277
+ }
209
278
 
210
279
  const header = [
211
280
  ...typeImports(entryFile),
@@ -220,53 +289,58 @@ export const lowerElaboration = (
220
289
  ...(specializer.sdkImports.size
221
290
  ? [`import { ${[...specializer.sdkImports].join(", ")} } from "@tsplc/compiler/clock";`]
222
291
  : []),
292
+ ...(specializer.telemetryImport
293
+ ? [`import { telemetry } from "@tsplc/compiler/telemetry";`]
294
+ : []),
223
295
  ...(specializer.typeImports.size
224
296
  ? [`import { ${[...specializer.typeImports].join(", ")} } from "@tsplc/compiler/types";`]
225
297
  : []),
226
298
  ];
227
299
  sources.set(
228
300
  entryFile,
229
- [
230
- ...header,
231
- ...specializer.tableDeclarations,
232
- ...specializer.routines,
233
- `export function ${entry.export}(): void {`,
234
- ...body,
235
- "}",
236
- ].join("\n"),
301
+ joined(
302
+ [
303
+ ...header.map((line) => from(main, line)),
304
+ ...specializer.tableDeclarations,
305
+ ...specializer.routines,
306
+ from(main, `export function ${entry.export}(): void {`),
307
+ ...body,
308
+ from(closingBrace(main), "}"),
309
+ ],
310
+ "\n",
311
+ ),
237
312
  );
313
+ for (const [name, origin] of specializer.origins) origins.set(`${entryFile}:${name}`, origin);
314
+ for (const { name, members } of specializer.layouts.literalEnums)
315
+ literals.set(`${typesFile}:${name}`, members);
316
+ for (const item of specializer.folded()) {
317
+ const known = constant(item.value, item.iec);
318
+ if (known) folded.push({ path: item.path, ...known, span: positions.node(item.declaration) });
319
+ }
238
320
  // The plain modules now live in the generated code; keep only their types for type importers.
239
321
  for (const source of runtime)
240
322
  if (source.fileName !== entryFile && !isKept(source.fileName))
241
323
  sources.set(
242
324
  source.fileName,
243
- [
244
- ...source.statements
245
- .filter(
246
- (statement) =>
247
- ts.isInterfaceDeclaration(statement) ||
248
- ts.isTypeAliasDeclaration(statement) ||
249
- (ts.isImportDeclaration(statement) && statement.importClause?.isTypeOnly),
250
- )
251
- .map((statement) => statement.getText()),
252
- "export {};",
253
- ].join("\n"),
325
+ joined(
326
+ [
327
+ ...source.statements
328
+ .filter(
329
+ (statement) =>
330
+ ts.isInterfaceDeclaration(statement) ||
331
+ ts.isTypeAliasDeclaration(statement) ||
332
+ (ts.isImportDeclaration(statement) && statement.importClause?.isTypeOnly),
333
+ )
334
+ .map(copied),
335
+ "export {};",
336
+ ],
337
+ "\n",
338
+ ),
254
339
  );
255
340
  } catch (cause) {
256
- if (cause instanceof SpecializeError) {
257
- const start = cause.node.getStart();
258
- const source = cause.node.getSourceFile();
259
- const position = source.getLineAndCharacterOfPosition(start);
260
- diagnostics.push(
261
- error("PLC1010", cause.message, {
262
- file: source.fileName,
263
- start,
264
- end: cause.node.getEnd(),
265
- line: position.line + 1,
266
- column: position.character + 1,
267
- }),
268
- );
269
- } else
341
+ if (cause instanceof SpecializeError)
342
+ diagnostics.push(error("PLC1010", cause.message, positions.node(cause.node)));
343
+ else
270
344
  diagnostics.push(
271
345
  error(
272
346
  "PLC1010",
@@ -278,7 +352,7 @@ export const lowerElaboration = (
278
352
  ),
279
353
  );
280
354
  }
281
- return { sources, diagnostics };
355
+ return result;
282
356
  };
283
357
 
284
358
  const findEntry = (
@@ -87,6 +87,14 @@ export class Layouts {
87
87
  return name;
88
88
  }
89
89
 
90
+ /** Each string-literal union's enum, with the string each member stands for. */
91
+ get literalEnums(): { name: string; members: Record<string, string> }[] {
92
+ return [...this.enums.values()].map((declared) => ({
93
+ name: declared.name,
94
+ members: Object.fromEntries(declared.members.map((member) => [enumMember(member), member])),
95
+ }));
96
+ }
97
+
90
98
  /** Generated enums, which modules import as values. */
91
99
  get enumNames(): string[] {
92
100
  return [...this.declarations]
@@ -10,6 +10,19 @@ export interface Owner {
10
10
  steps: readonly Step[];
11
11
  }
12
12
 
13
+ /** The TypeScript path of an owned object or field, as the program names it: `program.diverters.binTrackers[10]`. */
14
+ export const tsPath = (owner: Owner): string =>
15
+ owner.root.name +
16
+ owner.steps
17
+ .map((step) =>
18
+ step.kind === "index"
19
+ ? `[${step.index}]`
20
+ : /^\d+$/.test(step.name)
21
+ ? `[${step.name}]`
22
+ : `.${step.name}`,
23
+ )
24
+ .join("");
25
+
13
26
  export interface Root {
14
27
  file: string;
15
28
  name: string;