@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, join, relative } from "node:path";
4
4
  import { error, type Diagnostic } from "@tsplc/compiler/ir";
5
+ import { edited, from, mapped, type Edit, type Mapped, type Positions } from "./positions.ts";
5
6
  import {
6
7
  isIntegerType,
7
8
  serviceContract,
@@ -142,9 +143,10 @@ const pascal = (path: string) =>
142
143
  export const lowerServices = (
143
144
  program: ts.Program,
144
145
  sdk: string,
146
+ positions: Positions,
145
147
  options: ServiceOptions | undefined,
146
148
  ) => {
147
- const sources = new Map<string, string>();
149
+ const sources = new Map<string, Mapped>();
148
150
  const diagnostics: Diagnostic[] = [];
149
151
  const records = new Map<string, { name: string; layout: RecordLayout }>();
150
152
  const calls = new Map<string, { contract: ServiceContract; input: string; output: string }>();
@@ -154,20 +156,8 @@ export const lowerServices = (
154
156
  while (value && value.flags & ts.SymbolFlags.Alias) value = checker.getAliasedSymbol(value);
155
157
  return value;
156
158
  };
157
- const fail = (node: ts.Node, code: string, message: string) => {
158
- const source = node.getSourceFile(),
159
- start = node.getStart(source),
160
- position = source.getLineAndCharacterOfPosition(start);
161
- diagnostics.push(
162
- error(code, message, {
163
- file: source.fileName,
164
- start,
165
- end: node.end,
166
- line: position.line + 1,
167
- column: position.character + 1,
168
- }),
169
- );
170
- };
159
+ const fail = (node: ts.Node, code: string, message: string) =>
160
+ diagnostics.push(error(code, message, positions.node(node)));
171
161
  const record = (layout: RecordLayout, name: string) => {
172
162
  const key = recordKey(layout);
173
163
  const existing = records.get(key);
@@ -177,7 +167,8 @@ export const lowerServices = (
177
167
  };
178
168
 
179
169
  const clients = new Map<ts.Symbol, ts.Type>();
180
- let file: string | undefined;
170
+ /** The generated service module, and the first client's creation it stands for. */
171
+ let module: { file: string; client: ts.CallExpression } | undefined;
181
172
  const sourceFiles = runtimeSources(program).filter((source) => !source.isDeclarationFile);
182
173
  for (const source of sourceFiles)
183
174
  for (const statement of source.statements) {
@@ -207,13 +198,13 @@ export const lowerServices = (
207
198
  fail(call, "PLC1013", "HTTP service transport requires server.baseUrlEnv.");
208
199
  else {
209
200
  clients.set(client, checker.getTypeFromTypeNode(router));
210
- file ??= join(dirname(source.fileName), ".tsplc-services.ts");
201
+ module ??= { file: join(dirname(source.fileName), ".tsplc-services.ts"), client: call };
211
202
  }
212
203
  }
213
204
  }
214
205
 
215
206
  for (const source of sourceFiles) {
216
- const edits: { start: number; end: number; text: string }[] = [];
207
+ const edits: Edit[] = [];
217
208
  const imports = new Map<string, string>();
218
209
  const visit = (node: ts.Node): void => {
219
210
  if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) {
@@ -332,20 +323,19 @@ export const lowerServices = (
332
323
  };
333
324
  visit(source);
334
325
  if (!edits.length) continue;
335
- let text = source.text;
336
- for (const edit of edits.sort((a, b) => b.start - a.start))
337
- text = text.slice(0, edit.start) + edit.text + text.slice(edit.end);
338
- if (imports.size && file) {
339
- const path = relative(dirname(source.fileName), file).replaceAll("\\", "/");
340
- text += `\nimport {${[...imports].map(([name, local]) => `${name} as ${local}`).join(",")}} from ${JSON.stringify(path.startsWith("../") ? path : `./${path}`)};\n`;
326
+ let text = edited(source, edits);
327
+ if (imports.size && module) {
328
+ const path = relative(dirname(source.fileName), module.file).replaceAll("\\", "/");
329
+ text = mapped`${text}\nimport {${[...imports].map(([name, local]) => `${name} as ${local}`).join(",")}} from ${JSON.stringify(path.startsWith("../") ? path : `./${path}`)};\n`;
341
330
  }
342
331
  sources.set(source.fileName, text);
343
332
  }
344
- if (file && options) sources.set(file, serviceModule(records, calls, options));
333
+ if (module && options)
334
+ sources.set(module.file, from(module.client, serviceModule(records, calls, options)));
345
335
  return {
346
336
  sources,
347
337
  diagnostics,
348
- file,
338
+ file: module?.file,
349
339
  records: new Map([...records].map(([key, { name }]) => [key, name])),
350
340
  };
351
341
  };
@@ -29,6 +29,9 @@ export function calleeName(node: ts.Expression): ts.MemberName | undefined {
29
29
  return ts.isPropertyAccessExpression(node) ? node.name : undefined;
30
30
  }
31
31
 
32
+ const telemetryMethods = ["capture", "info", "warn", "error", "captureException", "text"] as const;
33
+ type TelemetryMethod = (typeof telemetryMethods)[number];
34
+
32
35
  // This is the sole owner of TypeScript annotation substitution and PLC layouts.
33
36
  // The checker resolves declarations; it never supplies erased numeric widths.
34
37
  // Service records are the exception: `iec.*` schemas carry their widths as literal types.
@@ -77,6 +80,17 @@ export class TypeResolver {
77
80
  : undefined;
78
81
  }
79
82
 
83
+ /** The `@tsplc/compiler/telemetry` method a call names, such as `capture`. */
84
+ telemetryMethod(node: ts.CallExpression): TelemetryMethod | undefined {
85
+ if (!ts.isPropertyAccessExpression(node.expression)) return undefined;
86
+ const symbol = this.checker.getSymbolAtLocation(node.expression.name);
87
+ const declared = symbol?.declarations?.some(
88
+ (declaration) =>
89
+ declaration.getSourceFile().fileName === `${dirname(this.sdk)}/telemetry.d.ts`,
90
+ );
91
+ return declared ? telemetryMethods.find((name) => name === symbol?.name) : undefined;
92
+ }
93
+
80
94
  /** `min`, `max` or `clamp` from the SDK's `@tsplc/compiler/math`. */
81
95
  mathHelper(node: ts.Node, name: string): MathHelper | undefined {
82
96
  return resolve(node.getSourceFile().fileName) ===
@@ -32,7 +32,6 @@ import {
32
32
  type MethodOwner,
33
33
  type PlcModule,
34
34
  type PlcProgram,
35
- type SourceSpan,
36
35
  type Statement,
37
36
  type Variable,
38
37
  type Place,
@@ -45,6 +44,7 @@ import { lowerAsync } from "./async.ts";
45
44
  import { lowerConstFunctions } from "./const-functions.ts";
46
45
  import { lowerElaboration } from "./elaborate/index.ts";
47
46
  import { lowerEnvironment } from "./configuration.ts";
47
+ import { Positions, sourceSpan, type Mapped } from "./positions.ts";
48
48
  import { BlockResolver, storageInitializer, type BlockSource } from "./blocks.ts";
49
49
  import { numericLiteralType } from "./types.ts";
50
50
  import {
@@ -124,23 +124,7 @@ class SemanticError extends Error {
124
124
  }
125
125
  }
126
126
 
127
- function sourceSpan(source: ts.SourceFile, start: number, end: number): SourceSpan {
128
- const position = source.getLineAndCharacterOfPosition(start);
129
- return {
130
- file: source.fileName,
131
- start,
132
- end,
133
- line: position.line + 1,
134
- column: position.character + 1,
135
- };
136
- }
137
-
138
- function span(node: ts.Node): SourceSpan {
139
- const source = node.getSourceFile();
140
- return sourceSpan(source, node.getStart(source), node.getEnd());
141
- }
142
-
143
- function tsDiagnostic(diagnostic: ts.Diagnostic): Diagnostic {
127
+ function tsDiagnostic(diagnostic: ts.Diagnostic, locate = sourceSpan): Diagnostic {
144
128
  const result: Diagnostic = {
145
129
  origin: "typescript",
146
130
  code: `TS${diagnostic.code}`,
@@ -148,7 +132,7 @@ function tsDiagnostic(diagnostic: ts.Diagnostic): Diagnostic {
148
132
  message: ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"),
149
133
  };
150
134
  if (diagnostic.file && diagnostic.start !== undefined)
151
- result.span = sourceSpan(
135
+ result.span = locate(
152
136
  diagnostic.file,
153
137
  diagnostic.start,
154
138
  diagnostic.start + (diagnostic.length ?? 1),
@@ -156,7 +140,7 @@ function tsDiagnostic(diagnostic: ts.Diagnostic): Diagnostic {
156
140
  return result;
157
141
  }
158
142
 
159
- const suppressionDiagnostics = (source: ts.SourceFile): Diagnostic[] => {
143
+ const suppressionDiagnostics = (source: ts.SourceFile, positions: Positions): Diagnostic[] => {
160
144
  const diagnostics: Diagnostic[] = [];
161
145
  const scanner = ts.createScanner(
162
146
  ts.ScriptTarget.Latest,
@@ -180,7 +164,7 @@ const suppressionDiagnostics = (source: ts.SourceFile): Diagnostic[] => {
180
164
  error(
181
165
  "PLC1009",
182
166
  "TypeScript diagnostic suppression is not allowed in PLC source.",
183
- sourceSpan(source, start, start + (match[1]?.length ?? 4)),
167
+ positions.span(source, start, start + (match[1]?.length ?? 4)),
184
168
  ),
185
169
  );
186
170
  }
@@ -231,7 +215,8 @@ export function analyze(options: FrontendOptions): FrontendResult {
231
215
  undefined,
232
216
  filename,
233
217
  );
234
- if (parsed.errors.length) return { diagnostics: parsed.errors.map(tsDiagnostic) };
218
+ if (parsed.errors.length)
219
+ return { diagnostics: parsed.errors.map((diagnostic) => tsDiagnostic(diagnostic)) };
235
220
  const programFiles = Object.values(options.programs).map((entry) =>
236
221
  resolve(dirname(filename), entry.module),
237
222
  );
@@ -272,6 +257,7 @@ export function analyze(options: FrontendOptions): FrontendResult {
272
257
  if (source.fileName.startsWith(dirname(sdk) + "/")) files.add(source);
273
258
  return files;
274
259
  };
260
+ const positions = new Positions();
275
261
  // Only PLC files: a type-only import of the server router brings the server's sources along.
276
262
  const sourceDiagnostics = (program: ts.Program) =>
277
263
  [
@@ -282,7 +268,7 @@ export function analyze(options: FrontendOptions): FrontendResult {
282
268
  ...program.getSyntacticDiagnostics(file),
283
269
  ...program.getSemanticDiagnostics(file),
284
270
  ]),
285
- ].map(tsDiagnostic);
271
+ ].map((diagnostic) => tsDiagnostic(diagnostic, positions.span));
286
272
  const diagnostics = sourceDiagnostics(program);
287
273
  if (
288
274
  program.getSyntacticDiagnostics().some((item) => !item.file || plcFiles(program).has(item.file))
@@ -292,24 +278,25 @@ export function analyze(options: FrontendOptions): FrontendResult {
292
278
  // Lowering also adds modules, such as the service client, that exist only here.
293
279
  let host: ts.CompilerHost = ts.createCompilerHost(compilerOptions);
294
280
  const apply = (lowering: {
295
- sources: Map<string, string>;
281
+ sources: Map<string, Mapped>;
296
282
  diagnostics: Diagnostic[];
297
283
  }): boolean => {
298
284
  diagnostics.push(...lowering.diagnostics);
299
285
  for (const source of runtimeSources(program))
300
286
  if (lowering.sources.has(source.fileName))
301
- diagnostics.push(...suppressionDiagnostics(source));
287
+ diagnostics.push(...suppressionDiagnostics(source, positions));
302
288
  if (lowering.diagnostics.length || (lowering.sources.size && hasErrors(diagnostics)))
303
289
  return false;
304
290
  if (lowering.sources.size) {
305
- for (const [path, text] of lowering.sources) virtualSources.set(path, text);
291
+ positions.record(lowering.sources, program);
292
+ for (const [path, text] of lowering.sources) virtualSources.set(path, text.text);
306
293
  // TSPLC_LOWERED=<directory> writes every generated or rewritten module, as the next step reads it.
307
294
  const dump = process.env.TSPLC_LOWERED;
308
295
  if (dump)
309
296
  for (const [path, text] of lowering.sources) {
310
297
  const target = join(dump, relative(dirname(filename), path));
311
298
  mkdirSync(dirname(target), { recursive: true });
312
- writeFileSync(target, text);
299
+ writeFileSync(target, text.text);
313
300
  }
314
301
  host = ts.createCompilerHost(compilerOptions);
315
302
  const read = host.readFile,
@@ -326,17 +313,23 @@ export function analyze(options: FrontendOptions): FrontendResult {
326
313
  }
327
314
  return true;
328
315
  };
329
- if (!apply(lowerElaboration(program, sdk, options.programs, dirname(filename))))
330
- return { diagnostics };
331
- const services = lowerServices(program, sdk, options.services);
316
+ const elaboration = lowerElaboration(
317
+ program,
318
+ sdk,
319
+ options.programs,
320
+ dirname(filename),
321
+ positions,
322
+ );
323
+ if (!apply(elaboration)) return { diagnostics };
324
+ const services = lowerServices(program, sdk, positions, options.services);
332
325
  if (!apply(services)) return { diagnostics };
333
- const exposure = lowerExposure(program, sdk);
326
+ const exposure = lowerExposure(program, sdk, positions);
334
327
  if (!apply(exposure)) return { diagnostics };
335
- if (!apply(lowerEnvironment(program, sdk))) return { diagnostics };
336
- if (!apply(lowerConstFunctions(program))) return { diagnostics };
337
- const promises = lowerPromises(program, sdk);
328
+ if (!apply(lowerEnvironment(program, sdk, positions))) return { diagnostics };
329
+ if (!apply(lowerConstFunctions(program, positions))) return { diagnostics };
330
+ const promises = lowerPromises(program, sdk, positions);
338
331
  if (!apply(promises)) return { diagnostics };
339
- const lowering = lowerAsync(program, sdk);
332
+ const lowering = lowerAsync(program, sdk, positions);
340
333
  for (const [key, value] of promises.runtimeBlocks) lowering.blocks.set(key, value);
341
334
  if (!apply(lowering)) return { diagnostics };
342
335
  const analyzer = new Analyzer(
@@ -345,17 +338,40 @@ export function analyze(options: FrontendOptions): FrontendResult {
345
338
  dirname(filename),
346
339
  sdk,
347
340
  diagnostics,
341
+ positions,
348
342
  serviceRecords(program, services),
349
343
  );
350
344
  const module = analyzer.run({ ...options.programs, ...lowering.programs });
345
+ // Spans point at the user's files; ids still start with the lowered module they were declared in.
346
+ const declared = (item: { id: string; name: string }) =>
347
+ `${resolve(dirname(filename), item.id.slice(0, item.id.indexOf(":")))}:${item.name}`;
351
348
  for (const variable of module.variables) {
352
- const item = exposure.variables.get(`${variable.span.file}:${variable.name}`);
349
+ const item = exposure.variables.get(declared(variable));
353
350
  if (item) variable.exposure = item;
354
351
  }
352
+ for (const fn of module.functions) {
353
+ const origin = elaboration.origins.get(declared(fn));
354
+ if (origin) fn.origin = origin;
355
+ }
356
+ module.types = module.types.map((type) => {
357
+ const literals =
358
+ type.kind === "enum" &&
359
+ elaboration.literals.get(declared({ id: type.id, name: type.id.split(":").at(-1)! }));
360
+ return type.kind === "enum" && literals
361
+ ? {
362
+ ...type,
363
+ members: type.members.map((member) => ({ ...member, text: literals[member.name] })),
364
+ }
365
+ : type;
366
+ });
355
367
  for (const block of module.blocks) {
356
- const runtime = lowering.blocks.get(`${block.span.file}:${block.name}`);
368
+ const runtime = lowering.blocks.get(declared(block));
357
369
  if (runtime) block.runtime = runtime;
370
+ const job = lowering.jobs.get(declared(block));
371
+ const origin = elaboration.origins.get(declared(block));
372
+ if (job) block.job = origin ? { ...job, ...origin } : job;
358
373
  }
374
+ if (elaboration.folded.length) module.folded = elaboration.folded;
359
375
  for (const entry of module.programs) {
360
376
  const background = lowering.schedules.get(entry.name);
361
377
  if (background) entry.background = background;
@@ -377,7 +393,7 @@ export function checkHostConfig(file: string): readonly Diagnostic[] {
377
393
  skipLibCheck: true,
378
394
  types: [bunTypes],
379
395
  });
380
- return ts.getPreEmitDiagnostics(program).map(tsDiagnostic);
396
+ return ts.getPreEmitDiagnostics(program).map((diagnostic) => tsDiagnostic(diagnostic));
381
397
  }
382
398
 
383
399
  class Analyzer {
@@ -413,15 +429,16 @@ class Analyzer {
413
429
  private readonly root: string,
414
430
  private readonly sdk: string,
415
431
  private readonly diagnostics: Diagnostic[],
432
+ private readonly positions: Positions,
416
433
  serviceRecord?: (type: ts.Type) => ts.Symbol | undefined,
417
434
  ) {
418
435
  this.checker = program.getTypeChecker();
419
436
  this.resolver = new TypeResolver(this.checker, root, sdk, this.fail, serviceRecord);
420
437
  this.blocks = new BlockResolver(
421
438
  this.resolver,
422
- span,
439
+ positions.node,
423
440
  this.fail,
424
- span(program.getSourceFile(sdk)!),
441
+ positions.node(program.getSourceFile(sdk)!),
425
442
  );
426
443
  const roots = new Set(program.getRootFileNames());
427
444
  this.sources = runtimeSources(program).filter(
@@ -434,7 +451,7 @@ class Analyzer {
434
451
  }
435
452
 
436
453
  private readonly fail: Fail = (node, code, message) => {
437
- throw new SemanticError(error(code, message, span(node)));
454
+ throw new SemanticError(error(code, message, this.positions.node(node)));
438
455
  };
439
456
 
440
457
  private type(node: ts.TypeNode): ResolvedType {
@@ -490,7 +507,7 @@ class Analyzer {
490
507
  });
491
508
  }
492
509
  for (const source of this.sources) {
493
- this.diagnostics.push(...suppressionDiagnostics(source));
510
+ this.diagnostics.push(...suppressionDiagnostics(source, this.positions));
494
511
  for (const statement of source.statements) {
495
512
  this.guard(() => this.declaration(statement));
496
513
  }
@@ -862,7 +879,7 @@ class Analyzer {
862
879
  ...(statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)
863
880
  ? { exported: true as const }
864
881
  : {}),
865
- span: span(declaration),
882
+ span: this.positions.node(declaration),
866
883
  };
867
884
  this.variables.set(this.resolver.symbol(declaration.name), variable);
868
885
  this.globalVariables.push(variable);
@@ -972,7 +989,7 @@ class Analyzer {
972
989
  mutable: mode === "inOut",
973
990
  ...(mode && { mode }),
974
991
  retain: false,
975
- span: span(parameter),
992
+ span: this.positions.node(parameter),
976
993
  };
977
994
  });
978
995
  let result: string | undefined;
@@ -997,7 +1014,7 @@ class Analyzer {
997
1014
  parameters,
998
1015
  locals: [],
999
1016
  body: [],
1000
- span: span(node),
1017
+ span: this.positions.node(node),
1001
1018
  ...(result && { result }),
1002
1019
  ...(bounds && { bounds }),
1003
1020
  };
@@ -1110,7 +1127,7 @@ class Analyzer {
1110
1127
  );
1111
1128
  }
1112
1129
  }
1113
- return this.checked({ kind: "constant", type, value, span: span(node) });
1130
+ return this.checked({ kind: "constant", type, value, span: this.positions.node(node) });
1114
1131
  }
1115
1132
 
1116
1133
  private expression(node: ts.Expression, expected?: string): Expression {
@@ -1127,7 +1144,7 @@ class Analyzer {
1127
1144
  }
1128
1145
 
1129
1146
  private rawExpression(node: ts.Expression, expected?: string): Expression {
1130
- const origin = { span: span(node) };
1147
+ const origin = { span: this.positions.node(node) };
1131
1148
  if (node.kind === ts.SyntaxKind.TrueKeyword || node.kind === ts.SyntaxKind.FalseKeyword) {
1132
1149
  return {
1133
1150
  ...origin,
@@ -1344,7 +1361,7 @@ class Analyzer {
1344
1361
  }
1345
1362
 
1346
1363
  private binaryExpression(node: ts.BinaryExpression, expected?: string): Expression {
1347
- const origin = { span: span(node) };
1364
+ const origin = { span: this.positions.node(node) };
1348
1365
  const operator = operators.get(node.operatorToken.kind);
1349
1366
  if (!operator)
1350
1367
  this.fail(
@@ -1388,7 +1405,7 @@ class Analyzer {
1388
1405
  }
1389
1406
 
1390
1407
  private sdkExpression(node: ts.CallExpression, expected?: string): Expression | undefined {
1391
- const origin = { span: span(node) };
1408
+ const origin = { span: this.positions.node(node) };
1392
1409
  const official = this.sdkCall(node);
1393
1410
  if (official === "errorCode") {
1394
1411
  if (node.arguments.length !== 1)
@@ -1593,7 +1610,7 @@ class Analyzer {
1593
1610
  instance: place.root,
1594
1611
  ...(index && { index }),
1595
1612
  inputs,
1596
- span: span(node),
1613
+ span: this.positions.node(node),
1597
1614
  };
1598
1615
  }
1599
1616
 
@@ -1678,13 +1695,18 @@ class Analyzer {
1678
1695
  const target = this.target(value.arguments[0]!);
1679
1696
  if (target.type !== parameter.type)
1680
1697
  this.fail(value, "PLC2001", "Borrowed place type must exactly match its InOut parameter.");
1681
- return { kind: "borrow", place: target.place, type: target.type, span: span(value) };
1698
+ return {
1699
+ kind: "borrow",
1700
+ place: target.place,
1701
+ type: target.type,
1702
+ span: this.positions.node(value),
1703
+ };
1682
1704
  }
1683
1705
  if (this.resolver.types.get(parameter.type)?.kind === "block") {
1684
1706
  const place = this.place(value);
1685
1707
  if (placeType(place, this.resolver.types, this.byId(), this.ranges).type !== parameter.type)
1686
1708
  this.fail(value, "PLC2001", "Pass a block instance of the parameter's type.");
1687
- return { kind: "borrow", place, type: parameter.type, span: span(value) };
1709
+ return { kind: "borrow", place, type: parameter.type, span: this.positions.node(value) };
1688
1710
  }
1689
1711
  return this.reference(this.expression(value, parameter.type), parameter);
1690
1712
  }
@@ -1892,7 +1914,7 @@ class Analyzer {
1892
1914
  }
1893
1915
 
1894
1916
  private statement(node: ts.Statement, locals: Variable[]): Statement[] {
1895
- const origin = { span: span(node) };
1917
+ const origin = { span: this.positions.node(node) };
1896
1918
  if (ts.isBlock(node)) return this.statements(node.statements, locals);
1897
1919
  if (ts.isEmptyStatement(node)) return [];
1898
1920
  if (ts.isIfStatement(node)) {
@@ -1959,6 +1981,8 @@ class Analyzer {
1959
1981
  if (ts.isExpressionStatement(node)) {
1960
1982
  const expression = node.expression;
1961
1983
  if (ts.isCallExpression(expression)) {
1984
+ const telemetry = this.telemetry(expression);
1985
+ if (telemetry) return [telemetry];
1962
1986
  const update = this.update(expression);
1963
1987
  if (update) return [update];
1964
1988
  const call = this.call(expression);
@@ -1992,8 +2016,99 @@ class Analyzer {
1992
2016
  this.fail(node, "PLC1001", `${ts.SyntaxKind[node.kind]} is not supported in PLC scan code.`);
1993
2017
  }
1994
2018
 
2019
+ /** A `@tsplc/compiler/telemetry` call, which the backend encodes as one record (docs/language/telemetry.md). */
2020
+ private telemetry(node: ts.CallExpression): Statement | undefined {
2021
+ const method = this.resolver.telemetryMethod(node);
2022
+ if (!method) return undefined;
2023
+ if (method === "text")
2024
+ this.fail(node, "PLC2001", "telemetry.text is a property value of a telemetry call.");
2025
+ const [first, properties, ...rest] = node.arguments;
2026
+ if (!first || rest.length || node.typeArguments?.length)
2027
+ this.fail(node, "PLC2001", `telemetry.${method} takes one value and optional properties.`);
2028
+ const literal = (label: string): string => {
2029
+ if (!ts.isStringLiteral(first) && !ts.isNoSubstitutionTemplateLiteral(first))
2030
+ this.fail(
2031
+ first,
2032
+ "PLC2001",
2033
+ `telemetry.${method} needs its ${label} as a string literal; put changing values in its properties.`,
2034
+ );
2035
+ return first.text;
2036
+ };
2037
+ let record: Extract<Statement, { kind: "telemetry" }>["record"];
2038
+ switch (method) {
2039
+ case "captureException":
2040
+ record = { kind: "exception", code: this.expression(first, "UDINT") };
2041
+ break;
2042
+ case "capture":
2043
+ record = { kind: "event", event: literal("event name") };
2044
+ break;
2045
+ default:
2046
+ record = { kind: "log", level: method, message: literal("message") };
2047
+ }
2048
+ return {
2049
+ span: this.positions.node(node),
2050
+ kind: "telemetry",
2051
+ record,
2052
+ properties: properties ? this.telemetryProperties(properties) : [],
2053
+ };
2054
+ }
2055
+
2056
+ private telemetryProperties(
2057
+ node: ts.Expression,
2058
+ ): Extract<Statement, { kind: "telemetry" }>["properties"] {
2059
+ if (!ts.isObjectLiteralExpression(node))
2060
+ this.fail(node, "PLC2001", "Telemetry properties are an object literal.");
2061
+ if (node.properties.length > 8)
2062
+ this.fail(node, "PLC2001", "A telemetry call has at most 8 properties.");
2063
+ return node.properties.map((property) => {
2064
+ if (
2065
+ !(ts.isPropertyAssignment(property) || ts.isShorthandPropertyAssignment(property)) ||
2066
+ !ts.isIdentifier(property.name)
2067
+ )
2068
+ this.fail(property, "PLC2001", "Name each telemetry property with an identifier.");
2069
+ const name = property.name.text;
2070
+ const value = ts.isPropertyAssignment(property) ? property.initializer : property.name;
2071
+ if (ts.isCallExpression(value) && this.resolver.telemetryMethod(value) === "text") {
2072
+ const [bytes, length] = value.arguments;
2073
+ if (!bytes || !length || value.arguments.length !== 2)
2074
+ this.fail(value, "PLC2001", "telemetry.text takes a byte array and a length.");
2075
+ const place = this.place(bytes),
2076
+ type = placeType(place, this.resolver.types, this.byId(), this.ranges).type,
2077
+ array = type === undefined ? undefined : this.resolver.types.get(type),
2078
+ element = array?.kind === "array" ? this.resolver.types.get(array.element) : undefined;
2079
+ if (
2080
+ !type ||
2081
+ (element?.kind !== "bits" && element?.kind !== "integer") ||
2082
+ element.bits !== 8
2083
+ )
2084
+ this.fail(bytes, "PLC2001", "telemetry.text reads an array of BYTE.");
2085
+ const counted = this.expression(length);
2086
+ if (!["integer", "bits"].includes(this.resolver.types.get(counted.type)?.kind ?? ""))
2087
+ this.fail(length, "PLC2001", "telemetry.text needs an integer length.");
2088
+ return {
2089
+ name,
2090
+ value: { kind: "borrow", place, type, span: this.positions.node(bytes) },
2091
+ length: counted,
2092
+ };
2093
+ }
2094
+ const expression = this.expression(value);
2095
+ const type = this.resolver.types.get(expression.type);
2096
+ if (
2097
+ !type ||
2098
+ !["bool", "integer", "bits", "float", "enum", "string"].includes(type.kind) ||
2099
+ (type.kind === "string" && type.encoding !== "utf8")
2100
+ )
2101
+ this.fail(
2102
+ value,
2103
+ "PLC2001",
2104
+ `Telemetry property ${name} is ${expression.type}; send BOOL, integers, REAL, LREAL, enums, STRINGs or telemetry.text(bytes, length).`,
2105
+ );
2106
+ return { name, value: expression };
2107
+ });
2108
+ }
2109
+
1995
2110
  private switchStatement(node: ts.SwitchStatement, locals: Variable[]): Statement[] {
1996
- const origin = { span: span(node) };
2111
+ const origin = { span: this.positions.node(node) };
1997
2112
  this.breakTargets.push("switch");
1998
2113
  try {
1999
2114
  const value = this.expression(node.expression);
@@ -2033,7 +2148,7 @@ class Analyzer {
2033
2148
  }
2034
2149
 
2035
2150
  private localDeclarations(node: ts.VariableStatement, locals: Variable[]): Statement[] {
2036
- const origin = { span: span(node) };
2151
+ const origin = { span: this.positions.node(node) };
2037
2152
  if (!(node.declarationList.flags & (ts.NodeFlags.Let | ts.NodeFlags.Const)))
2038
2153
  this.fail(node, "PLC1001", "Use let or const for invocation locals.");
2039
2154
  return node.declarationList.declarations.flatMap((declaration) => {
@@ -2084,7 +2199,7 @@ class Analyzer {
2084
2199
  storage: "local",
2085
2200
  mutable: !(node.declarationList.flags & ts.NodeFlags.Const),
2086
2201
  retain: false,
2087
- span: span(declaration),
2202
+ span: this.positions.node(declaration),
2088
2203
  };
2089
2204
  this.variables.set(this.resolver.symbol(declaration.name), variable);
2090
2205
  locals.push(variable);
@@ -2124,7 +2239,7 @@ class Analyzer {
2124
2239
  storage: "local",
2125
2240
  mutable: true,
2126
2241
  retain: false,
2127
- span: span(declaration),
2242
+ span: this.positions.node(declaration),
2128
2243
  };
2129
2244
  this.variables.set(this.resolver.symbol(declaration.name), counter);
2130
2245
  locals.push(counter);
@@ -2225,7 +2340,7 @@ class Analyzer {
2225
2340
  try {
2226
2341
  return [
2227
2342
  {
2228
- span: span(node),
2343
+ span: this.positions.node(node),
2229
2344
  kind: "for",
2230
2345
  counter: counter.id,
2231
2346
  ...(existing && { counterScope: "existing" as const }),
@@ -2275,8 +2390,13 @@ class Analyzer {
2275
2390
  {
2276
2391
  kind: "assign",
2277
2392
  destination: { root: counter.id, path: [] },
2278
- value: { kind: "constant", type, value: start, span: span(initializer) },
2279
- span: span(node.initializer!),
2393
+ value: {
2394
+ kind: "constant",
2395
+ type,
2396
+ value: start,
2397
+ span: this.positions.node(initializer),
2398
+ },
2399
+ span: this.positions.node(node.initializer!),
2280
2400
  },
2281
2401
  ]
2282
2402
  : [];
@@ -2284,15 +2404,15 @@ class Analyzer {
2284
2404
  kind: "constant",
2285
2405
  type,
2286
2406
  value: { kind: "integer", value: String(finish) },
2287
- span: span(condition.right),
2407
+ span: this.positions.node(condition.right),
2288
2408
  };
2289
2409
  return [
2290
2410
  {
2291
- span: span(node),
2411
+ span: this.positions.node(node),
2292
2412
  kind: "for",
2293
2413
  counter: counter.id,
2294
2414
  ...(existing && { counterScope: "existing" as const }),
2295
- start: { kind: "constant", type, value: start, span: span(initializer) },
2415
+ start: { kind: "constant", type, value: start, span: this.positions.node(initializer) },
2296
2416
  limit,
2297
2417
  step: String(step),
2298
2418
  maxIterations: Number(count),
@@ -2371,7 +2491,7 @@ class Analyzer {
2371
2491
  if (segment.kind === "index" && !this.unchanging(segment.value))
2372
2492
  this.fail(node.expression, "PLC3003", "An iterated array's index must keep its value.");
2373
2493
 
2374
- const origin = { span: span(node) };
2494
+ const origin = { span: this.positions.node(node) };
2375
2495
  const local = (declaration: ts.Node, name: string, type: string): Variable => {
2376
2496
  const variable: Variable = {
2377
2497
  id: this.storageId(declaration, name),
@@ -2380,7 +2500,7 @@ class Analyzer {
2380
2500
  storage: "local",
2381
2501
  mutable: true,
2382
2502
  retain: false,
2383
- span: span(declaration),
2503
+ span: this.positions.node(declaration),
2384
2504
  };
2385
2505
  locals.push(variable);
2386
2506
  return variable;