@tsplc/compiler 0.5.5 → 0.5.7

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 (80) hide show
  1. package/dist/bun-runtime.js +152 -31
  2. package/dist/bun-runtime.js.map +10 -9
  3. package/dist/cli.js +8 -5
  4. package/dist/cli.js.map +3 -3
  5. package/dist/codesys.js +260 -85
  6. package/dist/codesys.js.map +9 -9
  7. package/dist/collections.js +395 -0
  8. package/dist/collections.js.map +10 -0
  9. package/dist/elaborate-capture.js +62 -4
  10. package/dist/elaborate-capture.js.map +4 -4
  11. package/dist/index.js +5322 -1058
  12. package/dist/index.js.map +30 -23
  13. package/dist/ir.js +122 -1
  14. package/dist/ir.js.map +6 -6
  15. package/dist/project.js +8 -5
  16. package/dist/project.js.map +3 -3
  17. package/package.json +14 -9
  18. package/src/codesys/emit.ts +8 -2
  19. package/src/codesys/http.ts +114 -72
  20. package/src/codesys/instrumentation.ts +30 -6
  21. package/src/codesys/numeric.ts +61 -0
  22. package/src/codesys/routines.ts +39 -9
  23. package/src/codesys/st-files.ts +73 -6
  24. package/src/codesys/telemetry.ts +70 -35
  25. package/src/frontend/control-flow.ts +752 -0
  26. package/src/frontend/coroutines.ts +171 -7
  27. package/src/frontend/elaborate/array-searches.ts +216 -0
  28. package/src/frontend/elaborate/assignments.ts +352 -0
  29. package/src/frontend/elaborate/calls.ts +467 -42
  30. package/src/frontend/elaborate/capture-protocol.ts +19 -0
  31. package/src/frontend/elaborate/capture.ts +80 -2
  32. package/src/frontend/elaborate/dialect.ts +116 -2
  33. package/src/frontend/elaborate/expressions.ts +927 -80
  34. package/src/frontend/elaborate/filtered-arrays.ts +607 -0
  35. package/src/frontend/elaborate/frame.ts +44 -1
  36. package/src/frontend/elaborate/generics.ts +137 -0
  37. package/src/frontend/elaborate/graph.ts +91 -0
  38. package/src/frontend/elaborate/index.ts +30 -5
  39. package/src/frontend/elaborate/initializers.ts +15 -1
  40. package/src/frontend/elaborate/iterators.ts +1677 -0
  41. package/src/frontend/elaborate/layouts.ts +41 -19
  42. package/src/frontend/elaborate/model.ts +64 -8
  43. package/src/frontend/elaborate/references.ts +749 -0
  44. package/src/frontend/elaborate/specialize.ts +459 -29
  45. package/src/frontend/elaborate/statements.ts +552 -133
  46. package/src/frontend/elaborate/storage.ts +151 -10
  47. package/src/frontend/elaborate/values.ts +72 -0
  48. package/src/frontend/elaborate/writes.ts +302 -1
  49. package/src/frontend/intrinsics.ts +32 -0
  50. package/src/frontend/module-graph.ts +2 -1
  51. package/src/frontend/positions.ts +12 -5
  52. package/src/frontend/typescript.ts +5 -1
  53. package/src/ir/core-model.ts +2 -6
  54. package/src/ir/fold.ts +30 -1
  55. package/src/ir/index.ts +5 -0
  56. package/src/ir/model.ts +53 -2
  57. package/src/ir/scalars.ts +126 -0
  58. package/src/runtime/.runtime-VaUSOu/server/router.ts +17 -0
  59. package/src/runtime/.runtime-VaUSOu/src/cell.ts +45 -0
  60. package/src/runtime/.runtime-VaUSOu/src/controller.ts +58 -0
  61. package/src/runtime/.runtime-VaUSOu/src/lane.ts +6 -0
  62. package/src/runtime/.runtime-VaUSOu/src/main.ts +11 -0
  63. package/src/runtime/.runtime-VaUSOu/src/services.ts +8 -0
  64. package/src/runtime/.runtime-VaUSOu/tsconfig.json +13 -0
  65. package/src/runtime/.runtime-VaUSOu/tsplc.config.ts +31 -0
  66. package/src/runtime/.runtime-ybIxYh/server/router.ts +17 -0
  67. package/src/runtime/.runtime-ybIxYh/src/cell.ts +45 -0
  68. package/src/runtime/.runtime-ybIxYh/src/controller.ts +58 -0
  69. package/src/runtime/.runtime-ybIxYh/src/lane.ts +6 -0
  70. package/src/runtime/.runtime-ybIxYh/src/main.ts +11 -0
  71. package/src/runtime/.runtime-ybIxYh/src/services.ts +8 -0
  72. package/src/runtime/.runtime-ybIxYh/tsconfig.json +13 -0
  73. package/src/runtime/.runtime-ybIxYh/tsplc.config.ts +31 -0
  74. package/src/runtime/async.ts +15 -12
  75. package/src/runtime/launch.ts +11 -4
  76. package/src/runtime/runtime.ts +26 -23
  77. package/src/runtime/telemetry.ts +14 -6
  78. package/src/runtime/transport.ts +172 -0
  79. package/stdlib/collections.ts +514 -0
  80. package/types/index.d.ts +18 -0
@@ -2,10 +2,12 @@ import {
2
2
  type Constant,
3
3
  type CoreExpression,
4
4
  type CoreStatement,
5
+ type ElementaryFunction,
5
6
  floatMaximum,
6
7
  type GeneratedObject,
7
8
  integerRange,
8
9
  integerType,
10
+ isElementary,
9
11
  nestedBodies,
10
12
  type PlcType,
11
13
  pathIndexes,
@@ -13,6 +15,20 @@ import {
13
15
  subexpressions,
14
16
  } from "@tsplc/compiler/ir";
15
17
 
18
+ /** The Structured Text function each elementary function is. */
19
+ const elementaryNames: Readonly<Record<ElementaryFunction, string>> = {
20
+ sqrt: "SQRT",
21
+ ln: "LN",
22
+ log10: "LOG",
23
+ exp: "EXP",
24
+ sin: "SIN",
25
+ cos: "COS",
26
+ tan: "TAN",
27
+ asin: "ASIN",
28
+ acos: "ACOS",
29
+ atan: "ATAN",
30
+ };
31
+
16
32
  const operatorTokens: Readonly<Record<string, string>> = {
17
33
  add: "+",
18
34
  subtract: "-",
@@ -66,6 +82,9 @@ export class NumericLowering {
66
82
  if (value.kind === "convert" && value.policy === "saturate") {
67
83
  this.saturation(value.operand.type, value.type);
68
84
  }
85
+ if (value.kind === "unary" && value.operator === "truncate") {
86
+ this.truncation(value.type);
87
+ }
69
88
  }
70
89
 
71
90
  prepareStatements(items: readonly CoreStatement[]): void {
@@ -100,6 +119,12 @@ export class NumericLowering {
100
119
  if (value.operator === "clock") {
101
120
  return "TO_DINT(TIME_TO_UDINT(TIME()))";
102
121
  }
122
+ if (isElementary(value.operator)) {
123
+ return `${elementaryNames[value.operator]}(${operands[0]})`;
124
+ }
125
+ if (value.operator === "truncate") {
126
+ return `${this.truncation(value.type)}(${operands[0]})`;
127
+ }
103
128
  return value.operator === "not"
104
129
  ? `(NOT ${operands[0]})`
105
130
  : `TO_${value.type}(${value.operator === "negate" ? "-" : "NOT "}${operands[0]})`;
@@ -110,6 +135,9 @@ export class NumericLowering {
110
135
  if (value.policy) {
111
136
  return `${this.arithmetic(value.type, value.operator, value.policy)}(${operands.join(", ")})`;
112
137
  }
138
+ if (value.operator === "power") {
139
+ return `EXPT(${operands.join(", ")})`;
140
+ }
113
141
  if (value.operator === "shiftLeft" || value.operator === "shiftRight") {
114
142
  const shift = value.operator === "shiftLeft" ? "SHL" : "SHR";
115
143
  return `TO_${value.type}(${shift}(${operands.join(", ")}))`;
@@ -346,6 +374,39 @@ END_IF;
346
374
  );
347
375
  }
348
376
 
377
+ /**
378
+ * A float toward zero, as a float. TRUNC returns DINT, so the whole part goes through LINT, which
379
+ * holds every float below the size where each float is already whole; those stay as they are.
380
+ */
381
+ private truncation(typeId: string): string {
382
+ const type = this.types.get(typeId);
383
+ if (type?.kind !== "float") {
384
+ throw new Error("Expected verified float truncation");
385
+ }
386
+ const whole = scalarLiteral(
387
+ { kind: "float", value: 2 ** (type.bits === 32 ? 23 : 52) },
388
+ typeId,
389
+ );
390
+ return this.helper(
391
+ `truncate_${typeId}`,
392
+ typeId,
393
+ [["value", typeId]],
394
+ (name) => `IF ABS(value) >= ${whole} THEN
395
+ ${name} := value;
396
+ RETURN;
397
+ END_IF;
398
+ nearest := TO_LINT(value);
399
+ IF value >= 0 AND TO_${typeId}(nearest) > value THEN
400
+ nearest := nearest - 1;
401
+ ELSIF value < 0 AND TO_${typeId}(nearest) < value THEN
402
+ nearest := nearest + 1;
403
+ END_IF;
404
+ ${name} := TO_${typeId}(nearest);
405
+ `,
406
+ " nearest : LINT;",
407
+ );
408
+ }
409
+
349
410
  private saturation(sourceId: string, targetId: string): string {
350
411
  const source = this.types.get(sourceId);
351
412
  const target = this.types.get(targetId);
@@ -1,5 +1,6 @@
1
1
  import {
2
2
  type Constant,
3
+ type CoreExpression,
3
4
  type CoreFunction,
4
5
  type CoreFunctionBlock,
5
6
  type CoreStatement,
@@ -181,6 +182,23 @@ export function emitRoutine(
181
182
  }
182
183
  };
183
184
 
185
+ const assignResult = (
186
+ destination: string,
187
+ value: CoreExpression,
188
+ depth: number,
189
+ span: SourceSpan,
190
+ ): void => {
191
+ if (value.kind === "constant") {
192
+ assignConstant(destination, value.value, value.type, depth, span);
193
+ } else {
194
+ write(
195
+ `${destination} := ${expressionText(storage, value)};`,
196
+ depth,
197
+ span,
198
+ );
199
+ }
200
+ };
201
+
184
202
  const tracked = block && instrumentation.fields.get(block.id);
185
203
  const body = (items: readonly CoreStatement[], depth: number): void => {
186
204
  for (const item of items) {
@@ -406,8 +424,19 @@ export function emitRoutine(
406
424
  case "return":
407
425
  writeProbes(probes, write, item, depth);
408
426
  if (block) {
409
- if (item.value) {
410
- const returned = expressionText(storage, item.value);
427
+ const { value } = item;
428
+ if (value?.kind === "constant" && value.value.kind === "record") {
429
+ for (const output of block.outputs) {
430
+ assignConstant(
431
+ storageName(storage, output.id),
432
+ required(value.value.fields[output.name]),
433
+ output.type,
434
+ depth,
435
+ item.span,
436
+ );
437
+ }
438
+ } else if (value) {
439
+ const returned = expressionText(storage, value);
411
440
  for (const output of block.outputs) {
412
441
  write(
413
442
  `${storageName(storage, output.id)} := ${returned}.${targetTypes.field(required(block.result), output.name)};`,
@@ -418,18 +447,19 @@ export function emitRoutine(
418
447
  }
419
448
  } else if (program) {
420
449
  if (item.value) {
421
- write(
422
- `${required(symbols.programResults.get(fn.id))} := ${expressionText(storage, item.value)};`,
450
+ assignResult(
451
+ required(symbols.programResults.get(fn.id)),
452
+ item.value,
423
453
  depth,
424
454
  item.span,
425
455
  );
426
456
  }
427
457
  } else if (!method || fn.result) {
428
- write(
429
- `${name} := ${item.value ? expressionText(storage, item.value) : "TRUE"};`,
430
- depth,
431
- item.span,
432
- );
458
+ if (item.value) {
459
+ assignResult(name, item.value, depth, item.span);
460
+ } else {
461
+ write(`${name} := TRUE;`, depth, item.span);
462
+ }
433
463
  }
434
464
  if (mutex) {
435
465
  release(mutex, depth, item.span);
@@ -129,17 +129,84 @@ function objectPaths(
129
129
  );
130
130
  return `${objectPath(owner)}/methods/${object.name}`;
131
131
  }
132
+ const folders = required(placed.get(object));
133
+ return [folderPath(folders), object.name].filter(Boolean).join("/");
134
+ };
135
+ const placedFolders = (object: GeneratedObject): string[] => {
132
136
  const folders = sourceFolders(plan.project.root, sourceModule(object));
133
137
  if (!folders) {
134
- return `${generatedFolder(object)}/${object.name}`;
138
+ return [generatedFolder(object)];
135
139
  }
136
140
  // A DUT directory can also contain sibling input/output layouts. Keep
137
141
  // that directory for every DUT, or its primary type would block the folder.
138
- const kept =
139
- object.kind !== "dataType" && folders.at(-1) === object.name
140
- ? folders.slice(0, -1)
141
- : folders;
142
- return [...kept, object.name].join("/");
142
+ return object.kind !== "dataType" && folders.at(-1) === object.name
143
+ ? folders.slice(0, -1)
144
+ : folders;
143
145
  };
146
+ const placed = new Map(
147
+ objects
148
+ .filter((object) => object.kind !== "method")
149
+ .map((object) => [object, placedFolders(object)]),
150
+ );
151
+ const folderPath = separatedFolders(
152
+ [...placed].map(([object, folders]) => ({ folders, name: object.name })),
153
+ );
144
154
  return objectPath;
145
155
  }
156
+
157
+ /**
158
+ * Each folder's path once no folder shares its name with an object beside it. CODESYS refuses that,
159
+ * ignoring case, as when a module's folder is named like an object another module places next to it:
160
+ * the folder takes the next free numbered name. Folders only organize the project, so no IEC name changes.
161
+ */
162
+ export function separatedFolders(
163
+ objects: readonly { folders: readonly string[]; name: string }[],
164
+ ): (folders: readonly string[]) => string {
165
+ const childrenOf = (entries: Iterable<readonly [string, string]>) => {
166
+ const children = new Map<string, Set<string>>();
167
+ for (const [parent, name] of entries) {
168
+ const names = children.get(parent) ?? new Set<string>();
169
+ names.add(name.toLowerCase());
170
+ children.set(parent, names);
171
+ }
172
+ return (parent: string) => children.get(parent) ?? new Set<string>();
173
+ };
174
+ const objectsIn = childrenOf(
175
+ objects.map(({ folders, name }) => [folders.join("/"), name] as const),
176
+ );
177
+ const foldersIn = childrenOf(
178
+ objects.flatMap(({ folders }) =>
179
+ folders.map((name, depth) => [folders.slice(0, depth).join("/"), name]),
180
+ ),
181
+ );
182
+ const renamed = new Map<string, string>();
183
+ const given = new Map<string, Set<string>>();
184
+ const folderPath = (folders: readonly string[]): string => {
185
+ const key = folders.join("/");
186
+ const known = renamed.get(key);
187
+ if (known !== undefined) {
188
+ return known;
189
+ }
190
+ if (folders.length === 0) {
191
+ return "";
192
+ }
193
+ const parentKey = folders.slice(0, -1).join("/");
194
+ const name = required(folders.at(-1));
195
+ const taken = given.get(parentKey) ?? new Set<string>();
196
+ given.set(parentKey, taken);
197
+ const blocked = (candidate: string) =>
198
+ objectsIn(parentKey).has(candidate.toLowerCase()) ||
199
+ taken.has(candidate.toLowerCase()) ||
200
+ (candidate !== name && foldersIn(parentKey).has(candidate.toLowerCase()));
201
+ const free = (count: number): string =>
202
+ blocked(`${name}_${count}`) ? free(count + 1) : `${name}_${count}`;
203
+ const chosen = blocked(name) ? free(2) : name;
204
+ taken.add(chosen.toLowerCase());
205
+ const path = [folderPath(folders.slice(0, -1)), chosen]
206
+ .filter(Boolean)
207
+ .join("/");
208
+ renamed.set(key, path);
209
+ return path;
210
+ };
211
+ return folderPath;
212
+ }
@@ -21,6 +21,7 @@ import {
21
21
  httpMethods,
22
22
  jsonScalar,
23
23
  nativeHttp,
24
+ opcuaClient,
24
25
  resolveHttpEndpoint,
25
26
  } from "./http";
26
27
  import { Sources } from "./sources";
@@ -361,11 +362,31 @@ export function planTelemetry(
361
362
 
362
363
  const server = project.server;
363
364
  const base = server?.baseUrlEnv && project.environment[server.baseUrlEnv];
365
+ const plan: TelemetryPlan = {
366
+ ...settings,
367
+ // One ring per task holds the trace too.
368
+ capacity: Math.max(
369
+ settings.capacity,
370
+ project.trace ? project.trace.capacity : 0,
371
+ ),
372
+ calls,
373
+ failures,
374
+ ...(project.trace && { traceOperands: project.trace.operands }),
375
+ };
364
376
  if (server?.transport === "opcua") {
365
- report(
366
- `Telemetry posts to the app server's ${telemetryPath} over HTTP; set server.transport to "http".`,
367
- );
368
- return {};
377
+ return {
378
+ telemetry: plan,
379
+ endpoint: {
380
+ transport: "opcua",
381
+ host: "",
382
+ port: 0,
383
+ authority: "",
384
+ path: telemetryPath,
385
+ token: "",
386
+ timeoutMs: options.http.timeoutMs,
387
+ tls: false,
388
+ },
389
+ };
369
390
  }
370
391
  if (!base) {
371
392
  report(
@@ -375,17 +396,7 @@ export function planTelemetry(
375
396
  }
376
397
  try {
377
398
  return {
378
- telemetry: {
379
- ...settings,
380
- // One ring per task holds the trace too.
381
- capacity: Math.max(
382
- settings.capacity,
383
- project.trace ? project.trace.capacity : 0,
384
- ),
385
- calls,
386
- failures,
387
- ...(project.trace && { traceOperands: project.trace.operands }),
388
- },
399
+ telemetry: plan,
389
400
  endpoint: resolveHttpEndpoint(
390
401
  `${base.replace(/\/+$/, "")}${telemetryPath}`,
391
402
  options.http,
@@ -452,20 +463,23 @@ const batchRecords = (recordBytes: number) => {
452
463
  * shared `Trace`, and a body each scan runs first that counts the scan, reads the clock and
453
464
  * sends. It encodes with the HTTP blocks' JSON methods, and sends through a native HTTP block.
454
465
  */
466
+ /** How the sender reaches the server: its HTTP client's endpoint and network, or the OPC UA slots it posts through. */
467
+ export type TelemetryTransport =
468
+ | { kind: "http"; endpoint: HttpEndpoint; network: string }
469
+ | { kind: "opcua"; timeoutMs: number; rpcGlobal: string };
470
+
455
471
  export function telemetryObjects({
456
472
  plan,
457
473
  names,
458
474
  target,
459
- endpoint,
460
- network,
475
+ transport,
461
476
  build,
462
477
  types,
463
478
  }: {
464
479
  plan: TelemetryPlan;
465
480
  names: { writer: string; record: string; client: string };
466
481
  target: CodesysTypes;
467
- endpoint: HttpEndpoint;
468
- network: string;
482
+ transport: TelemetryTransport;
469
483
  build: string;
470
484
  types: ReadonlyMap<string, PlcType>;
471
485
  }): GeneratedObject[] {
@@ -623,18 +637,42 @@ export function telemetryObjects({
623
637
  const helpers = httpMethods(writer).filter((item) =>
624
638
  ["ByteLength", "Append", "WriteString"].includes(item.name),
625
639
  );
626
- const [client, ...clientLifecycle] = nativeHttp({
627
- id: telemetryClient,
628
- name: names.client,
629
- ports: `VAR_INPUT\nstart : BOOL;\ncancel : BOOL;\nEND_VAR\nVAR_IN_OUT\nbody : STRING(${plcBufferBytes});\nEND_VAR\nVAR_OUTPUT\nbusy : BOOL;\ndone : BOOL;\nerror : UDINT;\nEND_VAR`,
630
- port: (label) => label,
631
- endpoint,
632
- network,
633
- method: "POST",
634
- json: true,
635
- body: "Append(body);",
636
- decode: "",
637
- });
640
+ const clientPorts = `VAR_INPUT\nstart : BOOL;\ncancel : BOOL;\nEND_VAR\nVAR_IN_OUT\nbody : STRING(${plcBufferBytes});\nEND_VAR\nVAR_OUTPUT\nbusy : BOOL;\ndone : BOOL;\nerror : UDINT;\nEND_VAR`;
641
+ const clientObjects =
642
+ transport.kind === "opcua"
643
+ ? [
644
+ opcuaClient({
645
+ id: telemetryClient,
646
+ name: names.client,
647
+ ports: clientPorts,
648
+ port: (label) => label,
649
+ timeoutMs: transport.timeoutMs,
650
+ rpcGlobal: transport.rpcGlobal,
651
+ body: "Append(body);",
652
+ decode: "",
653
+ }),
654
+ ...httpMethods(telemetryClient, "opcua"),
655
+ ]
656
+ : [
657
+ ...nativeHttp({
658
+ id: telemetryClient,
659
+ name: names.client,
660
+ ports: clientPorts,
661
+ port: (label) => label,
662
+ endpoint: transport.endpoint,
663
+ network: transport.network,
664
+ method: "POST",
665
+ json: true,
666
+ body: "Append(body);",
667
+ decode: "",
668
+ }),
669
+ ...httpMethods(telemetryClient),
670
+ ...httpCertificateVerifier(
671
+ telemetryClient,
672
+ names.client,
673
+ transport.endpoint,
674
+ ),
675
+ ];
638
676
  return [
639
677
  {
640
678
  id: "tsplc:telemetryRecord",
@@ -772,9 +810,6 @@ WriteString(text);
772
810
  ...calls,
773
811
  ...failures,
774
812
  ...trace,
775
- client,
776
- ...clientLifecycle,
777
- ...httpMethods(telemetryClient),
778
- ...httpCertificateVerifier(telemetryClient, names.client, endpoint),
813
+ ...clientObjects,
779
814
  ];
780
815
  }