@tsplc/compiler 0.5.17 → 0.5.18

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.
package/package.json CHANGED
@@ -17,7 +17,7 @@
17
17
  "url": "git+https://github.com/rip-technologies/tsplc.git",
18
18
  "directory": "packages/compiler"
19
19
  },
20
- "version": "0.5.17",
20
+ "version": "0.5.18",
21
21
  "type": "module",
22
22
  "exports": {
23
23
  ".": {
@@ -93,17 +93,17 @@
93
93
  "bun": ">=1.4.3"
94
94
  },
95
95
  "dependencies": {
96
- "@tsplc/agent": "0.5.17",
97
- "@tsplc/build": "0.5.17",
98
- "@tsplc/config": "0.5.17",
99
- "@tsplc/debug": "0.5.17",
100
- "@tsplc/opcua": "0.5.17",
101
- "@tsplc/typegen": "0.5.17",
96
+ "@tsplc/agent": "0.5.18",
97
+ "@tsplc/build": "0.5.18",
98
+ "@tsplc/config": "0.5.18",
99
+ "@tsplc/debug": "0.5.18",
100
+ "@tsplc/opcua": "0.5.18",
101
+ "@tsplc/typegen": "0.5.18",
102
102
  "typescript": "6.0.3",
103
103
  "zod": "4.3.6",
104
104
  "@types/bun": "1.4.2",
105
- "@tsplc/server": "0.5.17",
106
- "@tsplc/iec": "0.5.17"
105
+ "@tsplc/server": "0.5.18",
106
+ "@tsplc/iec": "0.5.18"
107
107
  },
108
108
  "bin": {
109
109
  "tsplc": "./dist/cli.js"
@@ -21,6 +21,7 @@ import { type CodesysPlan, isPlanned } from "./plan";
21
21
  import { emitScanProgram, emitTaskWrappers } from "./programs";
22
22
  import { publishedSymbols } from "./publication";
23
23
  import { emitRoutine } from "./routines";
24
+ import { emitScanClock } from "./scan-clock";
24
25
  import { serviceChannelsFile } from "./service-channels";
25
26
  import { Sources } from "./sources";
26
27
  import { type ObjectMapping, type PlacedObject, stFiles } from "./st-files";
@@ -75,6 +76,7 @@ function emissionContext(plan: CodesysPlan) {
75
76
  ...global.targetTypes.objects,
76
77
  ...globalLists.objects,
77
78
  ...ioList.objects,
79
+ ...(global.scanClock ? [emitScanClock(global.scanClock)] : []),
78
80
  ...(network ? [network] : []),
79
81
  ];
80
82
 
@@ -12,13 +12,13 @@ import {
12
12
  statementExpressions,
13
13
  subexpressions,
14
14
  } from "@tsplc/compiler/ir";
15
- import { scanClockType } from "@tsplc/debug/manifest";
16
15
  import {
17
16
  type BinaryOperator,
18
17
  type ElementaryFunction,
19
18
  floatMaximum,
20
19
  isElementary,
21
20
  } from "@tsplc/iec/arithmetic";
21
+ import { required } from "./required";
22
22
 
23
23
  /** The Structured Text function each elementary function is. */
24
24
  const elementaryNames: Readonly<Record<ElementaryFunction, string>> = {
@@ -58,9 +58,6 @@ const operatorTokens: Readonly<Record<InfixOperator, string>> = {
58
58
  const isInfix = (operator: BinaryOperator): operator is InfixOperator =>
59
59
  Object.hasOwn(operatorTokens, operator);
60
60
 
61
- /** Milliseconds since the runtime started; DINT wraps after 24.8 days, so subtract to compare. */
62
- export const scanClock = `TO_${scanClockType}(TIME_TO_UDINT(TIME()))`;
63
-
64
61
  export function scalarLiteral(value: Constant, type: string): string {
65
62
  if (value.kind === "bool") {
66
63
  return value.value ? "TRUE" : "FALSE";
@@ -85,6 +82,8 @@ export class NumericLowering {
85
82
  constructor(
86
83
  private readonly types: ReadonlyMap<string, PlcType>,
87
84
  private readonly allocate: (label: string) => string,
85
+ /** What a `now()` reads; undefined for a program that never calls it. */
86
+ private readonly scanClock: string | undefined,
88
87
  ) {}
89
88
 
90
89
  private prepare(value: CoreExpression): void {
@@ -131,7 +130,7 @@ export class NumericLowering {
131
130
  return `TIME_TO_UDINT(${operands[0]})`;
132
131
  }
133
132
  if (value.operator === "clock") {
134
- return scanClock;
133
+ return required(this.scanClock);
135
134
  }
136
135
  if (isElementary(value.operator)) {
137
136
  return `${elementaryNames[value.operator]}(${operands[0]})`;
@@ -5,9 +5,9 @@ import {
5
5
  type Task,
6
6
  } from "@tsplc/compiler/ir";
7
7
  import type { IoChannel } from "./global-lists";
8
- import { scanClock } from "./numeric";
9
8
  import type { CodesysPlan } from "./plan";
10
9
  import { required } from "./required";
10
+ import { latchScanClock, restoreScanClock, runtimeClock } from "./scan-clock";
11
11
  import { noResult } from "./statements";
12
12
  import type { EmissionContext } from "./symbols";
13
13
  import { accessedStorage } from "./task-access";
@@ -29,7 +29,8 @@ export function emitScanProgram(
29
29
  const channels = ioChannels.filter((channel) => used.has(channel.root));
30
30
  const stateful = symbols.programRoutines.has(program.entry);
31
31
  const call = `${required(symbols.functionNames.get(program.entry))}();`;
32
- // The first program of a task with a ring runs its sender first, which counts the scan and reads the clock.
32
+ // A task's first program starts its cycle: it reads the scan's clock before anything else runs,
33
+ // then a task with a ring runs its sender, which counts the scan.
33
34
  const task = plan.deployment.tasks.find(
34
35
  (item) => item.programs[0] === program.name,
35
36
  );
@@ -38,8 +39,15 @@ export function emitScanProgram(
38
39
  // The scan snapshots physical inputs before the authored routine and commits outputs
39
40
  // afterwards. RETURN in an authored routine cannot skip that epilogue.
40
41
  const lines = [
42
+ ...(task && symbols.scanClock
43
+ ? latchScanClock(symbols.scanClock, task.name)
44
+ : []),
41
45
  ...(ring ? [`${instrumentation.global}.${ring}();`] : []),
42
- ...(clock ? [`${instrumentation.global}.${clock} := ${scanClock};`] : []),
46
+ ...(clock
47
+ ? [
48
+ `${instrumentation.global}.${clock} := ${symbols.scanClock?.now ?? runtimeClock};`,
49
+ ]
50
+ : []),
43
51
  ...channels
44
52
  .filter((channel) => channel.input)
45
53
  .map(
@@ -90,7 +98,10 @@ export const taskPrograms = (plan: CodesysPlan, task: Task) => {
90
98
  };
91
99
  };
92
100
 
93
- /** Each task's wrapper PROGRAM, which calls the programs the compiler added to it in their order. */
101
+ /**
102
+ * Each task's wrapper PROGRAM, which calls the programs the compiler added to it in their order.
103
+ * It is the last program of the task's cycle, so it ends the scan's clock.
104
+ */
94
105
  export function emitTaskWrappers(
95
106
  { plan, symbols }: EmissionContext,
96
107
  objects: readonly GeneratedObject[],
@@ -108,9 +119,14 @@ export function emitTaskWrappers(
108
119
  return plan.deployment.tasks.map((task) => {
109
120
  const { wrapped, wrapper } = taskPrograms(plan, task);
110
121
  const name = symbols.names.allocateObject("PRG", wrapper.label);
111
- const calls = wrapped.map(
112
- (program) => `${required(programObjects.get(program)).name}();`,
113
- );
122
+ const calls = [
123
+ ...wrapped.map(
124
+ (program) => `${required(programObjects.get(program)).name}();`,
125
+ ),
126
+ ...(symbols.scanClock
127
+ ? restoreScanClock(symbols.scanClock, task.name)
128
+ : []),
129
+ ];
114
130
  return {
115
131
  id: wrapper.id,
116
132
  kind: "program",
@@ -0,0 +1,103 @@
1
+ import type {
2
+ CoreExpression,
3
+ CoreStatement,
4
+ GeneratedObject,
5
+ Task,
6
+ VerifiedCoreModule,
7
+ } from "@tsplc/compiler/ir";
8
+ import {
9
+ nestedBodies,
10
+ statementExpressions,
11
+ subexpressions,
12
+ } from "@tsplc/compiler/ir";
13
+ import { scanClockType } from "@tsplc/debug/manifest";
14
+ import { Names } from "./names";
15
+
16
+ /** Milliseconds since the runtime started; DINT wraps after 24.8 days, so subtract to compare. */
17
+ export const runtimeClock = `TO_${scanClockType}(TIME_TO_UDINT(TIME()))`;
18
+
19
+ /** The scan's clock of a program that calls `now()`: where a scan's time is held while the scan runs. */
20
+ export interface ScanClock {
21
+ /** The global list that holds the clock. */
22
+ list: string;
23
+ /** The time the running scan began, which every `now()` reads. */
24
+ now: string;
25
+ /**
26
+ * By task, where its scan keeps the clock of the scan it interrupted. A program with one task
27
+ * has none.
28
+ */
29
+ interrupted: ReadonlyMap<string, string>;
30
+ }
31
+
32
+ const readsClock = (value: CoreExpression): boolean =>
33
+ (value.kind === "unary" && value.operator === "clock") ||
34
+ subexpressions(value).some(readsClock);
35
+
36
+ const anyReadsClock = (items: readonly CoreStatement[]): boolean =>
37
+ items.some(
38
+ (item) =>
39
+ statementExpressions(item).some(readsClock) ||
40
+ nestedBodies(item).some(anyReadsClock),
41
+ );
42
+
43
+ /** The scan clock's names, for a program in which some routine calls `now()`. */
44
+ export function planScanClock(
45
+ core: VerifiedCoreModule,
46
+ tasks: readonly Task[],
47
+ objectNames: Names,
48
+ ): ScanClock | undefined {
49
+ if (
50
+ ![...core.functions, ...core.blocks].some((routine) =>
51
+ anyReadsClock(routine.body),
52
+ )
53
+ ) {
54
+ return undefined;
55
+ }
56
+ const list = objectNames.allocateObject("GVL", "TsplcScan");
57
+ const fields = new Names();
58
+ const now = fields.allocate("clock");
59
+ return {
60
+ list,
61
+ now: `${list}.${now}`,
62
+ interrupted: new Map(
63
+ tasks.length > 1
64
+ ? tasks.map((task) => [
65
+ task.name,
66
+ `${list}.${fields.allocate(`interrupted_${task.name}`)}`,
67
+ ])
68
+ : [],
69
+ ),
70
+ };
71
+ }
72
+
73
+ const field = (qualified: string) =>
74
+ qualified.slice(qualified.indexOf(".") + 1);
75
+
76
+ export const emitScanClock = (clock: ScanClock): GeneratedObject => ({
77
+ id: "tsplc:scanClock",
78
+ kind: "globalList",
79
+ name: clock.list,
80
+ declaration: `{attribute 'qualified_only'}
81
+ VAR_GLOBAL
82
+ ${[clock.now, ...clock.interrupted.values()].map((name) => ` ${field(name)} : ${scanClockType};\n`).join("")}END_VAR
83
+ `,
84
+ });
85
+
86
+ /**
87
+ * What a task's cycle starts with: it reads the runtime's clock once, so every `now()` of the scan
88
+ * returns one time. A task that interrupts another's scan runs to its end before that scan
89
+ * resumes, so it keeps the interrupted scan's time for `restoreScanClock` to put back.
90
+ */
91
+ export const latchScanClock = (clock: ScanClock, task: string): string[] => {
92
+ const interrupted = clock.interrupted.get(task);
93
+ return [
94
+ ...(interrupted ? [`${interrupted} := ${clock.now};`] : []),
95
+ `${clock.now} := ${runtimeClock};`,
96
+ ];
97
+ };
98
+
99
+ /** What a task's cycle ends with when it may have interrupted another task's scan. */
100
+ export const restoreScanClock = (clock: ScanClock, task: string): string[] => {
101
+ const interrupted = clock.interrupted.get(task);
102
+ return interrupted ? [`${clock.now} := ${interrupted};`] : [];
103
+ };
@@ -13,6 +13,7 @@ import { Names } from "./names";
13
13
  import { NumericLowering } from "./numeric";
14
14
  import type { CodesysPlan } from "./plan";
15
15
  import { required } from "./required";
16
+ import { planScanClock } from "./scan-clock";
16
17
  import { accessedStorage } from "./task-access";
17
18
 
18
19
  /** The names a routine's ST gives its parameters, locals and the block state it reaches. */
@@ -63,11 +64,19 @@ export function globalSymbols(plan: CodesysPlan) {
63
64
  .map((fn) => fn.id),
64
65
  );
65
66
  const globalNames = planGlobalNames(core, plan.programNames);
67
+ const scanClock = planScanClock(
68
+ core,
69
+ plan.deployment.tasks,
70
+ globalNames.names,
71
+ );
66
72
  return {
67
73
  ...globalNames,
68
74
  blocks: coreTables(core).blocks,
69
- numeric: new NumericLowering(globalNames.typeMap, (label) =>
70
- globalNames.names.allocate(label),
75
+ scanClock,
76
+ numeric: new NumericLowering(
77
+ globalNames.typeMap,
78
+ (label) => globalNames.names.allocate(label),
79
+ scanClock?.now,
71
80
  ),
72
81
  programRoutines,
73
82
  };
@@ -87,8 +87,16 @@ export const startRuntime = async (options: RuntimeOptions) => {
87
87
  slots?.transport ??
88
88
  (baseUrl === null ? null : httpTransport(http, baseUrl));
89
89
 
90
- /** The task whose scan runs, or last ran: continuations run in their caller's task. */
91
- const current = { task: tasks[0]?.name ?? "", scan: 0, scanning: false };
90
+ /**
91
+ * The task whose scan runs, or last ran: continuations run in their caller's task. `time` is
92
+ * the clock as that scan read it when it began.
93
+ */
94
+ const current = {
95
+ task: tasks[0]?.name ?? "",
96
+ scan: 0,
97
+ scanning: false,
98
+ time: 0,
99
+ };
92
100
  const diagnostics = { count: 0, lastError: 0 };
93
101
  const records = createTelemetry({
94
102
  build: manifest.build.id,
@@ -141,9 +149,10 @@ export const startRuntime = async (options: RuntimeOptions) => {
141
149
  ]),
142
150
  ),
143
151
  sdk: {
144
- "@tsplc/compiler/clock": { now } satisfies SdkModule<
145
- typeof import("../../types/clock")
146
- >,
152
+ "@tsplc/compiler/clock": {
153
+ // Awaited code resumes between scans here, where no scan's time stands, so it reads the clock itself.
154
+ now: () => (current.scanning ? current.time : now()),
155
+ } satisfies SdkModule<typeof import("../../types/clock")>,
147
156
  "@tsplc/compiler/retain": { persist, retain } satisfies SdkModule<
148
157
  typeof import("../../types/retain")
149
158
  >,
@@ -262,6 +271,7 @@ export const startRuntime = async (options: RuntimeOptions) => {
262
271
  task: task.name,
263
272
  scan: state.scan,
264
273
  scanning: true,
274
+ time: now(),
265
275
  });
266
276
  try {
267
277
  records.send(task.name, state.scan);
package/stdlib/clock.ts CHANGED
@@ -1,4 +1,8 @@
1
1
  import { plcTime } from "./plc-time";
2
2
 
3
- /** Milliseconds since the process started, as the PLC's `now()` counts them in a DINT; used when a program runs under Bun. */
3
+ /**
4
+ * Milliseconds since the process started, as the PLC's `now()` counts them in a DINT; used when a
5
+ * program runs under Bun. Each call reads the clock: holding one time for a scan is the Bun
6
+ * runtime's to do, as only it knows when a scan runs.
7
+ */
4
8
  export const now = (): number => plcTime() | 0;
package/types/clock.d.ts CHANGED
@@ -1,4 +1,8 @@
1
1
  import type { DINT } from "./index.d.ts";
2
2
 
3
- /** Milliseconds since the PLC runtime started. It wraps after 24.8 days, so compare times by subtracting: `now() - since >= 500`. */
3
+ /**
4
+ * The scan's clock: milliseconds since the PLC runtime started, read once when the scan began, so
5
+ * every call during one scan returns the same value. It wraps after 24.8 days, so compare times by
6
+ * subtracting: `now() - since >= 500`.
7
+ */
4
8
  export declare function now(): DINT;