@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
@@ -14,6 +14,7 @@ import {
14
14
  type CapturedNode,
15
15
  type CapturedValue,
16
16
  type CaptureRequest,
17
+ type ClosureSite,
17
18
  captureRequestSchema,
18
19
  withBindingRegistry,
19
20
  } from "./capture-protocol";
@@ -48,7 +49,11 @@ plugin({
48
49
  },
49
50
  ({ path }) => ({
50
51
  contents: withBindingRegistry(
51
- readFileSync(path, "utf8"),
52
+ withClosureNotes(
53
+ readFileSync(path, "utf8"),
54
+ real.get(path)!,
55
+ request.closures[real.get(path)!] ?? [],
56
+ ),
52
57
  request.bindings[real.get(path)!]!,
53
58
  exportName,
54
59
  ),
@@ -73,6 +78,20 @@ plugin({
73
78
  "export const retain = (value) => globalThis.__tsplcRetain(value);",
74
79
  loader: "js",
75
80
  }));
81
+ // The SDK's types module has no runtime of its own; a module importing a time constructor still loads.
82
+ build.module("@tsplc/compiler/types", () => ({
83
+ contents: `const unsupported = (name) => () => { throw new Error(name + " cannot run during PLC setup."); };
84
+ export const ms = (value) => value, seconds = (value) => value * 1000, minutes = (value) => value * 60000;
85
+ export const exact = unsupported("exact"), wrap = unsupported("wrap"), saturate = unsupported("saturate");
86
+ export const wrapAdd = unsupported("wrapAdd"), wrapSubtract = unsupported("wrapSubtract"), wrapMultiply = unsupported("wrapMultiply");
87
+ export const saturatingAdd = unsupported("saturatingAdd"), saturatingSubtract = unsupported("saturatingSubtract"), saturatingMultiply = unsupported("saturatingMultiply");
88
+ export const div = unsupported("div"), defaultValue = unsupported("defaultValue"), copy = unsupported("copy"), entries = unsupported("entries");
89
+ export const ref = unsupported("ref"), retain = unsupported("retain"), timeToMilliseconds = unsupported("timeToMilliseconds");
90
+ export const date = unsupported("date"), timeOfDay = unsupported("timeOfDay"), dateAndTime = unsupported("dateAndTime");
91
+ export const sqrt = Math.sqrt, ln = Math.log, log10 = Math.log10, exp = Math.exp, sin = Math.sin, cos = Math.cos, tan = Math.tan;
92
+ export const asin = Math.asin, acos = Math.acos, atan = Math.atan, trunc = Math.trunc, expt = Math.pow;`,
93
+ loader: "js",
94
+ }));
76
95
  build.module("@tsplc/compiler/async", () => ({
77
96
  contents: `export const createServiceClient = () => globalThis.__tsplcService([]);
78
97
  const unsupported = (name) => () => { throw new Error(name + " cannot run during PLC setup."); };
@@ -83,6 +102,52 @@ plugin({
83
102
  },
84
103
  });
85
104
  (globalThis as { __tsplcService?: unknown }).__tsplcService = service;
105
+
106
+ /** Closures setup made, with where each is written and a reader of what it captured. */
107
+ const closures = new Map<
108
+ unknown,
109
+ { file: string; start: number; names: string[]; captured: () => unknown[] }
110
+ >();
111
+ (globalThis as { __tsplcClosure?: unknown }).__tsplcClosure = (
112
+ file: string,
113
+ start: number,
114
+ names: string[],
115
+ made: unknown,
116
+ captured: () => unknown[],
117
+ ) => {
118
+ closures.set(made, { file, start, names, captured });
119
+ return made;
120
+ };
121
+
122
+ /**
123
+ * Wraps each closure in the source so making it notes it. The wrapper keeps the expression's value,
124
+ * and its reader is an arrow beside it, so it reads the same variables and `this`.
125
+ */
126
+ const withClosureNotes = (
127
+ text: string,
128
+ file: string,
129
+ sites: readonly ClosureSite[],
130
+ ): string => {
131
+ const inserts = sites.flatMap((site) => [
132
+ {
133
+ at: site.start,
134
+ order: 1,
135
+ text: `globalThis.__tsplcClosure(${JSON.stringify(file)}, ${site.start}, ${JSON.stringify(site.captures)}, (`,
136
+ },
137
+ {
138
+ at: site.end,
139
+ order: 0,
140
+ text: `), () => [${site.captures.join(", ")}])`,
141
+ },
142
+ ]);
143
+ // From the end, so earlier offsets stay valid; at one offset, a closing wrapper before an opening one.
144
+ inserts.sort((left, right) => right.at - left.at || left.order - right.order);
145
+ return inserts.reduce(
146
+ (result, insert) =>
147
+ result.slice(0, insert.at) + insert.text + result.slice(insert.at),
148
+ text,
149
+ );
150
+ };
86
151
  /** Objects setup passed to `retain`. A retained primitive has no identity; the compiler finds those in the source. */
87
152
  const retainedObjects = new Set<object>();
88
153
  (globalThis as { __tsplcRetain?: unknown }).__tsplcRetain = (
@@ -127,8 +192,9 @@ const capture = (value: unknown, where: string): CapturedValue => {
127
192
  if (value === undefined) {
128
193
  return { kind: "undefined" };
129
194
  }
195
+ // null is the PLC's one empty value, as undefined is.
130
196
  if (value === null) {
131
- throw new Error(`${where}: null has no PLC value; use undefined.`);
197
+ return { kind: "undefined" };
132
198
  }
133
199
  if (typeof value === "number") {
134
200
  if (!Number.isFinite(value)) {
@@ -158,10 +224,22 @@ const capture = (value: unknown, where: string): CapturedValue => {
158
224
  if (typeof value === "function") {
159
225
  const path = (value as { [servicePath]?: string })[servicePath];
160
226
  const named = functions.get(value) ?? classes.get(value);
227
+ const closure = closures.get(value);
161
228
  if (path !== undefined) {
162
229
  nodes[id] = { kind: "service", path };
163
230
  } else if (named) {
164
231
  nodes[id] = { kind: "function", ...named };
232
+ } else if (closure) {
233
+ const values = closure.captured();
234
+ nodes[id] = {
235
+ kind: "closure",
236
+ file: closure.file,
237
+ start: closure.start,
238
+ captures: closure.names.map((name, index) => ({
239
+ name,
240
+ value: capture(values[index], `${where} (captured ${name})`),
241
+ })),
242
+ };
165
243
  } else {
166
244
  throw new Error(
167
245
  `${where}: setup stored a function that is not a module-level function, so the PLC can't call it.`,
@@ -5,6 +5,7 @@ import type { EntryImports } from "./imports";
5
5
  import type { Initializers } from "./initializers";
6
6
  import type { Layouts } from "./layouts";
7
7
  import type { Model } from "./model";
8
+ import { referenceIndex, referenceType } from "./references";
8
9
  import type { Storage } from "./storage";
9
10
  import type { Value } from "./values";
10
11
 
@@ -24,6 +25,12 @@ export class DialectText {
24
25
 
25
26
  /** Dialect text for a value, in a place of `expected` type when known. */
26
27
  code(value: Value, expected: ts.Type | undefined): string | Mapped {
28
+ // Where a reference is held, a value is the id of the object it is.
29
+ const index =
30
+ expected && referenceType(expected) ? referenceIndex(value) : undefined;
31
+ if (index !== undefined) {
32
+ return index;
33
+ }
27
34
  switch (value.kind) {
28
35
  case "code":
29
36
  if (
@@ -103,7 +110,37 @@ export class DialectText {
103
110
  }
104
111
  case "function":
105
112
  throw new Error("A function has no PLC value; call it.");
113
+ case "counted":
114
+ throw new Error(
115
+ "An array whose length is decided at run time has no PLC value: read it with for…of, its length, an index or an array method.",
116
+ );
117
+ case "choice":
118
+ return expected ? this.chosenCopy(value, expected) : value.index;
119
+ case "masked":
120
+ throw new Error(
121
+ "An array filtered or sorted at run time has no PLC value: read its length, or pick from it.",
122
+ );
123
+ }
124
+ }
125
+
126
+ /** A record chosen at run time, where the PLC holds a record's value: a copy of whichever it is. */
127
+ private chosenCopy(
128
+ choice: Value & { kind: "choice" },
129
+ expected: ts.Type,
130
+ ): string | Mapped {
131
+ const copies = choice.options.map((option) => ({
132
+ id: option.id,
133
+ text: this.code({ kind: "static", node: option }, expected),
134
+ }));
135
+ const last = copies.pop();
136
+ if (!last) {
137
+ throw new Error("A reference to no object has no PLC value.");
106
138
  }
139
+ return copies.reduceRight<string | Mapped>(
140
+ (otherwise, copy) =>
141
+ mapped`(${choice.index} === ${copy.id} ? ${copy.text} : ${otherwise})`,
142
+ last.text,
143
+ );
107
144
  }
108
145
 
109
146
  /** A record literal of `type`, every field written; a tagged union fills the other variants' fields. */
@@ -131,18 +168,51 @@ export class DialectText {
131
168
  return `${name}: ${this.initializers.defaultOf(fieldType)}`;
132
169
  }
133
170
  const property = this.checker.getPropertyOfType(type, name);
134
- return mapped`${name}: ${this.assignmentText(value, fieldType, this.layouts.iecName(property?.valueDeclaration))}`;
171
+ // A record field holds exactly its type, so a narrower integer widens explicitly, as a result does.
172
+ return mapped`${name}: ${this.returnText(value, fieldType, this.layouts.iecName(property?.valueDeclaration))}`;
135
173
  }),
136
174
  ", ",
137
175
  )} }`;
138
176
  }
139
177
 
178
+ /**
179
+ * A routine's result: stored as an assignment is, and a narrower integer widened explicitly, as
180
+ * Structured Text's typed functions return exactly their declared type.
181
+ */
182
+ returnText(
183
+ value: Value,
184
+ declared: ts.Type | undefined,
185
+ iec: string | undefined,
186
+ ): string | Mapped {
187
+ const target =
188
+ iec ??
189
+ (declared && declared.flags & ts.TypeFlags.Number ? "DINT" : undefined);
190
+ const from = value.kind === "code" ? value.iec : undefined;
191
+ if (
192
+ target &&
193
+ from &&
194
+ from !== target &&
195
+ integerTypes.has(from) &&
196
+ integerTypes.has(target) &&
197
+ !needsConversion(from, target)
198
+ ) {
199
+ this.imports.addSdk("@tsplc/compiler/types", "exact");
200
+ return mapped`exact<${target}>(${this.code(value, undefined)})`;
201
+ }
202
+ return this.assignmentText(value, declared, iec);
203
+ }
204
+
140
205
  /** The text stored into a place of `declared` type, wrapping an optional's value. */
141
206
  assignmentText(
142
207
  value: Value,
143
208
  declared: ts.Type | undefined,
144
209
  iec?: string,
145
210
  ): string | Mapped {
211
+ const index =
212
+ declared && referenceType(declared) ? referenceIndex(value) : undefined;
213
+ if (index !== undefined) {
214
+ return index;
215
+ }
146
216
  const target =
147
217
  iec ??
148
218
  (declared && declared.flags & ts.TypeFlags.Number ? "DINT" : undefined);
@@ -166,10 +236,14 @@ export class DialectText {
166
236
  ) {
167
237
  return value.text;
168
238
  }
169
- return this.wrapDefined(
239
+ const defined = this.wrapDefined(
170
240
  this.code(value, this.checker.getNonNullableType(declared)),
171
241
  declared,
172
242
  );
243
+ // A record chosen at run time may be none, which the optional says.
244
+ return value.kind === "choice" && value.optional
245
+ ? mapped`(${value.index} >= 0 ? ${defined} : defaultValue<${this.layouts.text(declared)}>())`
246
+ : defined;
173
247
  }
174
248
  return this.code(value, declared);
175
249
  }
@@ -199,6 +273,9 @@ export class DialectText {
199
273
 
200
274
  /** A boolean condition, including JavaScript truthiness of optionals and enums. */
201
275
  condition(value: Value, at: ts.Node): string | Mapped {
276
+ if (value.kind === "choice") {
277
+ return value.optional ? mapped`(${value.index} >= 0)` : "true";
278
+ }
202
279
  if (value.kind === "code" && value.declared) {
203
280
  const declared = value.declared;
204
281
  if (
@@ -240,6 +317,43 @@ export class DialectText {
240
317
  this.imports.addSdk("@tsplc/compiler/types", "wrap");
241
318
  return [mapped`wrap<LINT>(${leftText})`, mapped`wrap<LINT>(${rightText})`];
242
319
  }
320
+
321
+ /**
322
+ * Operands of integer arithmetic at one width, as TypeScript numbers are: the narrower widens to
323
+ * the other, or both to LINT when neither holds the other. `iec` is the width of the result.
324
+ */
325
+ arithmetic(
326
+ left: Value,
327
+ right: Value,
328
+ ): { texts: [string | Mapped, string | Mapped]; iec: string | undefined } {
329
+ const leftText = this.code(left, undefined);
330
+ const rightText = this.code(right, undefined);
331
+ // A literal takes the other operand's width, so the result keeps it.
332
+ if (left.kind !== "code" || right.kind !== "code") {
333
+ const operand = left.kind === "code" ? left : right;
334
+ return {
335
+ texts: [leftText, rightText],
336
+ iec: operand.kind === "code" ? operand.iec : undefined,
337
+ };
338
+ }
339
+ const from = left.iec ?? "DINT";
340
+ const to = right.iec ?? "DINT";
341
+ if (from === to || !integerTypes.has(from) || !integerTypes.has(to)) {
342
+ return { texts: [leftText, rightText], iec: left.iec };
343
+ }
344
+ const common = !needsConversion(from, to)
345
+ ? to
346
+ : !needsConversion(to, from)
347
+ ? from
348
+ : "LINT";
349
+ this.imports.addSdk("@tsplc/compiler/types", "exact");
350
+ const widened = (text: string | Mapped, width: string) =>
351
+ width === common ? text : mapped`exact<${common}>(${text})`;
352
+ return {
353
+ texts: [widened(leftText, from), widened(rightText, to)],
354
+ iec: common === "DINT" ? undefined : common,
355
+ };
356
+ }
243
357
  }
244
358
 
245
359
  /** IEC integer and bit-string types by name. */