@tsplc/tmp-compiler 0.0.0-stage → 0.6.3

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 (185) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +41 -2
  3. package/dist/cli.js +2325 -0
  4. package/dist/cli.js.map +26 -0
  5. package/dist/clock.js +11 -0
  6. package/dist/clock.js.map +11 -0
  7. package/dist/codesys.js +6563 -0
  8. package/dist/codesys.js.map +51 -0
  9. package/dist/collections.js +399 -0
  10. package/dist/collections.js.map +10 -0
  11. package/dist/index.js +16198 -0
  12. package/dist/index.js.map +62 -0
  13. package/dist/ir.js +3948 -0
  14. package/dist/ir.js.map +35 -0
  15. package/dist/retain.js +10 -0
  16. package/dist/retain.js.map +10 -0
  17. package/dist/signals.js +115 -0
  18. package/dist/signals.js.map +10 -0
  19. package/dist/telemetry.js +121 -0
  20. package/dist/telemetry.js.map +12 -0
  21. package/package.json +122 -4
  22. package/src/codesys/config.ts +50 -0
  23. package/src/codesys/debug.ts +655 -0
  24. package/src/codesys/emit.ts +185 -0
  25. package/src/codesys/endpoints.ts +111 -0
  26. package/src/codesys/engineering.ts +96 -0
  27. package/src/codesys/explain/expressions.ts +445 -0
  28. package/src/codesys/explain/flags.ts +134 -0
  29. package/src/codesys/explain/parameters.ts +53 -0
  30. package/src/codesys/explain/rows.ts +182 -0
  31. package/src/codesys/explain/tables.ts +79 -0
  32. package/src/codesys/explain/tasks.ts +68 -0
  33. package/src/codesys/explain/writes.ts +497 -0
  34. package/src/codesys/explain.ts +149 -0
  35. package/src/codesys/expressions.ts +100 -0
  36. package/src/codesys/global-lists.ts +284 -0
  37. package/src/codesys/global-names.ts +66 -0
  38. package/src/codesys/http.ts +1090 -0
  39. package/src/codesys/index.ts +13 -0
  40. package/src/codesys/instrumentation.ts +574 -0
  41. package/src/codesys/io-paths.ts +149 -0
  42. package/src/codesys/loops.ts +101 -0
  43. package/src/codesys/manifest.ts +684 -0
  44. package/src/codesys/names.ts +58 -0
  45. package/src/codesys/numeric.ts +516 -0
  46. package/src/codesys/plan.ts +688 -0
  47. package/src/codesys/programs.ts +138 -0
  48. package/src/codesys/publication.ts +99 -0
  49. package/src/codesys/required.ts +8 -0
  50. package/src/codesys/routines.ts +247 -0
  51. package/src/codesys/scan-clock.ts +103 -0
  52. package/src/codesys/scheduling.ts +96 -0
  53. package/src/codesys/service-channels.ts +24 -0
  54. package/src/codesys/sources.ts +118 -0
  55. package/src/codesys/st-files.ts +219 -0
  56. package/src/codesys/statements.ts +409 -0
  57. package/src/codesys/storage.ts +150 -0
  58. package/src/codesys/symbols.ts +240 -0
  59. package/src/codesys/task-access.ts +186 -0
  60. package/src/codesys/telemetry-settings.ts +19 -0
  61. package/src/codesys/telemetry.ts +852 -0
  62. package/src/codesys/types.ts +310 -0
  63. package/src/codesys/vendor.ts +113 -0
  64. package/src/frontend/analyzer.ts +779 -0
  65. package/src/frontend/async.ts +530 -0
  66. package/src/frontend/blocks.ts +578 -0
  67. package/src/frontend/configuration.ts +83 -0
  68. package/src/frontend/const-enums.ts +196 -0
  69. package/src/frontend/const-functions.ts +204 -0
  70. package/src/frontend/control-flow.ts +787 -0
  71. package/src/frontend/cooperative.ts +114 -0
  72. package/src/frontend/coroutines.ts +1344 -0
  73. package/src/frontend/dialect-names.ts +104 -0
  74. package/src/frontend/elaborate/array-searches.ts +224 -0
  75. package/src/frontend/elaborate/assignments.ts +343 -0
  76. package/src/frontend/elaborate/calls.ts +1342 -0
  77. package/src/frontend/elaborate/capture-protocol.ts +237 -0
  78. package/src/frontend/elaborate/capture.ts +388 -0
  79. package/src/frontend/elaborate/declarations.ts +124 -0
  80. package/src/frontend/elaborate/dialect.ts +473 -0
  81. package/src/frontend/elaborate/expressions.ts +2177 -0
  82. package/src/frontend/elaborate/filtered-arrays.ts +643 -0
  83. package/src/frontend/elaborate/frame.ts +145 -0
  84. package/src/frontend/elaborate/generics.ts +123 -0
  85. package/src/frontend/elaborate/graph.ts +141 -0
  86. package/src/frontend/elaborate/imports.ts +105 -0
  87. package/src/frontend/elaborate/index.ts +851 -0
  88. package/src/frontend/elaborate/initializers.ts +235 -0
  89. package/src/frontend/elaborate/iterators.ts +1541 -0
  90. package/src/frontend/elaborate/layouts.ts +1025 -0
  91. package/src/frontend/elaborate/model.ts +478 -0
  92. package/src/frontend/elaborate/names.ts +134 -0
  93. package/src/frontend/elaborate/reduce.ts +900 -0
  94. package/src/frontend/elaborate/references.ts +727 -0
  95. package/src/frontend/elaborate/retention.ts +284 -0
  96. package/src/frontend/elaborate/specialize.ts +1137 -0
  97. package/src/frontend/elaborate/statements.ts +1220 -0
  98. package/src/frontend/elaborate/storage.ts +836 -0
  99. package/src/frontend/elaborate/time-constructors.ts +34 -0
  100. package/src/frontend/elaborate/values.ts +200 -0
  101. package/src/frontend/elaborate/writes.ts +415 -0
  102. package/src/frontend/expressions.ts +1382 -0
  103. package/src/frontend/generated-names.ts +95 -0
  104. package/src/frontend/intrinsics.ts +382 -0
  105. package/src/frontend/lowering-key.ts +23 -0
  106. package/src/frontend/module-graph.ts +156 -0
  107. package/src/frontend/positions.ts +359 -0
  108. package/src/frontend/promise-chains.ts +872 -0
  109. package/src/frontend/promises.ts +419 -0
  110. package/src/frontend/routines.ts +239 -0
  111. package/src/frontend/sdk.ts +187 -0
  112. package/src/frontend/services.ts +612 -0
  113. package/src/frontend/statements.ts +871 -0
  114. package/src/frontend/tasks.ts +526 -0
  115. package/src/frontend/telemetry.ts +174 -0
  116. package/src/frontend/types.ts +1073 -0
  117. package/src/frontend/typescript.ts +659 -0
  118. package/src/index.ts +9 -0
  119. package/src/ir/aggregates.ts +291 -0
  120. package/src/ir/allocation.ts +96 -0
  121. package/src/ir/conditions.ts +855 -0
  122. package/src/ir/core-model.ts +289 -0
  123. package/src/ir/declarations.ts +281 -0
  124. package/src/ir/diagnostics.ts +68 -0
  125. package/src/ir/domains.ts +151 -0
  126. package/src/ir/fold.ts +279 -0
  127. package/src/ir/identity.ts +19 -0
  128. package/src/ir/index.ts +137 -0
  129. package/src/ir/job-errors.ts +69 -0
  130. package/src/ir/layouts.ts +211 -0
  131. package/src/ir/link.ts +302 -0
  132. package/src/ir/model.ts +394 -0
  133. package/src/ir/normalization-error.ts +10 -0
  134. package/src/ir/normalize.ts +52 -0
  135. package/src/ir/numeric.ts +163 -0
  136. package/src/ir/operands.ts +160 -0
  137. package/src/ir/ranges.ts +420 -0
  138. package/src/ir/routine.ts +1116 -0
  139. package/src/ir/scalars.ts +453 -0
  140. package/src/ir/share.ts +790 -0
  141. package/src/ir/short-circuit.ts +140 -0
  142. package/src/ir/tables.ts +111 -0
  143. package/src/ir/temporaries.ts +138 -0
  144. package/src/ir/types.ts +151 -0
  145. package/src/project/artifacts.ts +424 -0
  146. package/src/project/cli.ts +211 -0
  147. package/src/project/debugger.ts +111 -0
  148. package/src/project/deployments.ts +387 -0
  149. package/src/project/flags.ts +14 -0
  150. package/src/project/git.ts +35 -0
  151. package/src/project/plant.ts +629 -0
  152. package/src/project/project-commands.ts +507 -0
  153. package/src/project/project.ts +559 -0
  154. package/src/project/release.ts +152 -0
  155. package/src/project/server-check.ts +54 -0
  156. package/src/project/server.ts +165 -0
  157. package/src/project/terminal.ts +45 -0
  158. package/src/runtime/async.ts +207 -0
  159. package/src/runtime/launch.ts +59 -0
  160. package/src/runtime/main.ts +59 -0
  161. package/src/runtime/missing-file.ts +3 -0
  162. package/src/runtime/process.ts +177 -0
  163. package/src/runtime/program.ts +109 -0
  164. package/src/runtime/retain.ts +108 -0
  165. package/src/runtime/runtime.ts +324 -0
  166. package/src/runtime/settings.ts +27 -0
  167. package/src/runtime/storage.ts +456 -0
  168. package/src/runtime/symbols.ts +97 -0
  169. package/src/runtime/telemetry.ts +154 -0
  170. package/src/runtime/transport.ts +168 -0
  171. package/stdlib/clock.ts +8 -0
  172. package/stdlib/collections.ts +534 -0
  173. package/stdlib/plc-time.ts +2 -0
  174. package/stdlib/retain.ts +4 -0
  175. package/stdlib/signals.ts +142 -0
  176. package/stdlib/telemetry.ts +89 -0
  177. package/types/async.d.ts +87 -0
  178. package/types/clock.d.ts +8 -0
  179. package/types/config.d.ts +2 -0
  180. package/types/data-types.d.ts +31 -0
  181. package/types/dialect.d.ts +49 -0
  182. package/types/globals.d.ts +10 -0
  183. package/types/index.d.ts +212 -0
  184. package/types/retain.d.ts +12 -0
  185. package/types/telemetry.d.ts +47 -0
@@ -0,0 +1,289 @@
1
+ import type { BinaryOperator, UnaryOperator } from "@tsplc/iec/arithmetic";
2
+ import type { SourceSpan } from "./diagnostics";
3
+ import type {
4
+ Constant,
5
+ FunctionBlock,
6
+ PlcFunction,
7
+ PlcModule,
8
+ PlcProgram,
9
+ TelemetryCall,
10
+ Variable,
11
+ } from "./model";
12
+ import { instancedBlock, type PlcType } from "./types";
13
+
14
+ // Core expressions contain no source-level calls. Their effects have already
15
+ // become ordered statements, and every place has passed storage/bounds checks.
16
+ export type CorePath = readonly (
17
+ | { readonly kind: "field"; readonly name: string }
18
+ | { readonly kind: "index"; readonly value: CoreExpression }
19
+ )[];
20
+ export interface CheckedPlace {
21
+ readonly root: string;
22
+ readonly path: CorePath;
23
+ }
24
+ export type CoreExpression = {
25
+ readonly type: string;
26
+ readonly span: SourceSpan;
27
+ } & (
28
+ | { readonly kind: "borrow"; readonly place: CheckedPlace }
29
+ | { readonly kind: "constant"; readonly value: Constant }
30
+ | { readonly kind: "load"; readonly root: string; readonly path?: CorePath }
31
+ | {
32
+ readonly kind: "unary";
33
+ readonly operator: UnaryOperator;
34
+ readonly operand: CoreExpression;
35
+ }
36
+ | {
37
+ readonly kind: "binary";
38
+ readonly operator: BinaryOperator;
39
+ readonly left: CoreExpression;
40
+ readonly right: CoreExpression;
41
+ readonly policy?: "wrap" | "saturate";
42
+ }
43
+ | {
44
+ readonly kind: "convert";
45
+ readonly operand: CoreExpression;
46
+ readonly policy: "exact" | "wrap" | "saturate";
47
+ }
48
+ );
49
+ export type CoreStatement = { readonly span: SourceSpan } & (
50
+ | {
51
+ readonly kind: "assign";
52
+ readonly root: string;
53
+ readonly path?: CorePath;
54
+ readonly value: CoreExpression;
55
+ }
56
+ | {
57
+ readonly kind: "if";
58
+ readonly condition: CoreExpression;
59
+ readonly then: readonly CoreStatement[];
60
+ readonly else: readonly CoreStatement[];
61
+ }
62
+ | {
63
+ readonly kind: "switch";
64
+ readonly value: CoreExpression;
65
+ readonly cases: readonly {
66
+ values: readonly Constant[];
67
+ body: readonly CoreStatement[];
68
+ }[];
69
+ readonly fallback: readonly CoreStatement[];
70
+ }
71
+ | {
72
+ readonly kind: "for";
73
+ readonly counter: string;
74
+ readonly counterScope?: "existing";
75
+ readonly start: Constant;
76
+ readonly limit: Constant;
77
+ readonly step: string;
78
+ readonly dynamic?: {
79
+ readonly start: CoreExpression;
80
+ readonly limit: CoreExpression;
81
+ readonly exclusive?: true;
82
+ };
83
+ readonly maxIterations: number;
84
+ readonly body: readonly CoreStatement[];
85
+ }
86
+ | {
87
+ readonly kind: "invoke";
88
+ readonly function: string;
89
+ readonly instance?: string;
90
+ readonly index?: CoreExpression;
91
+ readonly arguments: readonly CoreExpression[];
92
+ readonly destination?: string;
93
+ }
94
+ | {
95
+ readonly kind: "blockUpdate";
96
+ readonly instance: string;
97
+ readonly index?: CoreExpression;
98
+ readonly inputs: Readonly<Record<string, CoreExpression>>;
99
+ }
100
+ | { readonly kind: "return"; readonly value?: CoreExpression }
101
+ | { readonly kind: "break" | "continue" }
102
+ | ({ readonly kind: "telemetry" } & TelemetryCall<CoreExpression>)
103
+ );
104
+ /** Whether a statement assigns the whole of `root`. */
105
+ export const wholeAssign = (
106
+ item: CoreStatement | undefined,
107
+ root: string,
108
+ ): item is Extract<CoreStatement, { kind: "assign" }> =>
109
+ item?.kind === "assign" && item.root === root && !item.path?.length;
110
+ /** The statement lists nested directly inside a statement. */
111
+ export const nestedBodies = (
112
+ item: CoreStatement,
113
+ ): readonly (readonly CoreStatement[])[] => {
114
+ if (item.kind === "if") {
115
+ return [item.then, item.else];
116
+ }
117
+ if (item.kind === "switch") {
118
+ return [...item.cases.map((branch) => branch.body), item.fallback];
119
+ }
120
+ if (item.kind === "for") {
121
+ return [item.body];
122
+ }
123
+ return [];
124
+ };
125
+ /** A statement with each list `nestedBodies` returns replaced by `map` of it. */
126
+ export const mapBodies = (
127
+ item: CoreStatement,
128
+ map: (body: readonly CoreStatement[]) => readonly CoreStatement[],
129
+ ): CoreStatement => {
130
+ switch (item.kind) {
131
+ case "if":
132
+ // biome-ignore lint/suspicious/noThenProperty: PLC branch data is an array, not a thenable callback.
133
+ return { ...item, then: map(item.then), else: map(item.else) };
134
+ case "switch":
135
+ return {
136
+ ...item,
137
+ cases: item.cases.map((branch) => ({
138
+ ...branch,
139
+ body: map(branch.body),
140
+ })),
141
+ fallback: map(item.fallback),
142
+ };
143
+ case "for":
144
+ return { ...item, body: map(item.body) };
145
+ default:
146
+ return item;
147
+ }
148
+ };
149
+ /**
150
+ * The storage roots a statement writes itself, in statement order: an assignment's target, a
151
+ * loop's counter, a call's destination and every place it borrows. Nested bodies and the
152
+ * routines a call runs are the caller's to follow.
153
+ */
154
+ export const directWrites = (item: CoreStatement): readonly string[] => {
155
+ if (item.kind === "assign") {
156
+ return [item.root];
157
+ }
158
+ if (item.kind === "for") {
159
+ return [item.counter];
160
+ }
161
+ if (item.kind === "invoke") {
162
+ return [
163
+ ...(item.destination ? [item.destination] : []),
164
+ ...item.arguments.flatMap((argument) =>
165
+ argument.kind === "borrow" ? [argument.place.root] : [],
166
+ ),
167
+ ];
168
+ }
169
+ if (item.kind === "blockUpdate") {
170
+ return Object.values(item.inputs).flatMap((input) =>
171
+ input.kind === "borrow" ? [input.place.root] : [],
172
+ );
173
+ }
174
+ return [];
175
+ };
176
+ /** The routine a statement runs: an invoke's function, or the block its instance's type instantiates. */
177
+ export const calledRoutine = (
178
+ item: CoreStatement,
179
+ variableOf: (id: string) => Variable | undefined,
180
+ types: ReadonlyMap<string, PlcType>,
181
+ ): string | undefined => {
182
+ if (item.kind === "invoke") {
183
+ return item.function;
184
+ }
185
+ if (item.kind !== "blockUpdate") {
186
+ return undefined;
187
+ }
188
+ const variable = variableOf(item.instance);
189
+ return variable && instancedBlock(variable.type, types)?.block;
190
+ };
191
+ export interface CoreFunction
192
+ extends Readonly<Omit<PlcFunction, "body" | "bounds">> {
193
+ readonly body: readonly CoreStatement[];
194
+ }
195
+ export interface CoreFunctionBlock
196
+ extends Readonly<Omit<FunctionBlock, "body">> {
197
+ readonly body: readonly CoreStatement[];
198
+ }
199
+ export const verified: unique symbol = Symbol("verified core");
200
+ export interface VerifiedCoreModule {
201
+ readonly [verified]: true;
202
+ readonly folded?: PlcModule["folded"];
203
+ readonly references?: PlcModule["references"];
204
+ readonly types: readonly PlcType[];
205
+ readonly variables: readonly Variable[];
206
+ readonly functions: readonly CoreFunction[];
207
+ readonly blocks: readonly CoreFunctionBlock[];
208
+ readonly programs: readonly PlcProgram[];
209
+ }
210
+
211
+ const verifiedModules = new WeakSet<object>();
212
+ export function isVerifiedCore(value: unknown): value is VerifiedCoreModule {
213
+ return (
214
+ typeof value === "object" && value !== null && verifiedModules.has(value)
215
+ );
216
+ }
217
+
218
+ /** Freezes a value and everything it holds. */
219
+ export function freeze(value: unknown): void {
220
+ if (typeof value !== "object" || value === null || Object.isFrozen(value)) {
221
+ return;
222
+ }
223
+ for (const child of Object.values(value)) {
224
+ freeze(child);
225
+ }
226
+ Object.freeze(value);
227
+ }
228
+
229
+ /**
230
+ * Admits a module across the trust boundary. Only normalization, and transformations of an
231
+ * admitted module that keep what it verified, call this.
232
+ */
233
+ export function admitCore(core: VerifiedCoreModule): VerifiedCoreModule {
234
+ freeze(core);
235
+ verifiedModules.add(core);
236
+ return core;
237
+ }
238
+
239
+ /** Whether a routine is a function block rather than a function. */
240
+ export function isBlockRoutine(
241
+ routine: CoreFunction | CoreFunctionBlock,
242
+ ): routine is CoreFunctionBlock;
243
+ export function isBlockRoutine(
244
+ routine: PlcFunction | FunctionBlock,
245
+ ): routine is FunctionBlock;
246
+ export function isBlockRoutine(
247
+ routine: CoreFunction | CoreFunctionBlock | PlcFunction | FunctionBlock,
248
+ ): boolean {
249
+ return "inputs" in routine;
250
+ }
251
+
252
+ /** The fields of a block's instance, in the order its type declares them: inputs, outputs, then state. */
253
+ export const instanceFields = (
254
+ block: CoreFunctionBlock,
255
+ ): readonly Variable[] => [...block.inputs, ...block.outputs, ...block.state];
256
+
257
+ /** Every variable a routine declares: a function's parameters and locals, a block's ports, state and locals. */
258
+ export const routineVariables = (
259
+ routine: CoreFunction | CoreFunctionBlock,
260
+ ): readonly Variable[] =>
261
+ isBlockRoutine(routine)
262
+ ? [...instanceFields(routine), ...routine.locals]
263
+ : [...routine.parameters, ...routine.locals];
264
+
265
+ const temporaryPrefix = (routine: string) => `${routine}:temporary:`;
266
+ export const temporaryId = (routine: string, index: number) =>
267
+ `${temporaryPrefix(routine)}${index}`;
268
+
269
+ /** Whether a local is a temporary the normalizer made for `routine`, rather than one its source declares. */
270
+ export function isTemporary(routine: string, variable: Variable): boolean {
271
+ const prefix = temporaryPrefix(routine);
272
+ return (
273
+ variable.storage === "local" &&
274
+ variable.id.startsWith(prefix) &&
275
+ /^\d+$/.test(variable.id.slice(prefix.length))
276
+ );
277
+ }
278
+
279
+ /**
280
+ * An index's value when it is an integer constant. Structural, because conditions' reconstructions
281
+ * carry indexes too, and they are not core expressions.
282
+ */
283
+ export const constantIndex = (expression: {
284
+ readonly kind: string;
285
+ readonly value?: Constant;
286
+ }): number | undefined =>
287
+ expression.kind === "constant" && expression.value?.kind === "integer"
288
+ ? Number(expression.value.value)
289
+ : undefined;
@@ -0,0 +1,281 @@
1
+ import { valueFits } from "./aggregates";
2
+ import type { SourceSpan } from "./diagnostics";
3
+ import { admitLayouts } from "./layouts";
4
+ import {
5
+ type FunctionBlock,
6
+ type PlcFunction,
7
+ type PlcModule,
8
+ type StandardBlock,
9
+ standardBlocks,
10
+ type Variable,
11
+ } from "./model";
12
+ import { reject } from "./normalization-error";
13
+ import { instancedBlock, isValueType, type PlcType } from "./types";
14
+
15
+ const matchesPorts = (
16
+ variables: readonly Variable[],
17
+ schema: readonly (readonly [string, string, string])[],
18
+ ): boolean =>
19
+ variables.length === schema.length &&
20
+ schema.every(([name, , type]) =>
21
+ variables.some(
22
+ (variable) =>
23
+ variable.name === name &&
24
+ variable.type === type &&
25
+ !variable.mode &&
26
+ variable.retention === "none",
27
+ ),
28
+ );
29
+
30
+ /** A standard block is exactly its vendor table entry: no body or state, and outputs at their defaults. */
31
+ const checkStandardBlock = (
32
+ block: FunctionBlock,
33
+ standard: StandardBlock,
34
+ ): void => {
35
+ const expected = standardBlocks[standard];
36
+ if (
37
+ block.name !== standard ||
38
+ block.body.length ||
39
+ block.state.length ||
40
+ block.locals.length ||
41
+ !matchesPorts(block.inputs, expected.inputs) ||
42
+ !matchesPorts(block.outputs, expected.outputs) ||
43
+ block.outputs.some(({ initial }) => {
44
+ switch (initial?.kind) {
45
+ case "bool":
46
+ return initial.value !== false;
47
+ case "duration":
48
+ return initial.nanoseconds !== "0";
49
+ case "integer":
50
+ return initial.value !== "0";
51
+ default:
52
+ return true;
53
+ }
54
+ })
55
+ ) {
56
+ reject("Invalid canonical standard block definition.", block.span);
57
+ }
58
+ };
59
+
60
+ // This index owns the module namespace and storage declarations. Routine
61
+ // lowering may claim temporary identifiers, but cannot weaken admission rules.
62
+ export class ModuleDeclarations {
63
+ private readonly ids = new Set<string>();
64
+ readonly types = new Map<string, PlcType>();
65
+ /** Each type's by-value size in scalar elements. */
66
+ readonly layoutSizes: ReadonlyMap<string, number>;
67
+ readonly globals = new Map<string, Variable>();
68
+ readonly blocks: Map<string, FunctionBlock>;
69
+ readonly signatures: Map<string, PlcFunction>;
70
+
71
+ constructor(module: PlcModule) {
72
+ for (const type of module.types) {
73
+ if (this.types.has(type.id)) {
74
+ reject(`Duplicate type ${type.id}.`);
75
+ }
76
+ this.types.set(type.id, type);
77
+ }
78
+ this.layoutSizes = admitLayouts(this.types);
79
+ if (this.types.get("BOOL")?.kind !== "bool") {
80
+ reject("Missing canonical BOOL type.");
81
+ }
82
+
83
+ this.blocks = new Map(module.blocks.map((block) => [block.id, block]));
84
+ for (const item of module.variables) {
85
+ this.checkVariable(item, [
86
+ "module",
87
+ "instance",
88
+ "input",
89
+ "output",
90
+ "constant",
91
+ ]);
92
+ this.globals.set(item.id, item);
93
+ }
94
+
95
+ this.signatures = new Map(module.functions.map((fn) => [fn.id, fn]));
96
+ for (const fn of module.functions) {
97
+ this.claimId(fn.id, fn.span);
98
+ if (
99
+ fn.owner &&
100
+ (!this.blocks.has(fn.owner.block) ||
101
+ this.blocks.get(fn.owner.block)?.standard)
102
+ ) {
103
+ reject(
104
+ "Methods require a user block owner and a valid access modifier.",
105
+ fn.span,
106
+ );
107
+ }
108
+ if (fn.result && !isValueType(fn.result, this.types)) {
109
+ reject("Unknown or non-value function result type.", fn.span);
110
+ }
111
+ for (const parameter of fn.parameters) {
112
+ this.checkVariable(parameter, ["parameter"], { allowBorrow: true });
113
+ if (parameter.mutable && !parameter.mode) {
114
+ reject("Value parameters are readonly.", parameter.span);
115
+ }
116
+ }
117
+ for (const local of fn.locals) {
118
+ this.checkVariable(local, ["local"]);
119
+ }
120
+ }
121
+
122
+ for (const block of module.blocks) {
123
+ this.claimId(block.id, block.span);
124
+ for (const input of block.inputs) {
125
+ this.checkVariable(input, ["parameter"], { allowBorrow: true });
126
+ if (!input.mode && input.mutable) {
127
+ reject("Value block inputs are readonly.", input.span);
128
+ }
129
+ }
130
+ for (const output of block.outputs) {
131
+ this.checkVariable(output, ["blockOutput"]);
132
+ }
133
+ for (const state of block.state) {
134
+ this.checkVariable(state, ["field", "instance"]);
135
+ // A controller has one persistent list, and it holds globals: an instance's state is the instance's to persist.
136
+ if (state.retention === "persist") {
137
+ reject(
138
+ "Only module state may persist; persist the module binding that holds the instance.",
139
+ state.span,
140
+ );
141
+ }
142
+ }
143
+ for (const local of block.locals) {
144
+ this.checkVariable(local, ["local"]);
145
+ }
146
+ for (const ports of [block.inputs, block.outputs]) {
147
+ if (
148
+ new Set(ports.map((variable) => variable.name)).size !== ports.length
149
+ ) {
150
+ reject(
151
+ "Block input and output names must each be unique within their schema.",
152
+ block.span,
153
+ );
154
+ }
155
+ }
156
+ const result = block.result ? this.types.get(block.result) : undefined;
157
+ if (
158
+ block.outputs.length
159
+ ? result?.kind !== "record" ||
160
+ !isValueType(result.id, this.types) ||
161
+ result.fields.length !== block.outputs.length ||
162
+ result.fields.some(
163
+ (field) =>
164
+ !block.outputs.some(
165
+ (output) =>
166
+ output.name === field.name && output.type === field.type,
167
+ ),
168
+ )
169
+ : Boolean(block.result)
170
+ ) {
171
+ reject(
172
+ "Block output schema differs from its result record.",
173
+ block.span,
174
+ );
175
+ }
176
+ if (block.standard) {
177
+ checkStandardBlock(block, block.standard);
178
+ }
179
+ }
180
+
181
+ for (const type of this.types.values()) {
182
+ if (type.kind === "block") {
183
+ const definition = this.blocks.get(type.block);
184
+ if (!definition || definition.result !== type.output) {
185
+ reject("Block type differs from its definition.");
186
+ }
187
+ }
188
+ }
189
+ }
190
+
191
+ hasId(id: string): boolean {
192
+ return this.ids.has(id);
193
+ }
194
+
195
+ public claimId(id: string, span?: SourceSpan): void {
196
+ if (this.ids.has(id)) {
197
+ reject(`Duplicate symbol ${id}.`, span);
198
+ }
199
+ this.ids.add(id);
200
+ }
201
+
202
+ private checkVariable(
203
+ item: Variable,
204
+ storage: readonly Variable["storage"][],
205
+ { allowBorrow }: { allowBorrow?: true } = {},
206
+ ): void {
207
+ this.claimId(item.id, item.span);
208
+ const type = this.types.get(item.type);
209
+ if (!type || !storage.includes(item.storage)) {
210
+ reject("Invalid storage type or class.", item.span);
211
+ }
212
+ if (
213
+ item.mode &&
214
+ (item.mode !== "inOut" ||
215
+ !allowBorrow ||
216
+ !item.mutable ||
217
+ item.storage !== "parameter")
218
+ ) {
219
+ reject("InOut belongs only on mutable parameters.", item.span);
220
+ }
221
+ const mutableState =
222
+ item.mutable ||
223
+ type.kind === "array" ||
224
+ (type.kind === "record" && type.fields.some((field) => !field.readonly));
225
+ if (
226
+ item.retention !== "none" &&
227
+ !(
228
+ item.storage === "instance" ||
229
+ (["module", "field"].includes(item.storage) && mutableState)
230
+ )
231
+ ) {
232
+ reject(
233
+ "Only mutable static state or block instances may retain.",
234
+ item.span,
235
+ );
236
+ }
237
+ if (item.storage === "instance") {
238
+ const instanced = instancedBlock(item.type, this.types);
239
+ if (
240
+ !instanced ||
241
+ !this.blocks.has(instanced.block) ||
242
+ item.initial ||
243
+ item.mode
244
+ ) {
245
+ reject(
246
+ "Instances require a known static block and cannot have value initializers.",
247
+ item.span,
248
+ );
249
+ }
250
+ } else if (
251
+ !isValueType(item.type, this.types) &&
252
+ !(allowBorrow && item.mode === "inOut" && type.kind === "block")
253
+ ) {
254
+ reject(
255
+ "Block instances and reference schemas cannot be stored as values.",
256
+ item.span,
257
+ );
258
+ }
259
+ if (item.storage === "parameter" && item.initial) {
260
+ reject(
261
+ "Inputs are supplied at each invocation and cannot have stored initializers.",
262
+ item.span,
263
+ );
264
+ }
265
+ if (item.initial && !valueFits(item.initial, type, this.types)) {
266
+ reject("Initializer has the wrong type or is out of range.", item.span);
267
+ }
268
+ if (
269
+ ["module", "field", "constant", "blockOutput"].includes(item.storage) &&
270
+ !item.initial
271
+ ) {
272
+ reject("Persistent storage requires initialization.", item.span);
273
+ }
274
+ if (
275
+ ["input", "constant", "blockOutput"].includes(item.storage) &&
276
+ item.mutable
277
+ ) {
278
+ reject("Readonly storage marked mutable.", item.span);
279
+ }
280
+ }
281
+ }
@@ -0,0 +1,68 @@
1
+ export interface SourceSpan {
2
+ file: string;
3
+ start: number;
4
+ end: number;
5
+ line: number;
6
+ column: number;
7
+ }
8
+
9
+ export interface Diagnostic {
10
+ origin: "typescript" | "plc" | "config" | "backend" | "vendor";
11
+ code: string;
12
+ severity: "error" | "warning";
13
+ message: string;
14
+ span?: SourceSpan;
15
+ notes?: readonly string[];
16
+ related?: readonly { span: SourceSpan; message: string }[];
17
+ }
18
+
19
+ export function error(
20
+ code: string,
21
+ message: string,
22
+ span?: SourceSpan,
23
+ ): Diagnostic {
24
+ return {
25
+ origin: "plc",
26
+ code,
27
+ severity: "error",
28
+ message,
29
+ ...(span && { span }),
30
+ };
31
+ }
32
+
33
+ export function hasErrors(diagnostics: readonly Diagnostic[]): boolean {
34
+ return diagnostics.some((diagnostic) => diagnostic.severity === "error");
35
+ }
36
+
37
+ export function formatDiagnostic(
38
+ diagnostic: Diagnostic,
39
+ source?: string,
40
+ ): string {
41
+ const { span } = diagnostic;
42
+ const location = span ? `${span.file}:${span.line}:${span.column}: ` : "";
43
+ return [
44
+ `${location}${diagnostic.code}: ${diagnostic.message}`,
45
+ ...(source !== undefined && span ? excerpt(span, source) : []),
46
+ ...(diagnostic.related ?? []).map(
47
+ (related) =>
48
+ ` ${related.span.file}:${related.span.line}:${related.span.column}: ${related.message}`,
49
+ ),
50
+ ...(diagnostic.notes ?? []).map((note) => ` ${note}`),
51
+ ].join("\n");
52
+ }
53
+
54
+ /** The source line a span starts on, underlined from the span's column. */
55
+ const excerpt = (span: SourceSpan, source: string): string[] => {
56
+ const line = source.split(/\r?\n/)[span.line - 1];
57
+ if (line === undefined) {
58
+ return [];
59
+ }
60
+ const width = Math.max(
61
+ 1,
62
+ Math.min(span.end - span.start, line.length - span.column + 2),
63
+ );
64
+ return [
65
+ `${span.line} | ${line}`,
66
+ `${" ".repeat(String(span.line).length + 3 + span.column - 1)}${"^".repeat(width)}`,
67
+ ];
68
+ };