@tsplc/compiler 0.2.21 → 0.4.0

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 (115) hide show
  1. package/README.md +1 -1
  2. package/dist/cli.js +280 -223
  3. package/dist/cli.js.map +12 -12
  4. package/dist/codesys.js +452 -330
  5. package/dist/codesys.js.map +24 -24
  6. package/dist/elaborate-capture.js +112 -7
  7. package/dist/elaborate-capture.js.map +5 -4
  8. package/dist/index.js +5682 -5407
  9. package/dist/index.js.map +39 -37
  10. package/dist/ir.js +1154 -327
  11. package/dist/ir.js.map +23 -20
  12. package/dist/project.js +68 -29
  13. package/dist/project.js.map +4 -4
  14. package/dist/retain.js +8 -0
  15. package/dist/retain.js.map +10 -0
  16. package/dist/server-check.js +59 -0
  17. package/dist/server-check.js.map +11 -0
  18. package/dist/telemetry.js +19 -10
  19. package/dist/telemetry.js.map +3 -3
  20. package/package.json +33 -12
  21. package/src/codesys/config.ts +1 -1
  22. package/src/codesys/debug.ts +7 -21
  23. package/src/codesys/engineering.ts +8 -12
  24. package/src/codesys/global-lists.ts +19 -17
  25. package/src/codesys/global-names.ts +3 -3
  26. package/src/codesys/http.ts +37 -34
  27. package/src/codesys/index.ts +5 -22
  28. package/src/codesys/instrumentation.ts +3 -1
  29. package/src/codesys/io-paths.ts +2 -1
  30. package/src/codesys/manifest.ts +35 -18
  31. package/src/codesys/numeric.ts +2 -4
  32. package/src/codesys/plan.ts +94 -26
  33. package/src/codesys/publication.ts +4 -3
  34. package/src/codesys/routines.ts +2 -2
  35. package/src/codesys/sources.ts +1 -0
  36. package/src/codesys/st-files.ts +86 -50
  37. package/src/codesys/storage.ts +44 -9
  38. package/src/codesys/task-access.ts +32 -10
  39. package/src/codesys/telemetry.ts +93 -46
  40. package/src/codesys/types.ts +81 -3
  41. package/src/codesys/vendor.ts +1 -1
  42. package/src/frontend/analyzer.ts +15 -14
  43. package/src/frontend/async.ts +23 -21
  44. package/src/frontend/blocks.ts +7 -6
  45. package/src/frontend/configuration.ts +8 -6
  46. package/src/frontend/const-functions.ts +5 -5
  47. package/src/frontend/cooperative.ts +2 -1
  48. package/src/frontend/coroutines.ts +24 -21
  49. package/src/frontend/elaborate/calls.ts +12 -7
  50. package/src/frontend/elaborate/capture-protocol.ts +103 -0
  51. package/src/frontend/elaborate/capture.ts +48 -19
  52. package/src/frontend/elaborate/dialect.ts +2 -2
  53. package/src/frontend/elaborate/expressions.ts +9 -6
  54. package/src/frontend/elaborate/frame.ts +1 -1
  55. package/src/frontend/elaborate/graph.ts +27 -43
  56. package/src/frontend/elaborate/index.ts +52 -17
  57. package/src/frontend/elaborate/initializers.ts +3 -2
  58. package/src/frontend/elaborate/layouts.ts +2 -2
  59. package/src/frontend/elaborate/model.ts +34 -21
  60. package/src/frontend/elaborate/retention.ts +206 -0
  61. package/src/frontend/elaborate/specialize.ts +7 -6
  62. package/src/frontend/elaborate/statements.ts +47 -38
  63. package/src/frontend/elaborate/storage.ts +26 -6
  64. package/src/frontend/exposure.ts +6 -6
  65. package/src/frontend/expressions.ts +26 -25
  66. package/src/frontend/intrinsics.ts +3 -3
  67. package/src/frontend/module-graph.ts +1 -1
  68. package/src/frontend/positions.ts +2 -1
  69. package/src/frontend/promise-chains.ts +1 -0
  70. package/src/frontend/promises.ts +8 -7
  71. package/src/frontend/routines.ts +3 -2
  72. package/src/frontend/sdk.ts +2 -2
  73. package/src/frontend/services.ts +23 -20
  74. package/src/frontend/statements.ts +8 -6
  75. package/src/frontend/tasks.ts +11 -6
  76. package/src/frontend/telemetry.ts +1 -1
  77. package/src/frontend/types.ts +11 -9
  78. package/src/frontend/typescript.ts +92 -42
  79. package/src/index.ts +2 -1
  80. package/src/ir/aggregates.ts +4 -3
  81. package/src/ir/allocation.ts +2 -1
  82. package/src/ir/core-model.ts +38 -8
  83. package/src/ir/declarations.ts +12 -12
  84. package/src/ir/domains.ts +8 -8
  85. package/src/ir/fold.ts +2 -2
  86. package/src/ir/index.ts +53 -40
  87. package/src/ir/job-errors.ts +22 -11
  88. package/src/ir/layouts.ts +3 -2
  89. package/src/ir/link.ts +6 -24
  90. package/src/ir/model.ts +3 -2
  91. package/src/ir/normalization-error.ts +1 -1
  92. package/src/ir/normalize.ts +19 -12
  93. package/src/ir/numeric.ts +1 -0
  94. package/src/{codesys → ir}/operands.ts +2 -6
  95. package/src/ir/ranges.ts +2 -2
  96. package/src/ir/routine.ts +35 -20
  97. package/src/ir/scalars.ts +3 -3
  98. package/src/ir/share.ts +862 -0
  99. package/src/ir/temporaries.ts +236 -0
  100. package/src/ir/types.ts +1 -1
  101. package/src/project/artifacts.ts +12 -2
  102. package/src/project/cli.ts +42 -44
  103. package/src/project/debugger.ts +15 -9
  104. package/src/project/index.ts +1 -1
  105. package/src/project/plant.ts +34 -23
  106. package/src/project/project-commands.ts +92 -73
  107. package/src/project/project.ts +91 -42
  108. package/src/project/release.ts +50 -57
  109. package/src/project/server-check.ts +54 -0
  110. package/src/project/server.ts +60 -41
  111. package/src/project/terminal.ts +3 -1
  112. package/stdlib/retain.ts +2 -0
  113. package/types/globals.d.ts +1 -0
  114. package/types/retain.d.ts +6 -0
  115. package/types/telemetry.d.ts +2 -2
@@ -1,52 +1,59 @@
1
+ // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
1
2
  import {
2
- instancedBlock,
3
3
  type Constant,
4
4
  type CoreExpression,
5
+ type CoreFunction,
5
6
  type CoreStatement,
6
7
  type Deployment,
7
8
  type Diagnostic,
9
+ foldConstantRoutines,
10
+ forwardTemporaries,
11
+ instancedBlock,
8
12
  isVerifiedCore,
13
+ joinPrograms,
9
14
  nestedBodies,
10
15
  type PlcType,
11
16
  type SourceSpan,
17
+ shareRoutines,
18
+ statementExpressions,
19
+ subexpressions,
12
20
  type VerifiedCoreModule,
13
21
  } from "@tsplc/compiler/ir";
14
- import { type CodesysOptions, optionsSchema } from "./config.ts";
22
+ import type {
23
+ Publication,
24
+ ResolvedDebugConfig,
25
+ ResolvedTelemetryConfig,
26
+ ResolvedTsplcConfig,
27
+ } from "@tsplc/config";
28
+ import { cyclicTasksSchema } from "@tsplc/config/build";
15
29
  import { ioScalarBits, sizePrefixes } from "@tsplc/iec";
16
30
  import { ioLayout } from "@tsplc/typegen/hardware";
31
+ import { type CodesysOptions, optionsSchema } from "./config.ts";
32
+ import {
33
+ type HttpEndpoint,
34
+ resolveHttpEndpoint,
35
+ validateHttpLayout,
36
+ } from "./http.ts";
17
37
  import {
18
38
  iecSpelling,
19
39
  isStoragePath,
20
40
  resolveStoragePath,
21
41
  type StorageBinding,
22
42
  } from "./io-paths.ts";
43
+ import type { ProjectHardware } from "./manifest.ts";
23
44
  import { isIecIdentifier } from "./names.ts";
24
- import { statementExpressions, subexpressions } from "./operands.ts";
45
+ import { resolvePublication } from "./publication.ts";
25
46
  import { storageLayout } from "./storage.ts";
26
- import {
27
- validateHttpLayout,
28
- resolveHttpEndpoint,
29
- type HttpEndpoint,
30
- } from "./http.ts";
31
47
  import {
32
48
  accessedStorage,
49
+ routineTasks,
33
50
  schedulePrograms,
34
51
  taskStorageOwnership,
35
52
  } from "./task-access.ts";
36
- import { resolvePublication } from "./publication.ts";
37
- import type {
38
- Environment,
39
- Publication,
40
- ResolvedDebugConfig,
41
- ResolvedTelemetryConfig,
42
- ResolvedTsplcConfig,
43
- } from "@tsplc/config";
44
- import { cyclicTasksSchema } from "@tsplc/config/build";
45
- import type { ProjectHardware } from "./manifest.ts";
46
53
  import {
47
54
  planTelemetry,
48
- telemetryClient,
49
55
  type TelemetryPlan,
56
+ telemetryClient,
50
57
  } from "./telemetry.ts";
51
58
 
52
59
  // Only this planner can admit a target configuration for emission. Cloning a
@@ -55,6 +62,12 @@ const planned: unique symbol = Symbol("CODESYS plan");
55
62
  export interface CodesysPlan {
56
63
  readonly [planned]: true;
57
64
  readonly core: VerifiedCoreModule;
65
+ /**
66
+ * The functions as the frontend specialized them, one per instance, and the routine each that
67
+ * `shareRoutines` merged away runs as. The debug manifest describes every instance.
68
+ */
69
+ readonly specialized: readonly CoreFunction[];
70
+ readonly sharedRoutines: ReadonlyMap<string, string>;
58
71
  readonly deployment: Deployment;
59
72
  readonly options: CodesysOptions;
60
73
  /** `io` keys that name authored storage, resolved against the verified types. */
@@ -79,8 +92,8 @@ export interface CodesysProject {
79
92
  "transport" | "baseUrlEnv"
80
93
  >;
81
94
  hardware?: ProjectHardware;
82
- /** What the server's base URL and the HTTP credentials are read from; `process.env` when omitted. */
83
- env?: Environment;
95
+ /** Where HTTP credentials and the telemetry base URL are read from; this process's environment by default. */
96
+ environment?: Readonly<Record<string, string | undefined>>;
84
97
  }
85
98
  const plans = new WeakSet<object>();
86
99
  export function diagnostic(message: string, span?: SourceSpan): Diagnostic {
@@ -97,12 +110,12 @@ export function isCodesysPlan(plan: CodesysPlan): boolean {
97
110
  }
98
111
 
99
112
  export function planCodesys(
100
- core: VerifiedCoreModule,
113
+ specialized: VerifiedCoreModule,
101
114
  deployment: Deployment,
102
115
  value: unknown,
103
116
  project: CodesysProject = { root: process.cwd() },
104
117
  ): { plan?: CodesysPlan; diagnostics: readonly Diagnostic[] } {
105
- if (!isVerifiedCore(core)) {
118
+ if (!isVerifiedCore(specialized)) {
106
119
  return {
107
120
  diagnostics: [
108
121
  diagnostic("CODESYS requires a verified, normalized core module."),
@@ -120,14 +133,19 @@ export function planCodesys(
120
133
  }
121
134
 
122
135
  const options = parsed.data;
136
+ const environment = project.environment ?? { ...process.env };
123
137
  const diagnostics: Diagnostic[] = [];
124
138
  const report = (message: string, span?: SourceSpan): void => {
125
139
  diagnostics.push(diagnostic(message, span));
126
140
  };
141
+ const { core, routines } = sharedRoutines(
142
+ specialized,
143
+ deployment,
144
+ project.debug,
145
+ );
127
146
  const scheduled: Deployment = {
128
147
  tasks: schedulePrograms(core, deployment.tasks, report),
129
148
  };
130
- const env = project.env ?? process.env;
131
149
  const http = new Map<string, HttpEndpoint>();
132
150
  for (const block of core.blocks) {
133
151
  if (block.runtime?.kind === "http" || block.runtime?.kind === "rpc") {
@@ -149,7 +167,7 @@ export function planCodesys(
149
167
  timeoutMs: options.http.timeoutMs,
150
168
  tls: false,
151
169
  }
152
- : resolveHttpEndpoint(block.runtime.url, options.http, env),
170
+ : resolveHttpEndpoint(block.runtime.url, options.http, environment),
153
171
  );
154
172
  } catch (cause) {
155
173
  report(
@@ -168,7 +186,7 @@ export function planCodesys(
168
186
  core,
169
187
  scheduled,
170
188
  options,
171
- { ...project, env, trace: project.debug?.trace },
189
+ { ...project, environment, trace: project.debug?.trace },
172
190
  report,
173
191
  );
174
192
  if (endpoint) {
@@ -185,6 +203,8 @@ export function planCodesys(
185
203
 
186
204
  const plan: CodesysPlan = Object.freeze({
187
205
  core,
206
+ specialized: specialized.functions,
207
+ sharedRoutines: routines,
188
208
  deployment: structuredClone(scheduled),
189
209
  options: structuredClone(options),
190
210
  storageBindings,
@@ -214,6 +234,54 @@ export function planCodesys(
214
234
 
215
235
  type Report = (message: string, span?: SourceSpan) => void;
216
236
 
237
+ /**
238
+ * Routines specialized per instance, merged where they run the same code in the same task, each
239
+ * task's continuation programs joined into one, calls of routines that only return a constant
240
+ * replaced by it, and temporaries read right after they are written folded into their reader.
241
+ * The debugger's instrumentation is written per statement of each routine, so a program built
242
+ * with `debug` keeps every instance's own routine, as does one whose scheduling is invalid: its
243
+ * diagnostics name the routines as written.
244
+ */
245
+ function sharedRoutines(
246
+ core: VerifiedCoreModule,
247
+ deployment: Deployment,
248
+ debug: ResolvedDebugConfig | undefined,
249
+ ): { core: VerifiedCoreModule; routines: ReadonlyMap<string, string> } {
250
+ const unshared = { core, routines: new Map<string, string>() };
251
+ if (debug) {
252
+ return unshared;
253
+ }
254
+ const issues: string[] = [];
255
+ const scheduled = {
256
+ tasks: schedulePrograms(core, deployment.tasks, (message) => {
257
+ issues.push(message);
258
+ }),
259
+ };
260
+ if (issues.length) {
261
+ return unshared;
262
+ }
263
+ const continuations = new Set(
264
+ core.programs.flatMap((program) =>
265
+ program.continuation ? [program.name] : [],
266
+ ),
267
+ );
268
+ const joined = joinPrograms(
269
+ core,
270
+ scheduled.tasks.map((task) =>
271
+ task.programs.filter((name) => continuations.has(name)),
272
+ ),
273
+ );
274
+ const folded = foldConstantRoutines(joined.core);
275
+ const tasks = routineTasks(folded.core, {
276
+ tasks: schedulePrograms(folded.core, deployment.tasks, () => {}),
277
+ });
278
+ const shared = shareRoutines(folded.core, (routine) => tasks.get(routine.id));
279
+ return {
280
+ core: forwardTemporaries(shared.core),
281
+ routines: new Map([...joined.routines, ...shared.routines]),
282
+ };
283
+ }
284
+
217
285
  /** Validate every `io` binding and return the ones that name authored storage. */
218
286
  function validateIo(
219
287
  core: VerifiedCoreModule,
@@ -1,9 +1,10 @@
1
- import type { Publication } from "@tsplc/config";
2
1
  import type {
3
2
  EmitResult,
4
3
  PlcType,
5
4
  VerifiedCoreModule,
6
5
  } from "@tsplc/compiler/ir";
6
+ import type { Publication } from "@tsplc/config";
7
+ import { emittedFiles } from "@tsplc/config/project-files";
7
8
  import type { RpcChannel } from "./http.ts";
8
9
  import type { CodesysPlan } from "./plan.ts";
9
10
  import { moduleFile, moduleName } from "./storage.ts";
@@ -161,10 +162,10 @@ export const machineInterfaces = (
161
162
  return [
162
163
  {
163
164
  path: "exposures.json",
164
- content: JSON.stringify(exposures, null, 2) + "\n",
165
+ content: `${JSON.stringify(exposures, null, 2)}\n`,
165
166
  },
166
167
  {
167
- path: "machines.ts",
168
+ path: emittedFiles.machines,
168
169
  content: `// Generated explicit read-only machine interfaces. Do not edit.\nexport const machines=${JSON.stringify(exposures, null, 2)} as const;\nexport const serviceChannels=${JSON.stringify(rpcChannels, null, 2)} as const;\n`,
169
170
  },
170
171
  ];
@@ -19,8 +19,8 @@ import {
19
19
  import {
20
20
  jobField,
21
21
  jobTracking,
22
- ringTarget,
23
22
  type RoutineProbes,
23
+ ringTarget,
24
24
  writeProbes,
25
25
  } from "./instrumentation.ts";
26
26
  import {
@@ -531,7 +531,7 @@ export function emitRoutine(
531
531
  "VAR_IN_OUT",
532
532
  inputs.filter((item) => item.mode === "inOut"),
533
533
  );
534
- if (tracked && tracked.job) {
534
+ if (tracked?.job) {
535
535
  declaration.push(
536
536
  "VAR_INPUT",
537
537
  ` ${tracked.job} : ${instrumentationFieldTypes.job};`,
@@ -1,3 +1,4 @@
1
+ // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
1
2
  import { existsSync, readFileSync } from "node:fs";
2
3
  import { isAbsolute, relative } from "node:path";
3
4
  import type { SourceSpan } from "@tsplc/compiler/ir";
@@ -18,8 +18,9 @@ export function stFiles(
18
18
  objects: readonly GeneratedObject[],
19
19
  mappings: readonly SourceMapping[],
20
20
  ): EmitResult["artifacts"] {
21
+ const paths = objectPaths(plan, symbols, objects);
21
22
  const placed = objects.map((object) => {
22
- const path = objectPath(plan, symbols, objects, object);
23
+ const path = paths(object);
23
24
  object.sourcePath = declarationFile(path, object);
24
25
  return { object, path };
25
26
  });
@@ -34,11 +35,9 @@ export function stFiles(
34
35
  },
35
36
  ]),
36
37
  ]);
38
+ const owners = firstBy(placed, ({ object }) => mappingKey(object));
37
39
  for (const mapping of mappings) {
38
- const owner = placed.find(({ object }) => {
39
- const key = mappingKey(object);
40
- return mapping.path === `${key}.st` || mapping.path.startsWith(`${key}/`);
41
- });
40
+ const owner = mappingOwner(owners, mapping.path);
42
41
  if (owner) {
43
42
  mapping.path =
44
43
  owner.path + mapping.path.slice(mappingKey(owner.object).length);
@@ -47,6 +46,39 @@ export function stFiles(
47
46
  return artifacts;
48
47
  }
49
48
 
49
+ /** Each key's first item, and that item's position, so a lookup keeps a linear search's first-match order. */
50
+ const firstBy = <T>(items: readonly T[], key: (item: T) => string) => {
51
+ const index = new Map<string, { item: T; position: number }>();
52
+ items.forEach((item, position) => {
53
+ const name = key(item);
54
+ if (!index.has(name)) {
55
+ index.set(name, { item, position });
56
+ }
57
+ });
58
+ return index;
59
+ };
60
+
61
+ /**
62
+ * The first placed object a mapping's path names: one whose key is the path without `.st`, or
63
+ * any prefix of the path that ends before a `/`. Keys may hold slashes, so every prefix is a candidate.
64
+ */
65
+ const mappingOwner = <T>(
66
+ owners: ReadonlyMap<string, { item: T; position: number }>,
67
+ path: string,
68
+ ): T | undefined => {
69
+ const candidates = [
70
+ ...(path.endsWith(".st") ? [path.slice(0, -".st".length)] : []),
71
+ ...[...path.matchAll(/\//g)].map((match) => path.slice(0, match.index)),
72
+ ];
73
+ const [first] = candidates
74
+ .flatMap((key) => {
75
+ const owner = owners.get(key);
76
+ return owner ? [owner] : [];
77
+ })
78
+ .sort((left, right) => left.position - right.position);
79
+ return first?.item;
80
+ };
81
+
50
82
  /** What an emitter names an object in its mappings' paths: a method by its id, as method names repeat across blocks. */
51
83
  const mappingKey = (object: GeneratedObject) =>
52
84
  object.kind === "method" ? object.id : object.name;
@@ -60,56 +92,60 @@ const generatedFolder = (object: GeneratedObject) => {
60
92
  };
61
93
 
62
94
  /** The module an object was emitted from, as the id of its symbol, program entry or variables names it. */
63
- const sourceModule = (
64
- { core }: CodesysPlan,
65
- symbols: CodesysSymbols,
66
- object: GeneratedObject,
67
- ): string => {
68
- const group = symbols.globals.find((item) => item.id === object.id);
69
- if (group) {
70
- // Variable IDs are relative to tsconfig, unlike their diagnostic spans.
71
- return group.variables[0]?.id.split(":")[0] ?? "";
72
- }
73
- const program = core.programs.find((item) => item.id === object.id);
74
- return (program ? program.entry : object.id).split(":")[0] ?? "";
95
+ const sourceModules = ({ core }: CodesysPlan, symbols: CodesysSymbols) => {
96
+ const groups = firstBy(symbols.globals, (item) => item.id);
97
+ const programs = firstBy(core.programs, (item) => item.id);
98
+ return (object: GeneratedObject): string => {
99
+ const group = groups.get(object.id)?.item;
100
+ if (group) {
101
+ // Variable IDs are relative to tsconfig, unlike their diagnostic spans.
102
+ return group.variables[0]?.id.split(":")[0] ?? "";
103
+ }
104
+ const program = programs.get(object.id)?.item;
105
+ return (program ? program.entry : object.id).split(":")[0] ?? "";
106
+ };
75
107
  };
76
108
 
77
- function objectPath(
109
+ /** Each object's path without extension: its source module's folder, or its parent's for a method. */
110
+ function objectPaths(
78
111
  plan: CodesysPlan,
79
112
  symbols: CodesysSymbols,
80
113
  objects: readonly GeneratedObject[],
81
- object: GeneratedObject,
82
- ): string {
83
- const { core } = plan;
84
- if (object.kind === "method" && object.parent) {
85
- const parent = required(
86
- objects.find((candidate) => candidate.id === object.parent),
87
- );
88
- return `${objectPath(plan, symbols, objects, parent)}/methods/${object.name}`;
89
- }
90
- if (object.kind === "method") {
91
- const method = required(core.functions.find((fn) => fn.id === object.id));
92
- const owner = required(
93
- objects.find((item) => item.id === method.owner?.block),
94
- );
95
- return `${objectPath(plan, symbols, objects, owner)}/methods/${object.name}`;
96
- }
97
- const source = sourceModule(plan, symbols, object);
98
- if (
99
- /^[\w./ -]+\.tsx?$/.test(source) &&
100
- !source.split(/[\\/]/).includes("..") &&
101
- !source.startsWith("/")
102
- ) {
103
- const segments = source.replaceAll("\\", "/").split("/").slice(0, -1);
104
- if (segments[0] === "src") {
105
- segments.shift();
114
+ ): (object: GeneratedObject) => string {
115
+ const byId = firstBy(objects, (item) => item.id);
116
+ const functions = firstBy(plan.core.functions, (fn) => fn.id);
117
+ const sourceModule = sourceModules(plan, symbols);
118
+ const objectPath = (object: GeneratedObject): string => {
119
+ if (object.kind === "method" && object.parent) {
120
+ const parent = required(byId.get(object.parent)?.item);
121
+ return `${objectPath(parent)}/methods/${object.name}`;
106
122
  }
107
- // A DUT directory can also contain sibling input/output layouts. Keep
108
- // that directory for every DUT, or its primary type would block the folder.
109
- if (object.kind !== "dataType" && segments.at(-1) === object.name) {
110
- segments.pop();
123
+ if (object.kind === "method") {
124
+ const method = required(functions.get(object.id)?.item);
125
+ const block = method.owner?.block;
126
+ const owner = required(
127
+ block === undefined ? undefined : byId.get(block)?.item,
128
+ );
129
+ return `${objectPath(owner)}/methods/${object.name}`;
111
130
  }
112
- return [...segments, object.name].join("/");
113
- }
114
- return `${generatedFolder(object)}/${object.name}`;
131
+ const source = sourceModule(object);
132
+ if (
133
+ /^[\w./ -]+\.tsx?$/.test(source) &&
134
+ !source.split(/[\\/]/).includes("..") &&
135
+ !source.startsWith("/")
136
+ ) {
137
+ const segments = source.replaceAll("\\", "/").split("/").slice(0, -1);
138
+ if (segments[0] === "src") {
139
+ segments.shift();
140
+ }
141
+ // A DUT directory can also contain sibling input/output layouts. Keep
142
+ // that directory for every DUT, or its primary type would block the folder.
143
+ if (object.kind !== "dataType" && segments.at(-1) === object.name) {
144
+ segments.pop();
145
+ }
146
+ return [...segments, object.name].join("/");
147
+ }
148
+ return `${generatedFolder(object)}/${object.name}`;
149
+ };
150
+ return objectPath;
115
151
  }
@@ -8,10 +8,21 @@ import {
8
8
  /** Which global list of its module a variable goes in. */
9
9
  export type GlobalStorage = "constants" | "retained" | "state";
10
10
 
11
+ /** A section of a global list: the variables one `VAR_GLOBAL` qualifier declares. */
12
+ interface GlobalSection {
13
+ storage: GlobalStorage;
14
+ variables: Variable[];
15
+ }
16
+
17
+ /**
18
+ * A module's constants, or its mutable storage. Retained and ordinary state share one list in
19
+ * separate sections, so retaining a variable never changes the path it is published at.
20
+ */
11
21
  interface GlobalList {
12
22
  id: string;
13
23
  module: string;
14
- storage: GlobalStorage;
24
+ kind: Exclude<GlobalStorage, "retained">;
25
+ sections: GlobalSection[];
15
26
  variables: Variable[];
16
27
  }
17
28
 
@@ -26,6 +37,12 @@ export const moduleFile = (variable: Variable): string =>
26
37
  export const moduleName = (variable: Variable): string =>
27
38
  basename(moduleFile(variable)).replace(/\.[^.]+$/, "");
28
39
 
40
+ const sectionOrder: readonly GlobalStorage[] = [
41
+ "constants",
42
+ "state",
43
+ "retained",
44
+ ];
45
+
29
46
  const globalStorage = (
30
47
  variable: Variable,
31
48
  retainedVariables: ReadonlySet<string>,
@@ -75,23 +92,41 @@ export function storageLayout(core: VerifiedCoreModule) {
75
92
  .map((variable) => variable.id),
76
93
  );
77
94
 
78
- const groups = new Map<string, GlobalList>();
95
+ const groups = new Map<string, Omit<GlobalList, "variables">>();
79
96
  for (const variable of core.variables) {
80
97
  if (variable.storage === "input" || variable.storage === "output") {
81
98
  continue;
82
99
  }
83
100
  const storage = globalStorage(variable, retainedVariables);
84
- const id = `${moduleFile(variable)}:${storage}`;
85
- let group = groups.get(id);
86
- if (!group) {
87
- group = { id, module: moduleName(variable), storage, variables: [] };
88
- groups.set(id, group);
101
+ const kind = storage === "constants" ? "constants" : "state";
102
+ const id = `${moduleFile(variable)}:${kind}`;
103
+ const group = groups.get(id) ?? {
104
+ id,
105
+ module: moduleName(variable),
106
+ kind,
107
+ sections: [],
108
+ };
109
+ groups.set(id, group);
110
+ const section = group.sections.find((item) => item.storage === storage);
111
+ if (section) {
112
+ section.variables.push(variable);
113
+ } else {
114
+ group.sections.push({ storage, variables: [variable] });
89
115
  }
90
- group.variables.push(variable);
91
116
  }
92
117
  return {
93
118
  retainedBlocks,
94
119
  retainedVariables,
95
- globalLists: [...groups.values()],
120
+ globalLists: [...groups.values()].map((group): GlobalList => {
121
+ // Ordinary state comes first, so retaining a variable leaves the others' lines in place.
122
+ const sections = sectionOrder.flatMap((storage) =>
123
+ group.sections.filter((section) => section.storage === storage),
124
+ );
125
+ return {
126
+ ...group,
127
+ sections,
128
+ variables: sections.flatMap((section) => section.variables),
129
+ };
130
+ }),
96
131
  };
97
132
  }
@@ -1,8 +1,4 @@
1
- import {
2
- instancedBlock,
3
- nanosecondsPerMillisecond,
4
- nestedBodies,
5
- } from "@tsplc/compiler/ir";
1
+ // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
6
2
  import type {
7
3
  CoreExpression,
8
4
  CoreFunction,
@@ -15,7 +11,13 @@ import type {
15
11
  Variable,
16
12
  VerifiedCoreModule,
17
13
  } from "@tsplc/compiler/ir";
18
- import { statementExpressions, subexpressions } from "./operands.ts";
14
+ import {
15
+ instancedBlock,
16
+ nanosecondsPerMillisecond,
17
+ nestedBodies,
18
+ statementExpressions,
19
+ subexpressions,
20
+ } from "@tsplc/compiler/ir";
19
21
 
20
22
  type Report = (message: string, span?: SourceSpan) => void;
21
23
 
@@ -179,6 +181,29 @@ export function taskStorageOwnership(
179
181
  };
180
182
  }
181
183
 
184
+ const buildModuleTables = (core: VerifiedCoreModule) => ({
185
+ functions: new Map(core.functions.map((item) => [item.id, item])),
186
+ blocks: new Map(core.blocks.map((item) => [item.id, item])),
187
+ types: new Map(core.types.map((item) => [item.id, item])),
188
+ variables: variablesById(core),
189
+ });
190
+
191
+ const builtTables = new WeakMap<
192
+ VerifiedCoreModule,
193
+ ReturnType<typeof buildModuleTables>
194
+ >();
195
+
196
+ /** A module's routines, types and variables by id, built once: planning and emission ask for every routine's storage. */
197
+ const moduleTables = (core: VerifiedCoreModule) => {
198
+ const known = builtTables.get(core);
199
+ if (known) {
200
+ return known;
201
+ }
202
+ const tables = buildModuleTables(core);
203
+ builtTables.set(core, tables);
204
+ return tables;
205
+ };
206
+
182
207
  // Follow both helper calls and instance updates. Borrow addresses count as storage
183
208
  // access, so scheduling cannot accidentally give one mutable record two owners.
184
209
  export function accessedStorage(
@@ -193,10 +218,7 @@ export function accessedStorage(
193
218
  );
194
219
  const result = new Set<string>();
195
220
  const seen = new Set<string>();
196
- const functions = new Map(core.functions.map((item) => [item.id, item]));
197
- const blocks = new Map(core.blocks.map((item) => [item.id, item]));
198
- const types = new Map(core.types.map((item) => [item.id, item]));
199
- const variables = variablesById(core);
221
+ const { functions, blocks, types, variables } = moduleTables(core);
200
222
 
201
223
  const expression = (value: CoreExpression): void => {
202
224
  if (value.kind === "load") {