@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
@@ -4,7 +4,9 @@ import {
4
4
  defaultValue,
5
5
  durationLiteral,
6
6
  type Expression,
7
+ elementaryFunctions,
7
8
  parseInteger,
9
+ type UnaryOperator,
8
10
  } from "@tsplc/compiler/ir";
9
11
  import ts from "typescript";
10
12
  import type { ExpressionLowering } from "./expressions";
@@ -32,8 +34,15 @@ const conversions = new Map<string, Conversion>([
32
34
  ["wrap", "wrap"],
33
35
  ["saturate", "saturate"],
34
36
  ]);
37
+ /** The SDK's one-operand math functions, each over the floating type its type argument names. */
38
+ const mathFunctions = new Map<string, UnaryOperator>([
39
+ ...elementaryFunctions.map((name): [string, UnaryOperator] => [name, name]),
40
+ ["trunc", "truncate"],
41
+ ]);
42
+
35
43
  const arithmetic = new Map<string, Arithmetic>([
36
44
  ["div", { operator: "divide" }],
45
+ ["expt", { operator: "power" }],
37
46
  ["wrapAdd", { operator: "add", policy: "wrap" }],
38
47
  ["wrapSubtract", { operator: "subtract", policy: "wrap" }],
39
48
  ["wrapMultiply", { operator: "multiply", policy: "wrap" }],
@@ -72,6 +81,10 @@ export function intrinsicExpression(
72
81
  if (operation !== undefined) {
73
82
  return arithmeticExpression(lowering, node, operation);
74
83
  }
84
+ const mathOperator = mathFunctions.get(name);
85
+ if (mathOperator !== undefined) {
86
+ return mathExpression(lowering, node, mathOperator);
87
+ }
75
88
  switch (name) {
76
89
  case "errorCode":
77
90
  return errorCode(lowering, node);
@@ -312,6 +325,25 @@ function converted(
312
325
  });
313
326
  }
314
327
 
328
+ function mathExpression(
329
+ lowering: ExpressionLowering,
330
+ node: ts.CallExpression,
331
+ operator: UnaryOperator,
332
+ ): Expression {
333
+ const type = operationType(lowering, node);
334
+ const [operand, ...rest] = node.arguments;
335
+ if (!operand || rest.length) {
336
+ lowering.fail(node, "PLC2001", "A math function takes one operand.");
337
+ }
338
+ return lowering.checked({
339
+ span: lowering.positions.node(node),
340
+ type,
341
+ kind: "unary",
342
+ operator,
343
+ operand: lowering.expression(operand, type),
344
+ });
345
+ }
346
+
315
347
  function arithmeticExpression(
316
348
  lowering: ExpressionLowering,
317
349
  node: ts.CallExpression,
@@ -5,7 +5,8 @@ import { symbolAt } from "./sdk";
5
5
  /** The quoted specifier an import generated into `importer` uses to reach `target`. */
6
6
  export const importSpecifier = (importer: string, target: string): string => {
7
7
  const path = relative(dirname(importer), target).replaceAll("\\", "/");
8
- return JSON.stringify(path.startsWith(".") ? path : `./${path}`);
8
+ // A file beside the importer may itself start with a dot, as a generated `.tsplc-services.ts` does.
9
+ return JSON.stringify(/^\.\.?\//.test(path) ? path : `./${path}`);
9
10
  };
10
11
 
11
12
  /** Runtime imports define execution; type-only imports provide layouts without allocating state. */
@@ -95,18 +95,25 @@ export const from = (node: ts.Node, text: Part): Mapped => {
95
95
  /** A node's source text, copied. */
96
96
  export const copied = (node: ts.Node): Mapped => {
97
97
  const source = node.getSourceFile();
98
- const start = node.getStart(source);
99
- return new Mapped(source.text.slice(start, node.end), [
98
+ return copiedRange(source, node.getStart(source), node.end);
99
+ };
100
+
101
+ /** A run of a source's text, copied. */
102
+ export const copiedRange = (
103
+ source: ts.SourceFile,
104
+ start: number,
105
+ end: number,
106
+ ): Mapped =>
107
+ new Mapped(source.text.slice(start, end), [
100
108
  {
101
109
  start: 0,
102
- end: node.end - start,
110
+ end: end - start,
103
111
  file: source.fileName,
104
112
  from: start,
105
- to: node.end,
113
+ to: end,
106
114
  copied: true,
107
115
  },
108
116
  ]);
109
- };
110
117
 
111
118
  export const slice = (text: Mapped, start: number, end: number): Mapped => {
112
119
  const segments: Segment[] = [];
@@ -7,6 +7,7 @@ import { Analyzer, suppressionDiagnostics } from "./analyzer";
7
7
  import { type AsyncLowering, lowerAsync } from "./async";
8
8
  import { lowerEnvironment } from "./configuration";
9
9
  import { lowerConstFunctions } from "./const-functions";
10
+ import { lowerControlFlow } from "./control-flow";
10
11
  import { lowerElaboration } from "./elaborate/index";
11
12
  import { lowerExposure } from "./exposure";
12
13
  import { runtimeSources } from "./module-graph";
@@ -127,7 +128,7 @@ export function analyze(options: FrontendOptions): FrontendResult {
127
128
  allowJs: false,
128
129
  skipLibCheck: false,
129
130
  types: [],
130
- lib: ["lib.es2022.d.ts"],
131
+ lib: ["lib.es2025.d.ts"],
131
132
  module: ts.ModuleKind.ESNext,
132
133
  moduleResolution: ts.ModuleResolutionKind.Bundler,
133
134
  };
@@ -218,6 +219,9 @@ export function analyze(options: FrontendOptions): FrontendResult {
218
219
  if (!apply(elaboration)) {
219
220
  return { diagnostics };
220
221
  }
222
+ if (!apply(lowerControlFlow(program))) {
223
+ return { diagnostics };
224
+ }
221
225
  const services = lowerServices(program, sdk, positions, options.services);
222
226
  if (!apply(services)) {
223
227
  return { diagnostics };
@@ -8,6 +8,7 @@ import type {
8
8
  PlcModule,
9
9
  PlcProgram,
10
10
  TelemetryCall,
11
+ UnaryOperator,
11
12
  Variable,
12
13
  } from "./model";
13
14
  import type { PlcType } from "./types";
@@ -31,12 +32,7 @@ export type CoreExpression = {
31
32
  | { readonly kind: "load"; readonly root: string; readonly path?: CorePath }
32
33
  | {
33
34
  readonly kind: "unary";
34
- readonly operator:
35
- | "not"
36
- | "negate"
37
- | "bitNot"
38
- | "timeToMilliseconds"
39
- | "clock";
35
+ readonly operator: UnaryOperator;
40
36
  readonly operand: CoreExpression;
41
37
  }
42
38
  | {
package/src/ir/fold.ts CHANGED
@@ -1,5 +1,12 @@
1
1
  import { nanosecondsPerMillisecond } from "./domains";
2
- import type { BinaryOperator, Constant, Expression, Variable } from "./model";
2
+ import {
3
+ type BinaryOperator,
4
+ type Constant,
5
+ type Expression,
6
+ elementaryValue,
7
+ isElementary,
8
+ type Variable,
9
+ } from "./model";
3
10
  import {
4
11
  applyIntegerPolicy,
5
12
  integerType,
@@ -153,6 +160,15 @@ const foldUnary = (
153
160
  value: String(BigInt(value.nanoseconds) / nanosecondsPerMillisecond),
154
161
  };
155
162
  }
163
+ if (value?.kind === "float" && isElementary(expression.operator)) {
164
+ return finiteFloat(
165
+ elementaryValue[expression.operator](value.value),
166
+ target,
167
+ );
168
+ }
169
+ if (value?.kind === "float" && expression.operator === "truncate") {
170
+ return finiteFloat(Math.trunc(value.value), target);
171
+ }
156
172
  if (value?.kind === "bool" && expression.operator === "not") {
157
173
  return { kind: "bool", value: !value.value };
158
174
  }
@@ -331,7 +347,20 @@ const floatArithmetic = (
331
347
  return left / right;
332
348
  case "remainder":
333
349
  return left % right;
350
+ case "power":
351
+ return left ** right;
334
352
  default:
335
353
  return undefined;
336
354
  }
337
355
  };
356
+
357
+ /** A float result as its type holds it, or nothing when it isn't finite, as NaN and infinities aren't constants. */
358
+ const finiteFloat = (
359
+ value: number,
360
+ target: PlcType | undefined,
361
+ ): Constant | undefined => {
362
+ const rounded = target?.kind === "float" ? roundFloat(value, target) : value;
363
+ return Number.isFinite(rounded)
364
+ ? { kind: "float", value: rounded }
365
+ : undefined;
366
+ };
package/src/ir/index.ts CHANGED
@@ -40,10 +40,14 @@ export {
40
40
  type Constant,
41
41
  comparisonOperators,
42
42
  type Deployment,
43
+ type ElementaryFunction,
43
44
  type EmitResult,
44
45
  type Expression,
46
+ elementaryFunctions,
47
+ elementaryValue,
45
48
  type FunctionBlock,
46
49
  type GeneratedObject,
50
+ isElementary,
47
51
  type MathHelper,
48
52
  type MethodOwner,
49
53
  type Place,
@@ -56,6 +60,7 @@ export {
56
60
  type Task,
57
61
  type TelemetryCall,
58
62
  telemetryOperands,
63
+ type UnaryOperator,
59
64
  type Variable,
60
65
  } from "./model";
61
66
  export { isVerifiedCore, normalizeModule } from "./normalize";
package/src/ir/model.ts CHANGED
@@ -42,6 +42,56 @@ export interface Place {
42
42
  )[];
43
43
  }
44
44
 
45
+ /**
46
+ * The elementary functions on REAL and LREAL, Structured Text's SQRT, LN, LOG, EXP and the
47
+ * trigonometric functions; each returns its operand's type.
48
+ */
49
+ export const elementaryFunctions = [
50
+ "sqrt",
51
+ "ln",
52
+ "log10",
53
+ "exp",
54
+ "sin",
55
+ "cos",
56
+ "tan",
57
+ "asin",
58
+ "acos",
59
+ "atan",
60
+ ] as const;
61
+ export type ElementaryFunction = (typeof elementaryFunctions)[number];
62
+
63
+ /** Each elementary function as JavaScript computes it, which constants fold and simulations run with. */
64
+ export const elementaryValue: Readonly<
65
+ Record<ElementaryFunction, (value: number) => number>
66
+ > = {
67
+ sqrt: Math.sqrt,
68
+ ln: Math.log,
69
+ log10: Math.log10,
70
+ exp: Math.exp,
71
+ sin: Math.sin,
72
+ cos: Math.cos,
73
+ tan: Math.tan,
74
+ asin: Math.asin,
75
+ acos: Math.acos,
76
+ atan: Math.atan,
77
+ };
78
+
79
+ export const isElementary = (
80
+ operator: string,
81
+ ): operator is ElementaryFunction =>
82
+ (elementaryFunctions as readonly string[]).includes(operator);
83
+
84
+ /** `truncate` is TRUNC, a REAL or LREAL toward zero as DINT. */
85
+ export type UnaryOperator =
86
+ | "not"
87
+ | "negate"
88
+ | "bitNot"
89
+ | "timeToMilliseconds"
90
+ | "clock"
91
+ | "truncate"
92
+ | ElementaryFunction;
93
+
94
+ /** `power` is EXPT on REAL or LREAL. */
45
95
  export type BinaryOperator =
46
96
  | "add"
47
97
  | "subtract"
@@ -60,7 +110,8 @@ export type BinaryOperator =
60
110
  | "bitOr"
61
111
  | "bitXor"
62
112
  | "shiftLeft"
63
- | "shiftRight";
113
+ | "shiftRight"
114
+ | "power";
64
115
 
65
116
  export const comparisonOperators: ReadonlySet<BinaryOperator> = new Set([
66
117
  "equal",
@@ -76,7 +127,7 @@ export type Expression = { type: TypeId; span: SourceSpan } & (
76
127
  | { kind: "load"; place: Place }
77
128
  | {
78
129
  kind: "unary";
79
- operator: "not" | "negate" | "bitNot" | "timeToMilliseconds" | "clock";
130
+ operator: UnaryOperator;
80
131
  operand: Expression;
81
132
  }
82
133
  | {
package/src/ir/scalars.ts CHANGED
@@ -2,7 +2,9 @@ import { fold } from "./fold";
2
2
  import {
3
3
  type Constant,
4
4
  comparisonOperators,
5
+ type ElementaryFunction,
5
6
  type Expression,
7
+ isElementary,
6
8
  type Variable,
7
9
  } from "./model";
8
10
  import {
@@ -156,7 +158,17 @@ const unaryIssue = (
156
158
  type: PlcType,
157
159
  proof: Proof,
158
160
  ): string | undefined => {
161
+ if (isElementary(expression.operator)) {
162
+ if (source.kind !== "float" || source.id !== type.id) {
163
+ return "Elementary functions take and return one floating type.";
164
+ }
165
+ return domainIssue(expression.operator, expression.operand, type, proof);
166
+ }
159
167
  switch (expression.operator) {
168
+ case "truncate":
169
+ return source.kind === "float" && source.id === type.id
170
+ ? undefined
171
+ : "trunc takes and returns one floating type.";
160
172
  case "clock":
161
173
  return type.id === "DINT"
162
174
  ? undefined
@@ -228,6 +240,12 @@ const binaryIssue = (
228
240
  }
229
241
  return right.id === type.id ? undefined : "Bit-string widths differ.";
230
242
  }
243
+ if (expression.operator === "power") {
244
+ if (type.kind !== "float" || left.id !== type.id || right.id !== type.id) {
245
+ return "A power takes and returns one floating type.";
246
+ }
247
+ return powerIssue(expression, type, proof);
248
+ }
231
249
  if (
232
250
  left.id !== type.id ||
233
251
  right.id !== type.id ||
@@ -263,6 +281,114 @@ const binaryIssue = (
263
281
  return resultIssue(expression, type, proof);
264
282
  };
265
283
 
284
+ /**
285
+ * The bounds a floating operand is proved to keep: a constant's value, or the proved range of an
286
+ * integer converted to it exactly. Other floating values have no proved bounds.
287
+ */
288
+ const floatBounds = (
289
+ expression: Expression,
290
+ proof: Proof,
291
+ ): readonly [number, number] | undefined => {
292
+ const value = proof.fold(expression);
293
+ if (value?.kind === "float") {
294
+ return [value.value, value.value];
295
+ }
296
+ if (value?.kind === "integer") {
297
+ return [Number(value.value), Number(value.value)];
298
+ }
299
+ if (expression.kind === "convert" && expression.policy === "exact") {
300
+ const proved = proof.interval(expression.operand);
301
+ return proved && [Number(proved[0]), Number(proved[1])];
302
+ }
303
+ return undefined;
304
+ };
305
+
306
+ /** Where each elementary function's result is finite, and what to prove when its operand may leave there. */
307
+ const domains: Readonly<
308
+ Record<
309
+ ElementaryFunction,
310
+ | {
311
+ holds: (low: number, high: number, type: PlcType) => boolean;
312
+ needs: string;
313
+ }
314
+ | undefined
315
+ >
316
+ > = {
317
+ sqrt: { holds: (low) => low >= 0, needs: "not negative" },
318
+ ln: { holds: (low) => low > 0, needs: "greater than zero" },
319
+ log10: { holds: (low) => low > 0, needs: "greater than zero" },
320
+ exp: {
321
+ holds: (_, high, type) =>
322
+ type.kind === "float" &&
323
+ Number.isFinite(roundFloat(Math.exp(high), type)),
324
+ needs: "small enough for a finite result",
325
+ },
326
+ asin: {
327
+ holds: (low, high) => low >= -1 && high <= 1,
328
+ needs: "between -1 and 1",
329
+ },
330
+ acos: {
331
+ holds: (low, high) => low >= -1 && high <= 1,
332
+ needs: "between -1 and 1",
333
+ },
334
+ sin: undefined,
335
+ cos: undefined,
336
+ tan: undefined,
337
+ atan: undefined,
338
+ };
339
+
340
+ /** A finite float operand keeps sine, cosine, tangent and arctangent finite; the others need their operand's domain proved. */
341
+ const domainIssue = (
342
+ operator: ElementaryFunction,
343
+ operand: Expression,
344
+ type: PlcType,
345
+ proof: Proof,
346
+ ): string | undefined => {
347
+ const domain = domains[operator];
348
+ if (!domain) {
349
+ return undefined;
350
+ }
351
+ const bounds = floatBounds(operand, proof);
352
+ if (bounds && domain.holds(bounds[0], bounds[1], type)) {
353
+ return undefined;
354
+ }
355
+ return `${operator} needs its operand proved ${domain.needs}, as a constant or an integer converted exactly is.`;
356
+ };
357
+
358
+ /** A power needs a constant exponent and a base whose proved bounds keep the result real and finite. */
359
+ const powerIssue = (
360
+ expression: Extract<Expression, { kind: "binary" }>,
361
+ type: PlcType,
362
+ proof: Proof,
363
+ ): string | undefined => {
364
+ const folded = proof.fold(expression);
365
+ if (folded) {
366
+ return constantFits(folded, type)
367
+ ? undefined
368
+ : "Floating result is not finite or representable.";
369
+ }
370
+ const exponent = proof.fold(expression.right);
371
+ const base = floatBounds(expression.left, proof);
372
+ if (exponent?.kind !== "float" || !base || type.kind !== "float") {
373
+ return "A power needs a constant exponent and a base proved within bounds, as a constant or an integer converted exactly is.";
374
+ }
375
+ const [low, high] = base;
376
+ if (!Number.isInteger(exponent.value) && low < 0) {
377
+ return "A fractional power needs its base proved not negative.";
378
+ }
379
+ if (exponent.value < 0 && low <= 0 && high >= 0) {
380
+ return "A negative power needs its base proved not zero.";
381
+ }
382
+ const magnitudes = [Math.abs(low), Math.abs(high)];
383
+ const largest =
384
+ exponent.value >= 0
385
+ ? Math.max(...magnitudes) ** exponent.value
386
+ : Math.min(...magnitudes) ** exponent.value;
387
+ return Number.isFinite(roundFloat(largest, type))
388
+ ? undefined
389
+ : "The power may not be finite.";
390
+ };
391
+
266
392
  /** Whether an arithmetic result is proved to stay in its integer type, or finite in its float type. */
267
393
  const resultIssue = (
268
394
  expression: Extract<Expression, { kind: "unary" | "binary" }>,
@@ -0,0 +1,17 @@
1
+ import { initTRPC } from "@trpc/server";
2
+ import { iec, type PlcMeta } from "@tsplc/server";
3
+ import { z } from "zod";
4
+
5
+ const api = initTRPC.meta<PlcMeta>().create();
6
+ /** Callable by the PLC through createServiceClient. */
7
+ const plcProcedure = api.procedure.meta({ plc: true });
8
+
9
+ export const appRouter = api.router({
10
+ cell: api.router({
11
+ report: plcProcedure
12
+ .input(z.strictObject({ count: iec.UINT(), running: z.boolean() }))
13
+ .output(z.strictObject({ answer: iec.DINT() }))
14
+ .mutation(({ input }) => ({ answer: input.count * 2 + 1 })),
15
+ }),
16
+ });
17
+ export type AppRouter = typeof appRouter;
@@ -0,0 +1,45 @@
1
+ import { retain } from "@tsplc/compiler/retain";
2
+ import { Lane } from "./lane";
3
+
4
+ export type Mode = "idle" | "running";
5
+
6
+ export interface Card {
7
+ input: { sensor: BOOL };
8
+ output: { motion: BOOL; speed: INT };
9
+ }
10
+
11
+ /** The cell's IO, its operator's controls and its counts: what the program publishes. */
12
+ export interface Cell {
13
+ cards: Card[];
14
+ mode: Mode;
15
+ start: BOOL;
16
+ bump: BOOL;
17
+ count: UINT;
18
+ scans: UDINT;
19
+ lanes: Record<Lane, BOOL>;
20
+ lastLane: Lane | undefined;
21
+ report: BOOL;
22
+ replies: UDINT;
23
+ answer: DINT;
24
+ failures: UDINT;
25
+ settings: { speed: INT };
26
+ }
27
+
28
+ export const createCell = (): Cell => ({
29
+ cards: Array.from({ length: 3 }, () => ({
30
+ input: { sensor: false },
31
+ output: { motion: false, speed: 0 },
32
+ })),
33
+ mode: "idle",
34
+ start: false,
35
+ bump: false,
36
+ count: 0,
37
+ scans: 0,
38
+ lanes: { [Lane.Unknown]: false, [Lane.Left]: false, [Lane.Right]: false },
39
+ lastLane: undefined,
40
+ report: false,
41
+ replies: 0,
42
+ answer: 0,
43
+ failures: 0,
44
+ settings: retain({ speed: 50 }),
45
+ });
@@ -0,0 +1,58 @@
1
+ import { telemetry } from "@tsplc/compiler/telemetry";
2
+ import type { Cell } from "./cell";
3
+ import { Lane } from "./lane";
4
+ import type { ReportReply, Services } from "./services";
5
+
6
+ export class CellController {
7
+ private sending = false;
8
+
9
+ constructor(
10
+ private readonly cell: Cell,
11
+ private readonly services: Services,
12
+ ) {}
13
+
14
+ scan(): void {
15
+ const cell = this.cell;
16
+ cell.scans += 1;
17
+ for (const card of cell.cards) {
18
+ card.output.motion = card.input.sensor && cell.mode === "running";
19
+ card.output.speed = card.input.sensor ? cell.settings.speed : 0;
20
+ }
21
+ if (cell.start) {
22
+ cell.start = false;
23
+ cell.mode = "running";
24
+ }
25
+ if (cell.bump) {
26
+ cell.bump = false;
27
+ cell.count = cell.count + 1;
28
+ }
29
+ cell.lastLane = undefined;
30
+ if (cell.lanes[Lane.Left]) {
31
+ cell.lastLane = Lane.Left;
32
+ }
33
+ if (cell.lanes[Lane.Right]) {
34
+ cell.lastLane = Lane.Right;
35
+ }
36
+ if (cell.report && !this.sending) {
37
+ cell.report = false;
38
+ void this.send();
39
+ }
40
+ }
41
+
42
+ private async send(): Promise<void> {
43
+ this.sending = true;
44
+ try {
45
+ const reply: ReportReply = await this.services.cell.report({
46
+ count: this.cell.count,
47
+ running: this.cell.mode === "running",
48
+ });
49
+ this.cell.replies += 1;
50
+ this.cell.answer = reply.answer;
51
+ telemetry.info("Report answered", { answer: reply.answer });
52
+ } catch (error) {
53
+ this.cell.failures += 1;
54
+ telemetry.captureException(error);
55
+ }
56
+ this.sending = false;
57
+ }
58
+ }
@@ -0,0 +1,6 @@
1
+ /** Where the cell sends a part. */
2
+ export enum Lane {
3
+ Unknown = 0,
4
+ Left = 1,
5
+ Right = 2,
6
+ }
@@ -0,0 +1,11 @@
1
+ import { createCell } from "./cell";
2
+ import { CellController } from "./controller";
3
+ import { services } from "./services";
4
+
5
+ export const cell = createCell();
6
+ const controller = new CellController(cell, services);
7
+
8
+ /** One PLC scan. */
9
+ export function main(): void {
10
+ controller.scan();
11
+ }
@@ -0,0 +1,8 @@
1
+ import type { inferRouterOutputs } from "@trpc/server";
2
+ import { createServiceClient } from "@tsplc/compiler/async";
3
+ import type { AppRouter } from "../server/router";
4
+
5
+ /** The server procedures the program calls. */
6
+ export const services = createServiceClient<AppRouter>();
7
+ export type Services = typeof services;
8
+ export type ReportReply = inferRouterOutputs<AppRouter>["cell"]["report"];
@@ -0,0 +1,13 @@
1
+ {
2
+ "compilerOptions": {
3
+ "strict": true,
4
+ "target": "ES2022",
5
+ "module": "ESNext",
6
+ "moduleResolution": "Bundler",
7
+ "noEmit": true,
8
+ "skipLibCheck": true,
9
+ "types": ["bun", "@tsplc/compiler/globals"],
10
+ "allowImportingTsExtensions": true
11
+ },
12
+ "include": ["src/**/*.ts", "server/**/*.ts"]
13
+ }
@@ -0,0 +1,31 @@
1
+ import { defineConfig, ms } from "@tsplc/config";
2
+
3
+ /** A cell whose plain TypeScript program the Bun runtime runs in the compiler's tests. */
4
+ export default defineConfig({
5
+ name: "BunRuntimeCell",
6
+ backend: "codesys",
7
+ build: { outDir: "build/codesys", symbols: true },
8
+ codesys: {
9
+ http: {
10
+ timeoutMs: 2000,
11
+ credentials: [
12
+ { originEnv: "CELL_SERVER_URL", bearerTokenEnv: "CELL_SERVER_TOKEN" },
13
+ ],
14
+ },
15
+ programNames: { main: "Main" },
16
+ },
17
+ compiler: {
18
+ programs: { main: { module: "src/main.ts", export: "main" } },
19
+ },
20
+ tasks: [
21
+ {
22
+ name: "MainTask",
23
+ priority: 1,
24
+ schedule: { kind: "cyclic", interval: ms(20) },
25
+ programs: ["main"],
26
+ },
27
+ ],
28
+ publish: { development: ["cell"], production: ["cell"] },
29
+ server: { transport: "http", baseUrlEnv: "CELL_SERVER_URL" },
30
+ typegen: { dir: "generated" },
31
+ });
@@ -0,0 +1,17 @@
1
+ import { initTRPC } from "@trpc/server";
2
+ import { iec, type PlcMeta } from "@tsplc/server";
3
+ import { z } from "zod";
4
+
5
+ const api = initTRPC.meta<PlcMeta>().create();
6
+ /** Callable by the PLC through createServiceClient. */
7
+ const plcProcedure = api.procedure.meta({ plc: true });
8
+
9
+ export const appRouter = api.router({
10
+ cell: api.router({
11
+ report: plcProcedure
12
+ .input(z.strictObject({ count: iec.UINT(), running: z.boolean() }))
13
+ .output(z.strictObject({ answer: iec.DINT() }))
14
+ .mutation(({ input }) => ({ answer: input.count * 2 + 1 })),
15
+ }),
16
+ });
17
+ export type AppRouter = typeof appRouter;