@tsplc/compiler 0.5.4 → 0.5.6

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 (67) hide show
  1. package/dist/bun-runtime.js +14 -2
  2. package/dist/bun-runtime.js.map +4 -4
  3. package/dist/codesys.js +46 -2
  4. package/dist/codesys.js.map +3 -3
  5. package/dist/collections.js +395 -0
  6. package/dist/collections.js.map +10 -0
  7. package/dist/elaborate-capture.js +64 -5
  8. package/dist/elaborate-capture.js.map +4 -4
  9. package/dist/index.js +5345 -1074
  10. package/dist/index.js.map +32 -25
  11. package/dist/ir.js +122 -1
  12. package/dist/ir.js.map +6 -6
  13. package/package.json +14 -9
  14. package/src/codesys/numeric.ts +61 -0
  15. package/src/frontend/control-flow.ts +752 -0
  16. package/src/frontend/coroutines.ts +171 -7
  17. package/src/frontend/elaborate/array-searches.ts +216 -0
  18. package/src/frontend/elaborate/assignments.ts +352 -0
  19. package/src/frontend/elaborate/calls.ts +488 -49
  20. package/src/frontend/elaborate/capture-protocol.ts +19 -0
  21. package/src/frontend/elaborate/capture.ts +82 -3
  22. package/src/frontend/elaborate/dialect.ts +118 -4
  23. package/src/frontend/elaborate/expressions.ts +927 -80
  24. package/src/frontend/elaborate/filtered-arrays.ts +607 -0
  25. package/src/frontend/elaborate/frame.ts +44 -1
  26. package/src/frontend/elaborate/generics.ts +137 -0
  27. package/src/frontend/elaborate/graph.ts +91 -0
  28. package/src/frontend/elaborate/imports.ts +14 -15
  29. package/src/frontend/elaborate/index.ts +30 -5
  30. package/src/frontend/elaborate/initializers.ts +15 -1
  31. package/src/frontend/elaborate/iterators.ts +1677 -0
  32. package/src/frontend/elaborate/layouts.ts +41 -19
  33. package/src/frontend/elaborate/model.ts +64 -8
  34. package/src/frontend/elaborate/references.ts +749 -0
  35. package/src/frontend/elaborate/specialize.ts +459 -29
  36. package/src/frontend/elaborate/statements.ts +552 -133
  37. package/src/frontend/elaborate/storage.ts +151 -10
  38. package/src/frontend/elaborate/values.ts +72 -0
  39. package/src/frontend/elaborate/writes.ts +302 -1
  40. package/src/frontend/intrinsics.ts +32 -0
  41. package/src/frontend/module-graph.ts +2 -1
  42. package/src/frontend/positions.ts +12 -5
  43. package/src/frontend/sdk.ts +7 -1
  44. package/src/frontend/typescript.ts +5 -1
  45. package/src/ir/core-model.ts +2 -6
  46. package/src/ir/fold.ts +30 -1
  47. package/src/ir/index.ts +5 -0
  48. package/src/ir/model.ts +53 -2
  49. package/src/ir/scalars.ts +126 -0
  50. package/src/runtime/.runtime-VaUSOu/server/router.ts +17 -0
  51. package/src/runtime/.runtime-VaUSOu/src/cell.ts +45 -0
  52. package/src/runtime/.runtime-VaUSOu/src/controller.ts +58 -0
  53. package/src/runtime/.runtime-VaUSOu/src/lane.ts +6 -0
  54. package/src/runtime/.runtime-VaUSOu/src/main.ts +11 -0
  55. package/src/runtime/.runtime-VaUSOu/src/services.ts +8 -0
  56. package/src/runtime/.runtime-VaUSOu/tsconfig.json +13 -0
  57. package/src/runtime/.runtime-VaUSOu/tsplc.config.ts +31 -0
  58. package/src/runtime/.runtime-ybIxYh/server/router.ts +17 -0
  59. package/src/runtime/.runtime-ybIxYh/src/cell.ts +45 -0
  60. package/src/runtime/.runtime-ybIxYh/src/controller.ts +58 -0
  61. package/src/runtime/.runtime-ybIxYh/src/lane.ts +6 -0
  62. package/src/runtime/.runtime-ybIxYh/src/main.ts +11 -0
  63. package/src/runtime/.runtime-ybIxYh/src/services.ts +8 -0
  64. package/src/runtime/.runtime-ybIxYh/tsconfig.json +13 -0
  65. package/src/runtime/.runtime-ybIxYh/tsplc.config.ts +31 -0
  66. package/stdlib/collections.ts +514 -0
  67. package/types/index.d.ts +18 -0
@@ -4,9 +4,19 @@ import { z } from "zod";
4
4
  * The files the compiler and its setup subprocess (capture.ts) exchange: the request names the
5
5
  * program's runtime files and the bindings each declares; the graph is what setup built.
6
6
  */
7
+ /** An arrow or function expression setup may store, and the names it captures from around it. */
8
+ const closureSiteSchema = z.strictObject({
9
+ start: z.number().int().nonnegative(),
10
+ end: z.number().int().nonnegative(),
11
+ captures: z.array(z.string()),
12
+ });
13
+ export type ClosureSite = z.infer<typeof closureSiteSchema>;
14
+
7
15
  export const captureRequestSchema = z.strictObject({
8
16
  entry: z.string().nonempty(),
9
17
  files: z.array(z.string().nonempty()),
18
+ /** By file, each closure whose creation setup notes, with what it captured. */
19
+ closures: z.record(z.string(), z.array(closureSiteSchema)),
10
20
  bindings: z.record(
11
21
  z.string(),
12
22
  z.strictObject({
@@ -76,6 +86,15 @@ const capturedNodeSchema = z.discriminatedUnion("kind", [
76
86
  name: z.string(),
77
87
  }),
78
88
  z.strictObject({ kind: z.literal("service"), path: z.string() }),
89
+ /** A function setup made inside another, by where it is written, with the values it captured. */
90
+ z.strictObject({
91
+ kind: z.literal("closure"),
92
+ file: z.string(),
93
+ start: z.number().int().nonnegative(),
94
+ captures: z.array(
95
+ z.strictObject({ name: z.string(), value: capturedValueSchema }),
96
+ ),
97
+ }),
79
98
  ]);
80
99
  export type CapturedNode = z.infer<typeof capturedNodeSchema>;
81
100
 
@@ -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,15 +78,76 @@ 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."); };
79
- export const sleep = unsupported("sleep"), fetch = unsupported("fetch"), cancelAsync = unsupported("cancelAsync");`,
98
+ export const sleep = unsupported("sleep"), fetch = unsupported("fetch"), cancelAsync = unsupported("cancelAsync");
99
+ export const errorCode = unsupported("errorCode"), asyncDiagnostics = unsupported("asyncDiagnostics"), opcuaCall = unsupported("opcuaCall");`,
80
100
  loader: "js",
81
101
  }));
82
102
  },
83
103
  });
84
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
+ };
85
151
  /** Objects setup passed to `retain`. A retained primitive has no identity; the compiler finds those in the source. */
86
152
  const retainedObjects = new Set<object>();
87
153
  (globalThis as { __tsplcRetain?: unknown }).__tsplcRetain = (
@@ -126,8 +192,9 @@ const capture = (value: unknown, where: string): CapturedValue => {
126
192
  if (value === undefined) {
127
193
  return { kind: "undefined" };
128
194
  }
195
+ // null is the PLC's one empty value, as undefined is.
129
196
  if (value === null) {
130
- throw new Error(`${where}: null has no PLC value; use undefined.`);
197
+ return { kind: "undefined" };
131
198
  }
132
199
  if (typeof value === "number") {
133
200
  if (!Number.isFinite(value)) {
@@ -157,10 +224,22 @@ const capture = (value: unknown, where: string): CapturedValue => {
157
224
  if (typeof value === "function") {
158
225
  const path = (value as { [servicePath]?: string })[servicePath];
159
226
  const named = functions.get(value) ?? classes.get(value);
227
+ const closure = closures.get(value);
160
228
  if (path !== undefined) {
161
229
  nodes[id] = { kind: "service", path };
162
230
  } else if (named) {
163
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
+ };
164
243
  } else {
165
244
  throw new Error(
166
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);
@@ -152,7 +222,7 @@ export class DialectText {
152
222
  needsConversion(value.iec ?? "DINT", target)
153
223
  ) {
154
224
  // A TypeScript number holds any of these; in the PLC a value converts as an IEC assignment does.
155
- this.imports.conversions.add("wrap");
225
+ this.imports.addSdk("@tsplc/compiler/types", "wrap");
156
226
  return mapped`wrap<${target}>(${this.code(value, undefined)})`;
157
227
  }
158
228
  if (declared && this.layouts.isOptionalRecord(declared)) {
@@ -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 (
@@ -237,9 +314,46 @@ export class DialectText {
237
314
  if (!needsConversion(from, to) || !needsConversion(to, from)) {
238
315
  return [leftText, rightText];
239
316
  }
240
- this.imports.conversions.add("wrap");
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. */