@tsplc/compiler 0.2.21 → 0.4.0

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 (115) hide show
  1. package/README.md +1 -1
  2. package/dist/cli.js +280 -223
  3. package/dist/cli.js.map +12 -12
  4. package/dist/codesys.js +452 -330
  5. package/dist/codesys.js.map +24 -24
  6. package/dist/elaborate-capture.js +112 -7
  7. package/dist/elaborate-capture.js.map +5 -4
  8. package/dist/index.js +5682 -5407
  9. package/dist/index.js.map +39 -37
  10. package/dist/ir.js +1154 -327
  11. package/dist/ir.js.map +23 -20
  12. package/dist/project.js +68 -29
  13. package/dist/project.js.map +4 -4
  14. package/dist/retain.js +8 -0
  15. package/dist/retain.js.map +10 -0
  16. package/dist/server-check.js +59 -0
  17. package/dist/server-check.js.map +11 -0
  18. package/dist/telemetry.js +19 -10
  19. package/dist/telemetry.js.map +3 -3
  20. package/package.json +33 -12
  21. package/src/codesys/config.ts +1 -1
  22. package/src/codesys/debug.ts +7 -21
  23. package/src/codesys/engineering.ts +8 -12
  24. package/src/codesys/global-lists.ts +19 -17
  25. package/src/codesys/global-names.ts +3 -3
  26. package/src/codesys/http.ts +37 -34
  27. package/src/codesys/index.ts +5 -22
  28. package/src/codesys/instrumentation.ts +3 -1
  29. package/src/codesys/io-paths.ts +2 -1
  30. package/src/codesys/manifest.ts +35 -18
  31. package/src/codesys/numeric.ts +2 -4
  32. package/src/codesys/plan.ts +94 -26
  33. package/src/codesys/publication.ts +4 -3
  34. package/src/codesys/routines.ts +2 -2
  35. package/src/codesys/sources.ts +1 -0
  36. package/src/codesys/st-files.ts +86 -50
  37. package/src/codesys/storage.ts +44 -9
  38. package/src/codesys/task-access.ts +32 -10
  39. package/src/codesys/telemetry.ts +93 -46
  40. package/src/codesys/types.ts +81 -3
  41. package/src/codesys/vendor.ts +1 -1
  42. package/src/frontend/analyzer.ts +15 -14
  43. package/src/frontend/async.ts +23 -21
  44. package/src/frontend/blocks.ts +7 -6
  45. package/src/frontend/configuration.ts +8 -6
  46. package/src/frontend/const-functions.ts +5 -5
  47. package/src/frontend/cooperative.ts +2 -1
  48. package/src/frontend/coroutines.ts +24 -21
  49. package/src/frontend/elaborate/calls.ts +12 -7
  50. package/src/frontend/elaborate/capture-protocol.ts +103 -0
  51. package/src/frontend/elaborate/capture.ts +48 -19
  52. package/src/frontend/elaborate/dialect.ts +2 -2
  53. package/src/frontend/elaborate/expressions.ts +9 -6
  54. package/src/frontend/elaborate/frame.ts +1 -1
  55. package/src/frontend/elaborate/graph.ts +27 -43
  56. package/src/frontend/elaborate/index.ts +52 -17
  57. package/src/frontend/elaborate/initializers.ts +3 -2
  58. package/src/frontend/elaborate/layouts.ts +2 -2
  59. package/src/frontend/elaborate/model.ts +34 -21
  60. package/src/frontend/elaborate/retention.ts +206 -0
  61. package/src/frontend/elaborate/specialize.ts +7 -6
  62. package/src/frontend/elaborate/statements.ts +47 -38
  63. package/src/frontend/elaborate/storage.ts +26 -6
  64. package/src/frontend/exposure.ts +6 -6
  65. package/src/frontend/expressions.ts +26 -25
  66. package/src/frontend/intrinsics.ts +3 -3
  67. package/src/frontend/module-graph.ts +1 -1
  68. package/src/frontend/positions.ts +2 -1
  69. package/src/frontend/promise-chains.ts +1 -0
  70. package/src/frontend/promises.ts +8 -7
  71. package/src/frontend/routines.ts +3 -2
  72. package/src/frontend/sdk.ts +2 -2
  73. package/src/frontend/services.ts +23 -20
  74. package/src/frontend/statements.ts +8 -6
  75. package/src/frontend/tasks.ts +11 -6
  76. package/src/frontend/telemetry.ts +1 -1
  77. package/src/frontend/types.ts +11 -9
  78. package/src/frontend/typescript.ts +92 -42
  79. package/src/index.ts +2 -1
  80. package/src/ir/aggregates.ts +4 -3
  81. package/src/ir/allocation.ts +2 -1
  82. package/src/ir/core-model.ts +38 -8
  83. package/src/ir/declarations.ts +12 -12
  84. package/src/ir/domains.ts +8 -8
  85. package/src/ir/fold.ts +2 -2
  86. package/src/ir/index.ts +53 -40
  87. package/src/ir/job-errors.ts +22 -11
  88. package/src/ir/layouts.ts +3 -2
  89. package/src/ir/link.ts +6 -24
  90. package/src/ir/model.ts +3 -2
  91. package/src/ir/normalization-error.ts +1 -1
  92. package/src/ir/normalize.ts +19 -12
  93. package/src/ir/numeric.ts +1 -0
  94. package/src/{codesys → ir}/operands.ts +2 -6
  95. package/src/ir/ranges.ts +2 -2
  96. package/src/ir/routine.ts +35 -20
  97. package/src/ir/scalars.ts +3 -3
  98. package/src/ir/share.ts +862 -0
  99. package/src/ir/temporaries.ts +236 -0
  100. package/src/ir/types.ts +1 -1
  101. package/src/project/artifacts.ts +12 -2
  102. package/src/project/cli.ts +42 -44
  103. package/src/project/debugger.ts +15 -9
  104. package/src/project/index.ts +1 -1
  105. package/src/project/plant.ts +34 -23
  106. package/src/project/project-commands.ts +92 -73
  107. package/src/project/project.ts +91 -42
  108. package/src/project/release.ts +50 -57
  109. package/src/project/server-check.ts +54 -0
  110. package/src/project/server.ts +60 -41
  111. package/src/project/terminal.ts +3 -1
  112. package/stdlib/retain.ts +2 -0
  113. package/types/globals.d.ts +1 -0
  114. package/types/retain.d.ts +6 -0
  115. package/types/telemetry.d.ts +2 -2
@@ -1,30 +1,27 @@
1
+ // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
1
2
  import {
3
+ type CoreStatement,
4
+ type Deployment,
2
5
  errorName,
6
+ type GeneratedObject,
3
7
  httpErrors,
4
8
  jobErrors,
5
9
  nestedBodies,
6
- type CoreStatement,
7
- type Deployment,
8
- type GeneratedObject,
9
10
  type PlcType,
10
11
  type SourceSpan,
11
12
  type VerifiedCoreModule,
12
13
  } from "@tsplc/compiler/ir";
13
- import {
14
- type Environment,
15
- telemetrySchema,
16
- type ResolvedTelemetryConfig,
17
- } from "@tsplc/config";
14
+ import { type ResolvedTelemetryConfig, telemetrySchema } from "@tsplc/config";
18
15
  import { plcBufferBytes } from "@tsplc/server/wire";
19
16
  import type { CodesysOptions } from "./config.ts";
20
17
  import { blockInstances, type InstancePath } from "./debug.ts";
21
18
  import {
19
+ type HttpEndpoint,
22
20
  httpCertificateVerifier,
23
21
  httpMethods,
24
22
  jsonScalar,
25
23
  nativeHttp,
26
24
  resolveHttpEndpoint,
27
- type HttpEndpoint,
28
25
  } from "./http.ts";
29
26
  import { Sources } from "./sources.ts";
30
27
  import { routineTasks } from "./task-access.ts";
@@ -33,7 +30,7 @@ import { type CodesysTypes, stStringLiteral } from "./types.ts";
33
30
  /** The sender's key in `CodesysPlan.http`, and its HTTP block's id. */
34
31
  export const telemetryClient = "tsplc:telemetry";
35
32
  /** Where each task posts its records, below the server's base URL. */
36
- export const telemetryPath = "/tsplc/telemetry";
33
+ const telemetryPath = "/tsplc/telemetry";
37
34
  /** A sender waits this long for a batch to fill. */
38
35
  const sendIntervalMs = 200;
39
36
  /** The longest task name a batch carries, as the wire allows. */
@@ -49,11 +46,16 @@ interface CallSite {
49
46
  call: TelemetryStatement;
50
47
  }
51
48
 
52
- /** A root job's unhandled failure; its source is that of the step it failed at. */
49
+ /**
50
+ * A root job's unhandled failure; its source is that of the step it failed at. Failures that
51
+ * differ only in their instance share a method, which takes `instance` as its JSON member.
52
+ */
53
53
  interface FailureSite {
54
54
  id: number;
55
55
  task: string;
56
56
  record: string;
57
+ /** The `"instance":…,` member this job passes, or null when its function has no instance. */
58
+ instance: string | null;
57
59
  sources: readonly { source: string; steps: readonly number[] }[];
58
60
  }
59
61
 
@@ -140,7 +142,7 @@ const traceRecord = (operands: number) => ({
140
142
  commitSize,
141
143
  });
142
144
 
143
- export function telemetryCalls(core: VerifiedCoreModule) {
145
+ function telemetryCalls(core: VerifiedCoreModule) {
144
146
  const routines = [
145
147
  ...core.functions,
146
148
  ...core.blocks.filter((block) => !block.standard),
@@ -172,7 +174,7 @@ interface JobFailure {
172
174
  }
173
175
 
174
176
  /** Root jobs own the unhandled record. Awaiting jobs own their children's errors. */
175
- export function planJobFailures(
177
+ function planJobFailures(
176
178
  core: VerifiedCoreModule,
177
179
  tasks: ReadonlyMap<string, string | undefined>,
178
180
  location: (span: SourceSpan) => string,
@@ -244,7 +246,7 @@ export function planTelemetry(
244
246
  telemetry?: ResolvedTelemetryConfig;
245
247
  trace?: { capacity: number; operands: number } | false;
246
248
  server?: { transport: "http" | "opcua"; baseUrlEnv?: string };
247
- env: Environment;
249
+ environment: Readonly<Record<string, string | undefined>>;
248
250
  },
249
251
  report: (message: string, span?: SourceSpan) => void,
250
252
  ): { telemetry?: TelemetryPlan; endpoint?: HttpEndpoint } {
@@ -271,6 +273,7 @@ export function planTelemetry(
271
273
  };
272
274
 
273
275
  const calls = new Map<CoreStatement, CallSite>();
276
+ const recordIds = new Map<string, number>();
274
277
  for (const { routine, call } of statements) {
275
278
  const task = tasks.get(routine);
276
279
  if (!task) {
@@ -298,14 +301,34 @@ export function planTelemetry(
298
301
  (record.kind === "exception" ? codeSize : 0) +
299
302
  commitSize;
300
303
  tooLarge(size, "This telemetry record", call.span);
301
- calls.set(call, { id: calls.size + 1, task, record: prefix, call });
304
+ // Calls that write the same record with the same parameters, such as one call site in
305
+ // several instances, share a method.
306
+ const key = JSON.stringify([
307
+ prefix,
308
+ record.kind,
309
+ call.properties.map(({ name }) => name),
310
+ callParameters(call).map(({ name, value, text }) => [
311
+ name,
312
+ value.type,
313
+ text,
314
+ ]),
315
+ ]);
316
+ const id = recordIds.get(key) ?? recordIds.size + 1;
317
+ recordIds.set(key, id);
318
+ calls.set(call, { id, task, record: prefix, call });
302
319
  }
303
320
 
304
321
  const failures = new Map<string, FailureSite>();
322
+ const failureIds = new Map<string, number>();
305
323
  for (const [block, job] of planJobFailures(core, tasks, location)) {
306
- const record = `{"kind":"exception","handled":false,"function":${asciiJson(job.function)},${job.instance ? `"instance":${asciiJson(job.instance)},` : ""}"properties":{}`;
324
+ const record = `{"kind":"exception","handled":false,"function":${asciiJson(job.function)},`;
325
+ const instance = job.instance
326
+ ? `"instance":${asciiJson(job.instance)},`
327
+ : null;
307
328
  tooLarge(
308
329
  record.length +
330
+ (instance?.length ?? 0) +
331
+ '"properties":{}'.length +
309
332
  codeSize +
310
333
  ',"source":""'.length +
311
334
  maximum(
@@ -317,10 +340,14 @@ export function planTelemetry(
317
340
  `The failure record of ${job.function}`,
318
341
  job.span,
319
342
  );
343
+ const key = JSON.stringify([record, instance !== null, job.sources]);
344
+ const id = failureIds.get(key) ?? failureIds.size + 1;
345
+ failureIds.set(key, id);
320
346
  failures.set(block, {
321
- id: failures.size + 1,
347
+ id,
322
348
  task: job.task,
323
349
  record,
350
+ instance,
324
351
  sources: job.sources,
325
352
  });
326
353
  }
@@ -333,7 +360,7 @@ export function planTelemetry(
333
360
  }
334
361
 
335
362
  const server = project.server;
336
- const base = server?.baseUrlEnv && project.env[server.baseUrlEnv];
363
+ const base = server?.baseUrlEnv && project.environment[server.baseUrlEnv];
337
364
  if (server?.transport === "opcua") {
338
365
  report(
339
366
  `Telemetry posts to the app server's ${telemetryPath} over HTTP; set server.transport to "http".`,
@@ -362,7 +389,7 @@ export function planTelemetry(
362
389
  endpoint: resolveHttpEndpoint(
363
390
  `${base.replace(/\/+$/, "")}${telemetryPath}`,
364
391
  options.http,
365
- project.env,
392
+ project.environment,
366
393
  ),
367
394
  };
368
395
  } catch (cause) {
@@ -384,6 +411,17 @@ export const callParameters = ({ record, properties }: TelemetryStatement) => [
384
411
  : []),
385
412
  ];
386
413
 
414
+ /** The first site of each method id, in id order. */
415
+ function firstOfEach<Site extends { id: number }>(sites: Iterable<Site>) {
416
+ const first = new Map<number, Site>();
417
+ for (const site of sites) {
418
+ if (!first.has(site.id)) {
419
+ first.set(site.id, site);
420
+ }
421
+ }
422
+ return [...first.values()].sort((a, b) => a.id - b.id);
423
+ }
424
+
387
425
  /** The batch header's literal parts, before and after the task's name. */
388
426
  const header = (build: string) => ({
389
427
  start: `{"build":${asciiJson(build)},"task":"`,
@@ -459,7 +497,7 @@ export function telemetryObjects({
459
497
  return jsonScalar(type, parameter)!.code;
460
498
  };
461
499
 
462
- const calls = [...plan.calls.values()].map(({ id, record, call }) => {
500
+ const calls = firstOfEach(plan.calls.values()).map(({ id, record, call }) => {
463
501
  const parameters = callParameters(call);
464
502
  const inputs = parameters.filter((parameter) => !parameter.text);
465
503
  const references = parameters.filter((parameter) => parameter.text);
@@ -497,7 +535,7 @@ export function telemetryObjects({
497
535
  ]
498
536
  .map((line) => `${line}\n`)
499
537
  .join(""),
500
- [
538
+ `${[
501
539
  "payload := '';",
502
540
  `Append(${stStringLiteral(record)});`,
503
541
  ...properties,
@@ -510,30 +548,39 @@ export function telemetryObjects({
510
548
  ]
511
549
  : []),
512
550
  "Commit();",
513
- ].join("\n") + "\n",
551
+ ].join("\n")}\n`,
514
552
  );
515
553
  });
516
554
 
517
- const failures = [...plan.failures.values()].map(({ id, record, sources }) =>
518
- method(
519
- `Failure${id}`,
520
- "VAR_INPUT\n code : UDINT;\n step : UINT;\nEND_VAR\n",
521
- [
522
- "payload := '';",
523
- `Append(${stStringLiteral(`${record},"code":`)});`,
524
- "Append(UDINT_TO_STRING(code));",
525
- "ErrorName(code);",
526
- `Append(',"source":"');`,
527
- "CASE step OF",
528
- ...sources.map(
529
- ({ source, steps }) =>
530
- `${steps.join(", ")}: Append(${stStringLiteral(asciiJson(source).slice(1, -1))});`,
531
- ),
532
- "END_CASE;",
533
- "Append('\"');",
534
- "Commit();",
535
- ].join("\n") + "\n",
536
- ),
555
+ const failures = firstOfEach(plan.failures.values()).map(
556
+ ({ id, record, sources }) => {
557
+ const instances = [...plan.failures.values()].flatMap((failure) =>
558
+ failure.id === id && failure.instance !== null
559
+ ? [failure.instance.length]
560
+ : [],
561
+ );
562
+ return method(
563
+ `Failure${id}`,
564
+ `VAR_INPUT\n code : UDINT;\n step : UINT;\n${instances.length ? ` instance : STRING(${maximum(instances)});\n` : ""}END_VAR\n`,
565
+ `${[
566
+ "payload := '';",
567
+ `Append(${stStringLiteral(record)});`,
568
+ ...(instances.length ? ["Append(instance);"] : []),
569
+ `Append(${stStringLiteral('"properties":{},"code":')});`,
570
+ "Append(UDINT_TO_STRING(code));",
571
+ "ErrorName(code);",
572
+ `Append(',"source":"');`,
573
+ "CASE step OF",
574
+ ...sources.map(
575
+ ({ source, steps }) =>
576
+ `${steps.join(", ")}: Append(${stStringLiteral(asciiJson(source).slice(1, -1))});`,
577
+ ),
578
+ "END_CASE;",
579
+ "Append('\"');",
580
+ "Commit();",
581
+ ].join("\n")}\n`,
582
+ );
583
+ },
537
584
  );
538
585
 
539
586
  const operands = plan.traceOperands;
@@ -543,7 +590,7 @@ export function telemetryObjects({
543
590
  : [
544
591
  method(
545
592
  "Trace",
546
- [
593
+ `${[
547
594
  "VAR_INPUT",
548
595
  " site : UINT;",
549
596
  " value : DINT;",
@@ -553,8 +600,8 @@ export function telemetryObjects({
553
600
  (_, index) => ` operand${index} : DINT;`,
554
601
  ),
555
602
  "END_VAR",
556
- ].join("\n") + "\n",
557
- [
603
+ ].join("\n")}\n`,
604
+ `${[
558
605
  "payload := '';",
559
606
  `Append(${stStringLiteral(traceRecord(operands).prefix)});`,
560
607
  "Append(UINT_TO_STRING(site));",
@@ -568,7 +615,7 @@ export function telemetryObjects({
568
615
  ),
569
616
  "Append(']');",
570
617
  "Commit();",
571
- ].join("\n") + "\n",
618
+ ].join("\n")}\n`,
572
619
  ),
573
620
  ];
574
621
 
@@ -1,5 +1,5 @@
1
- import { instancedBlock, nanosecondsPerMillisecond } from "@tsplc/compiler/ir";
2
1
  import type { Constant, GeneratedObject, PlcType } from "@tsplc/compiler/ir";
2
+ import { instancedBlock, nanosecondsPerMillisecond } from "@tsplc/compiler/ir";
3
3
  import { escapeString } from "@tsplc/iec/st";
4
4
  import { Names } from "./names.ts";
5
5
  import { scalarLiteral } from "./numeric.ts";
@@ -24,18 +24,45 @@ const stEscapes: ReadonlyMap<string, string> = new Map([
24
24
  export const stStringLiteral = (text: string) =>
25
25
  `'${[...text].map((character) => stEscapes.get(character) ?? character).join("")}'`;
26
26
 
27
+ /** A type literal's id: its position and `record`, then any type arguments it was resolved with. */
28
+ const anonymousRecordId = /:\d+:record(<.*>)?$/;
29
+
30
+ const required = <T>(value: T | undefined): T => {
31
+ if (value === undefined) {
32
+ throw new Error("Missing verified type name");
33
+ }
34
+ return value;
35
+ };
36
+
27
37
  export class CodesysTypes {
28
38
  readonly objects: GeneratedObject[] = [];
29
39
  private readonly names = new Map<string, string>();
30
40
  private readonly fields = new Map<string, Map<string, string>>();
41
+ /** Anonymous record types declared by an identical one's DUT. */
42
+ private readonly aliases = new Set<string>();
43
+ private readonly shapes = new Map<string, string | null>();
31
44
 
32
45
  constructor(
33
46
  private readonly types: ReadonlyMap<string, PlcType>,
34
47
  names: Names,
35
48
  blockNames: ReadonlyMap<string, string>,
36
49
  ) {
37
- // Register every type and member name before following layout dependencies.
50
+ // Register every type and member name before following layout dependencies. Anonymous
51
+ // record types with the same fields share one DUT: an elaborated program states such a
52
+ // type once per instance.
53
+ const anonymous = new Map<string, string>();
38
54
  for (const type of types.values()) {
55
+ const shape = this.anonymousShape(type);
56
+ const shared = shape === null ? undefined : anonymous.get(shape);
57
+ if (shared !== undefined) {
58
+ this.names.set(type.id, required(this.names.get(shared)));
59
+ this.fields.set(type.id, required(this.fields.get(shared)));
60
+ this.aliases.add(type.id);
61
+ continue;
62
+ }
63
+ if (shape !== null) {
64
+ anonymous.set(shape, type.id);
65
+ }
39
66
  if (type.kind === "block") {
40
67
  const name = blockNames.get(type.block);
41
68
  if (!name) {
@@ -80,6 +107,7 @@ export class CodesysTypes {
80
107
  if (
81
108
  instancedBlock(type.id, types) ||
82
109
  !this.names.has(type.id) ||
110
+ this.aliases.has(type.id) ||
83
111
  emitted.has(type.id)
84
112
  ) {
85
113
  return;
@@ -102,6 +130,29 @@ export class CodesysTypes {
102
130
  }
103
131
  }
104
132
 
133
+ /**
134
+ * A type literal's structure, which identifies it among anonymous record types, or null for
135
+ * a named or non-record type. Field types are compared by their own shape, so nested literals
136
+ * that match share too.
137
+ */
138
+ private anonymousShape(type: PlcType): string | null {
139
+ if (type.kind !== "record" || !anonymousRecordId.test(type.id)) {
140
+ return null;
141
+ }
142
+ const known = this.shapes.get(type.id);
143
+ if (known !== undefined) {
144
+ return known;
145
+ }
146
+ const shape = JSON.stringify(
147
+ type.fields.map((field) => [
148
+ field.name,
149
+ this.anonymousShape(this.type(field.type)) ?? field.type,
150
+ ]),
151
+ );
152
+ this.shapes.set(type.id, shape);
153
+ return shape;
154
+ }
155
+
105
156
  /** The declaration of a data type's DUT. */
106
157
  private dutDeclaration(type: PlcType, name: string): string {
107
158
  if (type.kind === "record") {
@@ -179,7 +230,34 @@ END_TYPE
179
230
  ) {
180
231
  return "";
181
232
  }
182
- return ` := ${this.literal(value, id)}`;
233
+ return ` := ${this.initializer(value, id)}`;
234
+ }
235
+
236
+ /**
237
+ * A declaration's initial value. A record initializer names only the fields that are not zero,
238
+ * which CODESYS initializes as it would an omitted one; an enum field is always named. A record
239
+ * that is all zero but must still be written, as an element of an array, is written in full.
240
+ */
241
+ private initializer(value: Constant, id: string): string {
242
+ const type = this.type(id);
243
+ if (type.kind === "array" && value.kind === "array") {
244
+ return `[${value.items.map((item) => this.initializer(item, type.element)).join(", ")}]`;
245
+ }
246
+ if (type.kind !== "record" || value.kind !== "record") {
247
+ return this.literal(value, id);
248
+ }
249
+ const fields = type.fields.flatMap((field) => {
250
+ const initial = value.fields[field.name];
251
+ if (!initial) {
252
+ throw new Error("Missing verified record initializer");
253
+ }
254
+ return this.type(field.type).kind !== "enum" && this.isZero(initial)
255
+ ? []
256
+ : [
257
+ `${this.field(id, field.name)} := ${this.initializer(initial, field.type)}`,
258
+ ];
259
+ });
260
+ return fields.length ? `(${fields.join(", ")})` : this.literal(value, id);
183
261
  }
184
262
 
185
263
  private isZero(value: Constant): boolean {
@@ -1,9 +1,9 @@
1
+ import { CodesysCompilerError } from "@tsplc/build";
1
2
  import type {
2
3
  Diagnostic,
3
4
  EmitResult,
4
5
  GeneratedObject,
5
6
  } from "@tsplc/compiler/ir";
6
- import { CodesysCompilerError } from "@tsplc/build";
7
7
  import type { SourceMapping } from "./emit.ts";
8
8
  import { declarationFile } from "./st-files.ts";
9
9
 
@@ -1,34 +1,35 @@
1
- import ts from "typescript";
1
+ // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
2
2
  import { resolve } from "node:path";
3
3
  import {
4
- error,
5
4
  aggregate,
6
5
  type Diagnostic,
6
+ error,
7
7
  type PlcFunction,
8
8
  type PlcModule,
9
9
  type PlcProgram,
10
10
  type Variable,
11
11
  } from "@tsplc/compiler/ir";
12
+ import ts from "typescript";
13
+ import { BlockResolver, storageInitializer } from "./blocks.ts";
14
+ import {
15
+ type AnalysisContext,
16
+ ExpressionLowering,
17
+ type LoweringScope,
18
+ } from "./expressions.ts";
12
19
  import { runtimeSources } from "./module-graph.ts";
13
- import { inSdk, unaliased } from "./sdk.ts";
14
20
  import type { Positions } from "./positions.ts";
15
- import { BlockResolver, storageInitializer } from "./blocks.ts";
21
+ import { methodAccess, RoutineTable } from "./routines.ts";
22
+ import { inSdk, unaliased } from "./sdk.ts";
23
+ import { StatementLowering } from "./statements.ts";
16
24
  import {
17
- SemanticError,
18
- TypeResolver,
25
+ type Fail,
19
26
  hasModifier,
20
27
  numericLiteral,
21
28
  numericLiteralType,
22
- type Fail,
23
29
  type ResolvedType,
30
+ SemanticError,
31
+ TypeResolver,
24
32
  } from "./types.ts";
25
- import { methodAccess, RoutineTable } from "./routines.ts";
26
- import {
27
- ExpressionLowering,
28
- type AnalysisContext,
29
- type LoweringScope,
30
- } from "./expressions.ts";
31
- import { StatementLowering } from "./statements.ts";
32
33
  import type { FrontendOptions } from "./typescript.ts";
33
34
 
34
35
  /** What a module variable's initializer and keyword establish about its storage. */
@@ -1,26 +1,27 @@
1
- import { runtimeSources } from "./module-graph.ts";
2
- import ts from "typescript";
1
+ // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
3
2
  import { resolve } from "node:path";
4
- import { namesSdk, symbolAt } from "./sdk.ts";
5
- import { lowerCoroutine } from "./coroutines.ts";
6
- import { lowerTaskDefinitions } from "./tasks.ts";
7
- import { SemanticError, hasModifier } from "./types.ts";
8
3
  import {
9
- error,
10
4
  type Diagnostic,
5
+ error,
11
6
  type FunctionBlock,
12
7
  type PlcProgram,
13
8
  } from "@tsplc/compiler/ir";
9
+ import ts from "typescript";
10
+ import { lowerCoroutine } from "./coroutines.ts";
11
+ import { runtimeSources } from "./module-graph.ts";
14
12
  import {
13
+ type Edit,
15
14
  edited,
16
15
  from,
17
16
  joined,
18
- mapped,
19
- slice,
20
- type Edit,
21
17
  type Mapped,
18
+ mapped,
22
19
  type Positions,
20
+ slice,
23
21
  } from "./positions.ts";
22
+ import { namesSdk, symbolAt } from "./sdk.ts";
23
+ import { lowerTaskDefinitions } from "./tasks.ts";
24
+ import { hasModifier, SemanticError } from "./types.ts";
24
25
 
25
26
  export type Job = NonNullable<FunctionBlock["job"]>;
26
27
  /** A named async function or method. */
@@ -161,10 +162,10 @@ function asyncRoutines(
161
162
  if (ts.isMethodDeclaration(fn)) {
162
163
  const prefix = `tsplcAsync${fn.name.getText(source)}${fn.getStart(source)}`;
163
164
  methods.set(symbol(fn.name)!, {
164
- start: prefix + "Start",
165
- reset: prefix + "Reset",
166
- snapshot: prefix + "Snapshot",
167
- advance: prefix + "Advance",
165
+ start: `${prefix}Start`,
166
+ reset: `${prefix}Reset`,
167
+ snapshot: `${prefix}Snapshot`,
168
+ advance: `${prefix}Advance`,
168
169
  });
169
170
  }
170
171
  }
@@ -257,15 +258,16 @@ function addInstanceEntries(
257
258
  return;
258
259
  }
259
260
  const name = declaration.name.text;
260
- for (const poll of polls ?? []) {
261
+ // One entry polls all of an instance's sites, in their order: they share its task.
262
+ if (polls?.length) {
261
263
  const entry = `tsplcContinuation${context.sequence()}`;
264
+ const calls = polls.map((poll) =>
265
+ instance.first === undefined
266
+ ? `${name}.${poll}();`
267
+ : `for(let element:DINT=${instance.first};element<=${instance.last};element++){${name}[element].${poll}();}`,
268
+ );
262
269
  entries.push(
263
- from(
264
- node,
265
- instance.first === undefined
266
- ? `export function ${entry}():void{${name}.${poll}();}`
267
- : `export function ${entry}():void{for(let element:DINT=${instance.first};element<=${instance.last};element++){${name}[element].${poll}();}}`,
268
- ),
270
+ from(node, `export function ${entry}():void{${calls.join("")}}`),
269
271
  );
270
272
  result.programs[entry] = {
271
273
  module: resolve(source.fileName),
@@ -1,19 +1,20 @@
1
- import ts from "typescript";
1
+ // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
2
2
  import {
3
3
  aggregate,
4
4
  defaultValue,
5
+ type FunctionBlock,
5
6
  instancedBlock,
6
- standardBlocks,
7
+ type PlcType,
8
+ type SourceSpan,
7
9
  type StandardBlock,
8
- type FunctionBlock,
10
+ standardBlocks,
9
11
  type Variable,
10
- type SourceSpan,
11
- type PlcType,
12
12
  } from "@tsplc/compiler/ir";
13
+ import ts from "typescript";
13
14
  import {
14
15
  calleeName,
15
- numericLiteralType,
16
16
  type Fail,
17
+ numericLiteralType,
17
18
  type TypeResolver,
18
19
  } from "./types.ts";
19
20
 
@@ -1,15 +1,15 @@
1
- import { runtimeSources } from "./module-graph.ts";
1
+ import { type Diagnostic, error } from "@tsplc/compiler/ir";
2
2
  import ts from "typescript";
3
+ import { runtimeSources } from "./module-graph.ts";
4
+ import { type Edit, edited, type Mapped, type Positions } from "./positions.ts";
3
5
  import { namesSdk, symbolAt } from "./sdk.ts";
4
- import { error, type Diagnostic } from "@tsplc/compiler/ir";
5
- import { edited, type Edit, type Mapped, type Positions } from "./positions.ts";
6
- import type { Environment } from "@tsplc/config";
6
+ import type { CompileEnvironment } from "./typescript.ts";
7
7
 
8
8
  export const lowerEnvironment = (
9
9
  program: ts.Program,
10
10
  sdk: string,
11
11
  positions: Positions,
12
- env: Environment,
12
+ environment: CompileEnvironment,
13
13
  ) => {
14
14
  const checker = program.getTypeChecker();
15
15
  const sources = new Map<string, Mapped>();
@@ -39,7 +39,9 @@ export const lowerEnvironment = (
39
39
  ts.isVariableStatement(owner.parent.parent) &&
40
40
  ts.isSourceFile(owner.parent.parent.parent);
41
41
  const value =
42
- name && ts.isStringLiteral(name) ? env[name.text] : undefined;
42
+ name && ts.isStringLiteral(name)
43
+ ? environment[name.text]
44
+ : undefined;
43
45
  let message: string | undefined;
44
46
  if (
45
47
  !moduleConst ||
@@ -1,14 +1,14 @@
1
- import { runtimeSources } from "./module-graph.ts";
1
+ import { type Diagnostic, error } from "@tsplc/compiler/ir";
2
2
  import ts from "typescript";
3
- import { error, type Diagnostic } from "@tsplc/compiler/ir";
3
+ import { runtimeSources } from "./module-graph.ts";
4
4
  import {
5
5
  copied,
6
+ type Edit,
6
7
  edited,
7
8
  from,
8
9
  joined,
9
- mapped,
10
- type Edit,
11
10
  type Mapped,
11
+ mapped,
12
12
  type Part,
13
13
  type Positions,
14
14
  } from "./positions.ts";
@@ -131,7 +131,7 @@ export const lowerConstFunctions = (
131
131
  signature &&
132
132
  Boolean(
133
133
  checker.getReturnTypeOfSignature(signature).flags &
134
- ts.TypeFlags.Void,
134
+ ts.TypeFlags.Void,
135
135
  );
136
136
  const inferredResult =
137
137
  signature &&
@@ -1,3 +1,4 @@
1
+ import { jobError } from "@tsplc/compiler/ir";
1
2
  import { mapped, type Part } from "./positions.ts";
2
3
 
3
4
  interface Parameter {
@@ -89,7 +90,7 @@ export const taskSite = (
89
90
  ${worker.declaration}
90
91
  public ${method("start")}(${signature}):BOOL{const accepted:BOOL=${worker.start}(${args});if(accepted){${cancelled}=false;${worker.advance}({cancel:false});}return accepted;}
91
92
  public ${method("cancel")}():BOOL{const state=${worker.snapshot}();if(!state.busy&&!state.done)return false;${cancelled}=true;return true;}
92
- public ${method("snapshot")}():{valid:BOOL;busy:BOOL;done:BOOL;cancelRequested:BOOL;error:UDINT;result:${value.type}}{const state=${worker.snapshot}();if(${cancelled}&&state.done)return {valid:true,busy:false,done:true,cancelRequested:false,error:1,result:defaultValue<${value.type}>()};return {valid:true,busy:state.busy,done:state.done,cancelRequested:${cancelled},error:state.error,result:${result}};}
93
+ public ${method("snapshot")}():{valid:BOOL;busy:BOOL;done:BOOL;cancelRequested:BOOL;error:UDINT;result:${value.type}}{const state=${worker.snapshot}();if(${cancelled}&&state.done)return {valid:true,busy:false,done:true,cancelRequested:false,error:${jobError.cancelled},result:defaultValue<${value.type}>()};return {valid:true,busy:state.busy,done:state.done,cancelRequested:${cancelled},error:state.error,result:${result}};}
93
94
  public ${method("reset")}():BOOL{const state=${worker.snapshot}();if(state.busy)return false;${worker.reset}();${cancelled}=false;return true;}
94
95
  public ${method("poll")}():void{${worker.advance}({cancel:${cancelled}});}`;
95
96
  return {