@tsplc/compiler 0.5.8 → 0.5.9

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/dist/telemetry.js CHANGED
@@ -10,9 +10,11 @@ var jobError = {
10
10
  malformedResponse: 4,
11
11
  network: 5,
12
12
  tls: 6,
13
- noRequestSlot: 7
13
+ noRequestSlot: 7,
14
+ codeChanged: 11001
14
15
  };
15
16
  var httpErrors = { base: 1e4, last: 10999 };
17
+ var reservedErrors = { first: 11000, last: 11099 };
16
18
  var jobErrors = {
17
19
  [jobError.cancelled]: "cancelled",
18
20
  [jobError.timeout]: "timeout",
@@ -21,12 +23,16 @@ var jobErrors = {
21
23
  [jobError.network]: "network error or server restarted",
22
24
  [jobError.tls]: "TLS error",
23
25
  [jobError.noRequestSlot]: "no free request slot",
26
+ [jobError.codeChanged]: "an online change replaced the job's code while it ran",
24
27
  [httpErrors.base]: "HTTP status: 10000 + status code"
25
28
  };
26
29
  var errorName = (code) => {
27
30
  if (code > httpErrors.base && code <= httpErrors.last) {
28
31
  return `HTTP ${code - httpErrors.base}`;
29
32
  }
33
+ if (code >= reservedErrors.first && code <= reservedErrors.last) {
34
+ return jobErrors[code];
35
+ }
30
36
  return code < httpErrors.base ? jobErrors[code] : undefined;
31
37
  };
32
38
 
@@ -106,5 +112,5 @@ export {
106
112
  telemetry
107
113
  };
108
114
 
109
- //# debugId=B79F687B98CD337A64756E2164756E21
115
+ //# debugId=4CC89CB4D7F08DDB64756E2164756E21
110
116
  //# sourceMappingURL=telemetry.js.map
@@ -3,10 +3,10 @@
3
3
  "sources": ["../stdlib/telemetry.ts", "../src/ir/job-errors.ts", "../stdlib/clock.ts"],
4
4
  "sourcesContent": [
5
5
  "import { relative } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { errorName } from \"../src/ir/job-errors\";\nimport { now } from \"./clock\";\n\ntype Reported = Readonly<Record<string, unknown>>;\nclass Text {\n\tconstructor(readonly value: string) {}\n}\ntype Value = boolean | number | bigint | string | Text;\ntype Properties = Readonly<Record<string, Value>>;\n\nconst module = fileURLToPath(import.meta.url);\nlet collector: ((record: Reported) => void) | undefined;\n\n/** The program's call: the first stack frame outside this module, relative to the working directory. */\nconst source = () => {\n\tfor (const line of new Error().stack?.split(\"\\n\") ?? []) {\n\t\tconst [, file, lineNumber] =\n\t\t\t/\\(?((?:\\/|[A-Za-z]:\\\\)[^():]+):(\\d+):\\d+\\)?$/.exec(line) ?? [];\n\t\tif (file && file !== module) {\n\t\t\treturn `${relative(process.cwd(), file).replaceAll(\"\\\\\", \"/\")}:${lineNumber}`;\n\t\t}\n\t}\n\treturn \"\";\n};\n\nconst reportedValue = (value: Value) => {\n\tif (value instanceof Text) {\n\t\treturn value.value;\n\t}\n\tif (typeof value === \"bigint\") {\n\t\treturn Number(value);\n\t}\n\treturn value;\n};\n\nconst exceptionName = (error: unknown) => {\n\tif (typeof error === \"number\") {\n\t\treturn errorName(error);\n\t}\n\treturn error instanceof Error ? error.message : String(error);\n};\n\nconst report = (record: Reported, properties: Properties = {}) =>\n\tcollector?.({\n\t\t...record,\n\t\tproperties: Object.fromEntries(\n\t\t\tObject.entries(properties).map(([name, value]) => [\n\t\t\t\tname,\n\t\t\t\treportedValue(value),\n\t\t\t]),\n\t\t),\n\t\tsource: source(),\n\t\tscan: 0,\n\t\ttime: now(),\n\t});\n\n/** What a PLC program's `telemetry` calls do under Bun; see `types/telemetry.d.ts`. */\nexport const telemetry = {\n\tcapture: (event: string, properties?: Properties) =>\n\t\treport({ kind: \"event\", event }, properties),\n\tinfo: (message: string, properties?: Properties) =>\n\t\treport({ kind: \"log\", level: \"info\", message }, properties),\n\twarn: (message: string, properties?: Properties) =>\n\t\treport({ kind: \"log\", level: \"warn\", message }, properties),\n\terror: (message: string, properties?: Properties) =>\n\t\treport({ kind: \"log\", level: \"error\", message }, properties),\n\t// Under Bun a failure can be a thrown Error rather than a code; it is sent as code 0 with its message.\n\tcaptureException: (error: unknown, properties?: Properties) => {\n\t\tconst code = typeof error === \"number\" ? error : 0;\n\t\tconst name = exceptionName(error);\n\t\treport(\n\t\t\t{ kind: \"exception\", code, ...(name && { name }), handled: true },\n\t\t\tproperties,\n\t\t);\n\t},\n\ttext: (bytes: readonly number[], length: number) => {\n\t\tconst sent = bytes.slice(0, Math.max(0, Math.min(length, bytes.length)));\n\t\tconst end = sent.indexOf(0);\n\t\treturn new Text(\n\t\t\tnew TextDecoder().decode(\n\t\t\t\tUint8Array.from(end < 0 ? sent : sent.slice(0, end)),\n\t\t\t),\n\t\t);\n\t},\n};\n\nexport const onTelemetry = (next: (record: Reported) => void) => {\n\tcollector = next;\n\treturn () => {\n\t\tif (collector === next) {\n\t\t\tcollector = undefined;\n\t\t}\n\t};\n};\n",
6
- "/** Job error codes by meaning, as generated async blocks and service calls set them. */\nexport const jobError = {\n\tcancelled: 1,\n\ttimeout: 2,\n\ttooLarge: 3,\n\tmalformedResponse: 4,\n\tnetwork: 5,\n\ttls: 6,\n\tnoRequestSlot: 7,\n} as const;\n\n/** An HTTP response fails a job with `base` + its status, up to `last`. */\nexport const httpErrors = { base: 10000, last: 10999 };\n\n/** Job error codes, as every generated async block and service call reports them. */\nexport const jobErrors: Record<string, string> = {\n\t[jobError.cancelled]: \"cancelled\",\n\t[jobError.timeout]: \"timeout\",\n\t[jobError.tooLarge]: \"request or response too large to encode\",\n\t[jobError.malformedResponse]: \"malformed response\",\n\t[jobError.network]: \"network error or server restarted\",\n\t[jobError.tls]: \"TLS error\",\n\t[jobError.noRequestSlot]: \"no free request slot\",\n\t[httpErrors.base]: \"HTTP status: 10000 + status code\",\n};\n\n/** What a telemetry exception record calls an error code: its meaning when it is a job error. */\nexport const errorName = (code: number): string | undefined => {\n\tif (code > httpErrors.base && code <= httpErrors.last) {\n\t\treturn `HTTP ${code - httpErrors.base}`;\n\t}\n\treturn code < httpErrors.base ? jobErrors[code] : undefined;\n};\n",
6
+ "/** Job error codes by meaning, as generated async blocks and service calls set them. */\nexport const jobError = {\n\tcancelled: 1,\n\ttimeout: 2,\n\ttooLarge: 3,\n\tmalformedResponse: 4,\n\tnetwork: 5,\n\ttls: 6,\n\tnoRequestSlot: 7,\n\t/**\n\t * An online change replaced the code of a job that was running: its step and stored state\n\t * were made for the old code, so it stops instead of resuming in the new. Like `cancelled`,\n\t * it skips `catch`, so a retry can't send a request twice.\n\t */\n\tcodeChanged: 11001,\n} as const;\n\n/** An HTTP response fails a job with `base` + its status, up to `last`. */\nexport const httpErrors = { base: 10000, last: 10999 };\n\n/** Codes tsPLC itself reports from 11000 on, which a program's own `throw` may not use. */\nexport const reservedErrors = { first: 11000, last: 11099 };\n\n/** Job error codes, as every generated async block and service call reports them. */\nexport const jobErrors: Record<string, string> = {\n\t[jobError.cancelled]: \"cancelled\",\n\t[jobError.timeout]: \"timeout\",\n\t[jobError.tooLarge]: \"request or response too large to encode\",\n\t[jobError.malformedResponse]: \"malformed response\",\n\t[jobError.network]: \"network error or server restarted\",\n\t[jobError.tls]: \"TLS error\",\n\t[jobError.noRequestSlot]: \"no free request slot\",\n\t[jobError.codeChanged]:\n\t\t\"an online change replaced the job's code while it ran\",\n\t[httpErrors.base]: \"HTTP status: 10000 + status code\",\n};\n\n/** What a telemetry exception record calls an error code: its meaning when it is a job error. */\nexport const errorName = (code: number): string | undefined => {\n\tif (code > httpErrors.base && code <= httpErrors.last) {\n\t\treturn `HTTP ${code - httpErrors.base}`;\n\t}\n\tif (code >= reservedErrors.first && code <= reservedErrors.last) {\n\t\treturn jobErrors[code];\n\t}\n\treturn code < httpErrors.base ? jobErrors[code] : undefined;\n};\n",
7
7
  "/** Milliseconds since the process started, as the PLC's `now()` counts them; used when a program runs under Bun. */\nexport const now = (): number => Math.floor(performance.now());\n"
8
8
  ],
9
- "mappings": ";AAAA;AACA;;;ACAO,IAAM,WAAW;AAAA,EACvB,WAAW;AAAA,EACX,SAAS;AAAA,EACT,UAAU;AAAA,EACV,mBAAmB;AAAA,EACnB,SAAS;AAAA,EACT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,MAAM,CAAC,SAAiB,eACvB,OAAO,EAAE,MAAM,OAAO,OAAO,QAAQ,QAAQ,GAAG,UAAU;AAAA,EAC3D,MAAM,CAAC,SAAiB,eACvB,OAAO,EAAE,MAAM,OAAO,OAAO,QAAQ,QAAQ,GAAG,UAAU;AAAA,EAC3D,OAAO,CAAC,SAAiB,eACxB,OAAO,EAAE,MAAM,OAAO,OAAO,SAAS,QAAQ,GAAG,UAAU;AAAA,EAE5D,kBAAkB,CAAC,OAAgB,eAA4B;AAAA,IAC9D,MAAM,OAAO,OAAO,UAAU,WAAW,QAAQ;AAAA,IACjD,MAAM,OAAO,cAAc,KAAK;AAAA,IAChC,OACC,EAAE,MAAM,aAAa,SAAU,QAAQ,EAAE,KAAK,GAAI,SAAS,KAAK,GAChE,UACD;AAAA;AAAA,EAED,MAAM,CAAC,OAA0B,WAAmB;AAAA,IACnD,MAAM,OAAO,MAAM,MAAM,GAAG,KAAK,IAAI,GAAG,KAAK,IAAI,QAAQ,MAAM,MAAM,CAAC,CAAC;AAAA,IACvE,MAAM,MAAM,KAAK,QAAQ,CAAC;AAAA,IAC1B,OAAO,IAAI,KACV,IAAI,YAAY,EAAE,OACjB,WAAW,KAAK,MAAM,IAAI,OAAO,KAAK,MAAM,GAAG,GAAG,CAAC,CACpD,CACD;AAAA;AAEF;AAEO,IAAM,cAAc,CAAC,SAAqC;AAAA,EAChE,YAAY;AAAA,EACZ,OAAO,MAAM;AAAA,IACZ,IAAI,cAAc,MAAM;AAAA,MACvB,YAAY;AAAA,IACb;AAAA;AAAA;",
10
+ "debugId": "4CC89CB4D7F08DDB64756E2164756E21",
11
11
  "names": []
12
12
  }
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.8",
20
+ "version": "0.5.9",
21
21
  "type": "module",
22
22
  "exports": {
23
23
  ".": {
@@ -106,17 +106,17 @@
106
106
  "bun": ">=1.4.3"
107
107
  },
108
108
  "dependencies": {
109
- "@tsplc/agent": "0.5.8",
110
- "@tsplc/build": "0.5.8",
111
- "@tsplc/config": "0.5.8",
112
- "@tsplc/debug": "0.5.8",
113
- "@tsplc/opcua": "0.5.8",
114
- "@tsplc/typegen": "0.5.8",
109
+ "@tsplc/agent": "0.5.9",
110
+ "@tsplc/build": "0.5.9",
111
+ "@tsplc/config": "0.5.9",
112
+ "@tsplc/debug": "0.5.9",
113
+ "@tsplc/opcua": "0.5.9",
114
+ "@tsplc/typegen": "0.5.9",
115
115
  "typescript": "6.0.3",
116
116
  "zod": "4.3.6",
117
117
  "@types/bun": "1.4.2",
118
- "@tsplc/server": "0.5.8",
119
- "@tsplc/iec": "0.5.8"
118
+ "@tsplc/server": "0.5.9",
119
+ "@tsplc/iec": "0.5.9"
120
120
  },
121
121
  "bin": {
122
122
  "tsplc": "./dist/cli.js"
@@ -26,7 +26,7 @@ import {
26
26
  } from "./instrumentation";
27
27
  import { debugManifest } from "./manifest";
28
28
  import { type CodesysPlan, diagnostic, isCodesysPlan } from "./plan";
29
- import { emitScanProgram } from "./programs";
29
+ import { emitScanProgram, emitTaskWrappers } from "./programs";
30
30
  import { machineInterfaces, publishedSymbols } from "./publication";
31
31
  import { emitRoutine } from "./routines";
32
32
  import { Sources } from "./sources";
@@ -129,6 +129,7 @@ export function emitCodesys(plan: CodesysPlan): CodesysBundle {
129
129
  for (const program of core.programs) {
130
130
  objects.push(emitScanProgram(context, ioList.channels, program));
131
131
  }
132
+ objects.push(...emitTaskWrappers(context, objects));
132
133
  // Explanations index the manifest's sources and functions, and its digest of them feeds the build id.
133
134
  const sources = new Sources(plan.project.root);
134
135
  const functionIds = new Map<string, number>();
@@ -9,6 +9,7 @@ import type { Controller, DeviceTree } from "@tsplc/config";
9
9
  import { engineeringBuildSchema, resolveConfig } from "@tsplc/config/build";
10
10
  import { z } from "zod";
11
11
  import type { CodesysPlan } from "./plan";
12
+ import { taskPrograms } from "./programs";
12
13
 
13
14
  export const engineeringSchema = z.strictObject({
14
15
  kind: z.literal("v3.5"),
@@ -48,18 +49,32 @@ export function codesysBuildConfig(
48
49
  return [program.name, generated] as const;
49
50
  }),
50
51
  );
51
- const tasks = plan.deployment.tasks.map((task) => ({
52
- ...task,
53
- programs: task.programs.map((name) => {
54
- const program = programs.get(name);
55
- if (!program) {
56
- throw new Error(
57
- `Task ${task.name} references a missing generated PROGRAM ${name}.`,
58
- );
59
- }
60
- return program.name;
61
- }),
62
- }));
52
+ const tasks = plan.deployment.tasks.map((task) => {
53
+ const { configured, wrapper } = taskPrograms(plan, task);
54
+ const wrapperObject = bundle.objects.find(
55
+ (object) => object.id === wrapper.id && object.kind === "program",
56
+ );
57
+ if (!wrapperObject) {
58
+ throw new Error(
59
+ `Generated bundle has no wrapper PROGRAM for ${task.name}.`,
60
+ );
61
+ }
62
+ return {
63
+ ...task,
64
+ programs: [
65
+ ...configured.map((name) => {
66
+ const program = programs.get(name);
67
+ if (!program) {
68
+ throw new Error(
69
+ `Task ${task.name} references a missing generated PROGRAM ${name}.`,
70
+ );
71
+ }
72
+ return program.name;
73
+ }),
74
+ wrapperObject.name,
75
+ ],
76
+ };
77
+ });
63
78
  const first = plan.core.programs[0];
64
79
  const entry = first && programs.get(first.name);
65
80
  if (!entry) {
@@ -9,7 +9,6 @@ import {
9
9
  forwardTemporaries,
10
10
  instancedBlock,
11
11
  isVerifiedCore,
12
- joinPrograms,
13
12
  nestedBodies,
14
13
  type PlcType,
15
14
  type SourceSpan,
@@ -251,9 +250,10 @@ export function planCodesys(
251
250
  type Report = (message: string, span?: SourceSpan) => void;
252
251
 
253
252
  /**
254
- * Routines specialized per instance, merged where they run the same code in the same task, each
255
- * task's continuation programs joined into one, calls of routines that only return a constant
256
- * replaced by it, and temporaries read right after they are written folded into their reader.
253
+ * Routines specialized per instance, merged where they run the same code in the same task, calls
254
+ * of routines that only return a constant replaced by it, and temporaries read right after they
255
+ * are written folded into their reader. Continuation programs stay apart: each task's wrapper
256
+ * calls them, and joining them named the joined program after whichever came first.
257
257
  * The debugger's instrumentation is written per statement of each routine, so a program built
258
258
  * with `debug` keeps every instance's own routine, as does one whose scheduling is invalid: its
259
259
  * diagnostics name the routines as written.
@@ -268,33 +268,20 @@ function sharedRoutines(
268
268
  return unshared;
269
269
  }
270
270
  const issues: string[] = [];
271
- const scheduled = {
272
- tasks: schedulePrograms(core, deployment.tasks, (message) => {
273
- issues.push(message);
274
- }),
275
- };
271
+ schedulePrograms(core, deployment.tasks, (message) => {
272
+ issues.push(message);
273
+ });
276
274
  if (issues.length) {
277
275
  return unshared;
278
276
  }
279
- const continuations = new Set(
280
- core.programs.flatMap((program) =>
281
- program.continuation ? [program.name] : [],
282
- ),
283
- );
284
- const joined = joinPrograms(
285
- core,
286
- scheduled.tasks.map((task) =>
287
- task.programs.filter((name) => continuations.has(name)),
288
- ),
289
- );
290
- const folded = foldConstantRoutines(joined.core);
277
+ const folded = foldConstantRoutines(core);
291
278
  const tasks = routineTasks(folded.core, {
292
279
  tasks: schedulePrograms(folded.core, deployment.tasks, () => {}),
293
280
  });
294
281
  const shared = shareRoutines(folded.core, (routine) => tasks.get(routine.id));
295
282
  return {
296
283
  core: forwardTemporaries(shared.core),
297
- routines: new Map([...joined.routines, ...shared.routines]),
284
+ routines: shared.routines,
298
285
  };
299
286
  }
300
287
 
@@ -1,5 +1,6 @@
1
- import type { GeneratedObject, PlcProgram } from "@tsplc/compiler/ir";
1
+ import type { GeneratedObject, PlcProgram, Task } from "@tsplc/compiler/ir";
2
2
  import type { IoChannel } from "./global-lists";
3
+ import type { CodesysPlan } from "./plan";
3
4
  import { type EmissionContext, required } from "./symbols";
4
5
  import { accessedStorage } from "./task-access";
5
6
 
@@ -53,3 +54,62 @@ export function emitScanProgram(
53
54
  implementation: `${lines.join("\n")}\n`,
54
55
  };
55
56
  }
57
+
58
+ /**
59
+ * How a task's program list splits: the programs its configuration names, which it calls itself,
60
+ * and the ones the compiler adds (detached continuations, background jobs), which it calls through
61
+ * one wrapper. A task's configuration then depends on the project's configuration alone, so adding
62
+ * a continuation or a background job at an existing interval changes code, which an online change
63
+ * applies, never the task configuration, which it refuses.
64
+ */
65
+ export const taskPrograms = (plan: CodesysPlan, task: Task) => {
66
+ const programs = new Map(
67
+ plan.core.programs.map((program) => [program.name, program]),
68
+ );
69
+ const generated = (name: string) => {
70
+ const program = programs.get(name);
71
+ return Boolean(program?.continuation || program?.background);
72
+ };
73
+ const background = task.programs.every(
74
+ (name) => programs.get(name)?.background,
75
+ );
76
+ return {
77
+ configured: task.programs.filter((name) => !generated(name)),
78
+ wrapped: task.programs.filter(generated),
79
+ wrapper: {
80
+ id: `tsplc:task:${task.name}`,
81
+ label: background ? task.name : `TsplcContinuations_${task.name}`,
82
+ },
83
+ };
84
+ };
85
+
86
+ /** Each task's wrapper PROGRAM, which calls the programs the compiler added to it in their order. */
87
+ export function emitTaskWrappers(
88
+ { plan, symbols }: EmissionContext,
89
+ objects: readonly GeneratedObject[],
90
+ ): GeneratedObject[] {
91
+ const programObjects = new Map(
92
+ plan.core.programs.map((program) => [
93
+ program.name,
94
+ required(
95
+ objects.find(
96
+ (object) => object.id === program.id && object.kind === "program",
97
+ ),
98
+ ),
99
+ ]),
100
+ );
101
+ return plan.deployment.tasks.map((task) => {
102
+ const { wrapped, wrapper } = taskPrograms(plan, task);
103
+ const name = symbols.names.allocateObject("PRG", wrapper.label);
104
+ const calls = wrapped.map(
105
+ (program) => `${required(programObjects.get(program)).name}();`,
106
+ );
107
+ return {
108
+ id: wrapper.id,
109
+ kind: "program",
110
+ name,
111
+ declaration: `PROGRAM ${name}\n`,
112
+ implementation: calls.length ? `${calls.join("\n")}\n` : ";\n",
113
+ };
114
+ });
115
+ }
@@ -75,7 +75,7 @@ export class CodesysTypes {
75
75
  if (type.kind === "record" || type.kind === "enum") {
76
76
  const prefix = type.kind === "record" ? "ST" : "E";
77
77
  this.names.set(type.id, names.allocateObject(prefix, label));
78
- } else {
78
+ } else if (!this.inline(type)) {
79
79
  this.names.set(type.id, names.allocate(`T_${label}`));
80
80
  }
81
81
  }
@@ -91,19 +91,13 @@ export class CodesysTypes {
91
91
  }
92
92
  }
93
93
 
94
- // A block array is declared in place: a function block cannot be a data type's element.
95
- for (const type of types.values()) {
96
- if (type.kind === "array" && instancedBlock(type.id, types)) {
97
- this.names.set(
98
- type.id,
99
- `ARRAY[${type.lowerBound}..${type.lowerBound + type.length - 1}] OF ${this.name(type.element)}`,
100
- );
101
- }
102
- }
103
-
104
94
  // Verified layouts are acyclic. Emit child DUTs first, then their containing DUT.
105
95
  const emitted = new Set<string>();
106
96
  const emit = (type: PlcType): void => {
97
+ if (type.kind === "array" && this.inline(type)) {
98
+ emit(this.type(type.element));
99
+ return;
100
+ }
107
101
  if (
108
102
  instancedBlock(type.id, types) ||
109
103
  !this.names.has(type.id) ||
@@ -207,7 +201,35 @@ END_TYPE
207
201
  }
208
202
 
209
203
  name(id: string): string {
210
- return this.names.get(id) ?? id;
204
+ const named = this.names.get(id);
205
+ if (named !== undefined) {
206
+ return named;
207
+ }
208
+ const type = this.types.get(id);
209
+ if (type?.kind === "string" && this.inline(type)) {
210
+ return `${stringTypeName(type)}(${type.capacity})`;
211
+ }
212
+ if (type?.kind === "array" && this.inline(type)) {
213
+ return `ARRAY[${type.lowerBound}..${type.lowerBound + type.length - 1}] OF ${this.name(type.element)}`;
214
+ }
215
+ return id;
216
+ }
217
+
218
+ /**
219
+ * Whether a type is declared in place rather than as a data type of its own. A named alias of
220
+ * an array or a string would name its length, so a length change would change the variable's
221
+ * type, which an online change refuses; in place it changes only the variable's layout. A block
222
+ * array is always in place: a function block cannot be a data type's element. Keyed arrays keep
223
+ * their alias, whose attribute publishes each key.
224
+ */
225
+ private inline(type: PlcType): boolean {
226
+ if (type.kind === "string") {
227
+ return true;
228
+ }
229
+ return (
230
+ type.kind === "array" &&
231
+ (!type.index || instancedBlock(type.id, this.types) !== undefined)
232
+ );
211
233
  }
212
234
 
213
235
  field(id: string, name: string): string {
@@ -8,6 +8,7 @@ import {
8
8
  } from "@tsplc/compiler/ir";
9
9
  import ts from "typescript";
10
10
  import { lowerCoroutine } from "./coroutines";
11
+ import { GeneratedNames } from "./generated-names";
11
12
  import { runtimeSources } from "./module-graph";
12
13
  import {
13
14
  type Edit,
@@ -67,8 +68,8 @@ export interface AsyncContext {
67
68
  /** Whether a node names the SDK declaration `name`. */
68
69
  namesSdk: (node: ts.Node, name: string) => boolean;
69
70
  fail: (node: ts.Node, message: string) => never;
70
- /** The next number for a generated name. */
71
- sequence: () => number;
71
+ /** Names for generated declarations, from the source node each stands for. */
72
+ names: GeneratedNames;
72
73
  }
73
74
 
74
75
  /** One source file being rewritten: edits to its text and declarations added around it. */
@@ -94,6 +95,7 @@ export const lowerAsync = (
94
95
  program: ts.Program,
95
96
  sdk: string,
96
97
  positions: Positions,
98
+ root: string,
97
99
  ): AsyncLowering => {
98
100
  const result: AsyncLowering = {
99
101
  sources: new Map(),
@@ -109,11 +111,11 @@ export const lowerAsync = (
109
111
  const fail: (node: ts.Node, message: string) => never = (node, message) => {
110
112
  throw new SemanticError(asyncDiagnostic(positions, node, message));
111
113
  };
112
- const { functions, methods } = asyncRoutines(program, symbol);
114
+ const names = new GeneratedNames(root);
115
+ const { functions, methods } = asyncRoutines(program, symbol, names);
113
116
  if (!functions.size) {
114
117
  return result;
115
118
  }
116
- let sequence = 0;
117
119
  const context: AsyncContext = {
118
120
  checker,
119
121
  positions,
@@ -125,7 +127,7 @@ export const lowerAsync = (
125
127
  symbol,
126
128
  namesSdk: (node, name) => namesSdk(checker, sdk, node, name),
127
129
  fail,
128
- sequence: () => sequence++,
130
+ names,
129
131
  };
130
132
  const sources = runtimeSources(program).filter(
131
133
  (source) => !source.isDeclarationFile,
@@ -143,6 +145,7 @@ export const lowerAsync = (
143
145
  function asyncRoutines(
144
146
  program: ts.Program,
145
147
  symbol: (node: ts.Node) => ts.Symbol | undefined,
148
+ names: GeneratedNames,
146
149
  ) {
147
150
  const functions = new Map<ts.Symbol, Routine>();
148
151
  const methods = new Map<ts.Symbol, MethodMembers>();
@@ -160,7 +163,7 @@ function asyncRoutines(
160
163
  }
161
164
  functions.set(symbol(fn.name)!, fn);
162
165
  if (ts.isMethodDeclaration(fn)) {
163
- const prefix = `tsplcAsync${fn.name.getText(source)}${fn.getStart(source)}`;
166
+ const prefix = names.name(`tsplcAsync${fn.name.getText(source)}`, fn);
164
167
  methods.set(symbol(fn.name)!, {
165
168
  start: `${prefix}Start`,
166
169
  reset: `${prefix}Reset`,
@@ -260,7 +263,7 @@ function addInstanceEntries(
260
263
  const name = declaration.name.text;
261
264
  // One entry polls all of an instance's sites, in their order: they share its task.
262
265
  if (polls?.length) {
263
- const entry = `tsplcContinuation${context.sequence()}`;
266
+ const entry = context.names.name("tsplcContinuation", declaration);
264
267
  const calls = polls.map((poll) =>
265
268
  instance.first === undefined
266
269
  ? `${name}.${poll}();`
@@ -279,7 +282,10 @@ function addInstanceEntries(
279
282
  });
280
283
  }
281
284
  for (const job of jobs ?? []) {
282
- const entry = `tsplcBackground${context.sequence()}`;
285
+ const entry = context.names.name(
286
+ `tsplcBackground_${job.method}`,
287
+ declaration,
288
+ );
283
289
  entries.push(
284
290
  from(node, `export function ${entry}():void{${name}.${job.method}();}`),
285
291
  );
@@ -1,5 +1,5 @@
1
1
  // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
2
- import { jobError } from "@tsplc/compiler/ir";
2
+ import { identityDigest, jobError, reservedErrors } from "@tsplc/compiler/ir";
3
3
  import ts from "typescript";
4
4
  import type {
5
5
  AsyncContext,
@@ -10,6 +10,7 @@ import type {
10
10
  } from "./async";
11
11
  import { staticString } from "./configuration";
12
12
  import { copyValue } from "./cooperative";
13
+ import type { GeneratedNames } from "./generated-names";
13
14
  import { importSpecifier } from "./module-graph";
14
15
  import {
15
16
  copied,
@@ -58,8 +59,16 @@ const containsAwait = (node: ts.Node, source: ts.SourceFile): boolean =>
58
59
  node.getChildren(source).some((child) => containsAwait(child, source));
59
60
 
60
61
  /** The prefix of the type aliases a routine's module exports for its result and arguments. */
61
- export const aliasPrefix = (fn: Routine) =>
62
- `TsplcAsync${fn.name.getText(fn.getSourceFile())}${fn.getStart(fn.getSourceFile())}`;
62
+ export const aliasPrefix = (names: GeneratedNames, fn: Routine) =>
63
+ names.name(`TsplcAsync${fn.name.getText(fn.getSourceFile())}`, fn);
64
+
65
+ /**
66
+ * A job's code identity: its steps, their targets and the state they keep. A job stores it when it
67
+ * starts and stops with `codeChanged` when an online change brings other code, since its step and
68
+ * fields were made for the code it started with. Never 0, the value of a field an online change adds.
69
+ */
70
+ const codeDigest = (code: string): number =>
71
+ Number.parseInt(identityDigest(code), 16) || 1;
63
72
 
64
73
  /** Replaces an async routine with a block that runs it as a resumable state machine. */
65
74
  export function lowerCoroutine(
@@ -321,7 +330,7 @@ class Coroutine {
321
330
  return annotated;
322
331
  }
323
332
  // Another module's result type is named through the alias its coroutine exports.
324
- const type = `${aliasPrefix(called)}Result`;
333
+ const type = `${aliasPrefix(this.context.names, called)}Result`;
325
334
  const statement = `import type {${type}} from ${importSpecifier(source.fileName, called.getSourceFile().fileName)};`;
326
335
  if (!extra.some((item) => item.text === statement)) {
327
336
  extra.push(from(node, statement));
@@ -560,7 +569,10 @@ class Coroutine {
560
569
  this.context.fail(call, "GET requests cannot contain json.");
561
570
  }
562
571
  const responseType = this.text(response);
563
- const httpName = `Tsplc${rpc ? "Rpc" : "Http"}${this.context.sequence()}`;
572
+ const httpName = this.context.names.name(
573
+ `Tsplc${rpc ? "Rpc" : "Http"}`,
574
+ call,
575
+ );
564
576
  if (!json) {
565
577
  extra.push(from(call, `interface ${httpName}Request {reserved:BOOL}`));
566
578
  }
@@ -827,6 +839,16 @@ class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { pr
827
839
  "Async throw requires a numeric error code.",
828
840
  );
829
841
  }
842
+ if (
843
+ ts.isNumericLiteral(statement.expression) &&
844
+ Number(statement.expression.text) >= reservedErrors.first &&
845
+ Number(statement.expression.text) <= reservedErrors.last
846
+ ) {
847
+ this.context.fail(
848
+ statement,
849
+ `Error codes ${reservedErrors.first} to ${reservedErrors.last} are tsPLC's own; throw another code.`,
850
+ );
851
+ }
830
852
  return this.state(
831
853
  reject(this.rewrite(statement.expression)),
832
854
  statement,
@@ -1009,7 +1031,7 @@ class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { pr
1009
1031
  (error, cancellable) => {
1010
1032
  const recover = mapped`${field ? mapped`this.${field.name} = ${error};` : ""}this.step = ${caught};`;
1011
1033
  return cancellable
1012
- ? mapped`if(${error} === 1) {${this.failure(error)}} else {${recover}}`
1034
+ ? mapped`if(${error} === ${jobError.cancelled} || ${error} === ${jobError.codeChanged}) {${this.failure(error)}} else {${recover}}`
1013
1035
  : recover;
1014
1036
  },
1015
1037
  );
@@ -1081,21 +1103,38 @@ class ${httpName} extends FunctionBlock<${httpName}Input,${httpName}Output> { pr
1081
1103
  const exported = hasModifier(fn, ts.SyntaxKind.ExportKeyword)
1082
1104
  ? "export "
1083
1105
  : "";
1084
- const aliases = `export type ${aliasPrefix(fn)}Result = ${returnType};\n${parameters.map((p, i) => `export type ${aliasPrefix(fn)}Argument${i} = ${p.type};`).join("\n")}`;
1085
- return mapped`${aliases}\n${exported}class ${this.text(fn.name)} extends FunctionBlock<{cancel:BOOL}> {
1086
- private step:UINT=0; private cancelling:BOOL=false; private busy:BOOL=false; private done:BOOL=false; private error:UDINT=0; private value:${returnType}=defaultValue<${returnType}>();
1106
+ const prefix = aliasPrefix(this.context.names, fn);
1107
+ const aliases = `export type ${prefix}Result = ${returnType};\n${parameters.map((p, i) => `export type ${prefix}Argument${i} = ${p.type};`).join("\n")}`;
1108
+ const fields = `private step:UINT=0; private cancelling:BOOL=false; private busy:BOOL=false; private done:BOOL=false; private error:UDINT=0; private value:${returnType}=defaultValue<${returnType}>();
1087
1109
  ${[...this.fields.values()].map((f) => `private ${f.name}:${f.type}=defaultValue<${f.type}>();`).join("\n")}
1088
1110
  ${[...this.positionFields.values()].map((name) => `private ${name}:DINT=0;`).join("\n")}
1089
- ${this.children.join("\n")}
1090
- start(${parameters.map((p) => `${p.name}:${p.type}`).join(",")}):BOOL {if(this.busy || this.done)return false; ${parameters.map((p) => `this.${p.field} = ${copyValue(p.name, p.aggregate)};`).join(" ")} ${this.resets.join(" ")} this.value = defaultValue<${returnType}>(); this.error=0;this.cancelling=false;this.busy=true;this.done=false;this.step=${entry};return true;}
1091
- reset():void {${this.resets.join(" ")} this.busy=false;this.cancelling=false;this.done=false;this.error=0;this.step=0;}
1092
- snapshot():{busy:BOOL;done:BOOL;error:UDINT;result:${returnType}} {return {busy:this.busy,done:this.done,error:this.error,result:${copyValue("this.value", this.resultAggregate)}};}
1093
- protected execute(input:{cancel:BOOL}):void {if(!this.busy)return;if(input.cancel)this.cancelling=true;if(this.cancelling){${this.cancels.map((cancel) => `{${cancel}}`).join(" ")}${this.failure("1")}return;}for(let transition:DINT=0;transition<${this.states.size + 1};transition++){const previous:UINT=this.step;switch(this.step){${joined(
1111
+ ${this.children.join("\n")}`;
1112
+ const table = joined(
1094
1113
  [...this.states].map(
1095
1114
  ([id, body]) => mapped`case ${id}: {${body}} break;`,
1096
1115
  ),
1097
1116
  "\n",
1098
- )} }if(!this.busy||this.step===previous${[...this.yielding].map((id) => `||previous===${id}`).join("")})return;}}
1117
+ );
1118
+ const code = codeDigest(
1119
+ [
1120
+ fields,
1121
+ parameters.map((p) => `${p.field}:${p.type}`).join(","),
1122
+ entry,
1123
+ table.text,
1124
+ this.resets.join(" "),
1125
+ this.cancels.join(" "),
1126
+ [...this.yielding].join(","),
1127
+ ].join("\n"),
1128
+ );
1129
+ const { codeChanged } = jobError;
1130
+ return mapped`${aliases}\n${exported}class ${this.text(fn.name)} extends FunctionBlock<{cancel:BOOL}> {
1131
+ ${fields}
1132
+ private tsplcCode:UDINT=0; private tsplcPending:UDINT=0;
1133
+ start(${parameters.map((p) => `${p.name}:${p.type}`).join(",")}):BOOL {if(this.busy || this.done)return false; ${parameters.map((p) => `this.${p.field} = ${copyValue(p.name, p.aggregate)};`).join(" ")} ${this.resets.join(" ")} this.value = defaultValue<${returnType}>(); this.error=0;this.cancelling=false;this.tsplcPending=0;this.tsplcCode=${code};this.busy=true;this.done=false;this.step=${entry};return true;}
1134
+ reset():void {${this.resets.join(" ")} this.busy=false;this.cancelling=false;this.tsplcPending=0;this.done=false;this.error=0;this.step=0;}
1135
+ snapshot():{busy:BOOL;done:BOOL;error:UDINT;result:${returnType}} {if(this.done&&this.tsplcCode!==${code}){return {busy:false,done:true,error:${codeChanged},result:defaultValue<${returnType}>()};}return {busy:this.busy,done:this.done,error:this.error,result:${copyValue("this.value", this.resultAggregate)}};}
1136
+ protected execute(input:{cancel:BOOL}):void {if(!this.busy)return;if(this.tsplcCode!==${code}&&!this.cancelling){this.tsplcPending=${codeChanged};this.cancelling=true;}if(input.cancel)this.cancelling=true;if(this.cancelling){${this.cancels.map((cancel) => `{${cancel}}`).join(" ")}if(this.tsplcPending===0)this.tsplcPending=${jobError.cancelled};${this.failure("this.tsplcPending")}return;}for(let transition:DINT=0;transition<${this.states.size + 1};transition++){const previous:UINT=this.step;switch(this.step){${table}
1137
+ default: {this.tsplcPending=${codeChanged};this.cancelling=true;return;} }if(!this.busy||this.step===previous${[...this.yielding].map((id) => `||previous===${id}`).join("")})return;}}
1099
1138
 
1100
1139
  }`;
1101
1140
  }
@@ -1113,7 +1152,7 @@ protected execute(input:{cancel:BOOL}):void {if(!this.busy)return;if(input.cance
1113
1152
  const names = new Map(
1114
1153
  worker.members.map((member) => [
1115
1154
  member.name!.getText(parsed),
1116
- `tsplcAsync${this.fn.getStart(source)}_${member.name!.getText(parsed)}`,
1155
+ `${this.context.names.name("tsplcAsync", this.fn)}_${member.name!.getText(parsed)}`,
1117
1156
  ]),
1118
1157
  );
1119
1158
  names.set("start", method.start);
@@ -1,4 +1,5 @@
1
1
  // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
2
+ import { identityDigest } from "@tsplc/compiler/ir";
2
3
  import ts from "typescript";
3
4
  import { from, joined, type Mapped, mapped, type Part } from "../positions";
4
5
  import { unaliased } from "../sdk";
@@ -571,8 +572,11 @@ export class ExpressionSpecializer {
571
572
  if (known) {
572
573
  return known;
573
574
  }
575
+ const id = -1 - this.services.size;
576
+ // A service is called, never held, so no reference holds its id.
574
577
  const node: ModelNode = {
575
- id: -1 - this.services.size,
578
+ id,
579
+ reference: id,
576
580
  captured: { kind: "service", path },
577
581
  };
578
582
  this.services.set(path, node);
@@ -698,7 +702,11 @@ export class ExpressionSpecializer {
698
702
  if (!node.type) {
699
703
  throw new Error("A table needs a declared type.");
700
704
  }
701
- const name = `tsplcTable${this.tables.size + 1}`;
705
+ // Named for where setup put it: numbered by first read, two tables swapped names under one type.
706
+ const identity = this.model.identity(node);
707
+ const name = identity
708
+ ? `tsplcTable_${identityDigest(identity)}`
709
+ : `tsplcTable${this.tables.size + 1}`;
702
710
  this.tables.set(node.id, name);
703
711
  const type = this.layouts.text(node.type, { kind: "node", id: node.id });
704
712
  this.tableDeclarations.push(