@tsplc/tmp-compiler 0.0.0-stage → 0.6.2

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 (184) 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 +6558 -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 +16076 -0
  12. package/dist/index.js.map +61 -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 +1078 -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-functions.ts +204 -0
  69. package/src/frontend/control-flow.ts +787 -0
  70. package/src/frontend/cooperative.ts +114 -0
  71. package/src/frontend/coroutines.ts +1336 -0
  72. package/src/frontend/dialect-names.ts +104 -0
  73. package/src/frontend/elaborate/array-searches.ts +224 -0
  74. package/src/frontend/elaborate/assignments.ts +343 -0
  75. package/src/frontend/elaborate/calls.ts +1342 -0
  76. package/src/frontend/elaborate/capture-protocol.ts +237 -0
  77. package/src/frontend/elaborate/capture.ts +388 -0
  78. package/src/frontend/elaborate/declarations.ts +124 -0
  79. package/src/frontend/elaborate/dialect.ts +473 -0
  80. package/src/frontend/elaborate/expressions.ts +2171 -0
  81. package/src/frontend/elaborate/filtered-arrays.ts +643 -0
  82. package/src/frontend/elaborate/frame.ts +145 -0
  83. package/src/frontend/elaborate/generics.ts +123 -0
  84. package/src/frontend/elaborate/graph.ts +141 -0
  85. package/src/frontend/elaborate/imports.ts +105 -0
  86. package/src/frontend/elaborate/index.ts +851 -0
  87. package/src/frontend/elaborate/initializers.ts +235 -0
  88. package/src/frontend/elaborate/iterators.ts +1541 -0
  89. package/src/frontend/elaborate/layouts.ts +1025 -0
  90. package/src/frontend/elaborate/model.ts +478 -0
  91. package/src/frontend/elaborate/names.ts +134 -0
  92. package/src/frontend/elaborate/reduce.ts +900 -0
  93. package/src/frontend/elaborate/references.ts +727 -0
  94. package/src/frontend/elaborate/retention.ts +284 -0
  95. package/src/frontend/elaborate/specialize.ts +1137 -0
  96. package/src/frontend/elaborate/statements.ts +1220 -0
  97. package/src/frontend/elaborate/storage.ts +836 -0
  98. package/src/frontend/elaborate/time-constructors.ts +34 -0
  99. package/src/frontend/elaborate/values.ts +200 -0
  100. package/src/frontend/elaborate/writes.ts +415 -0
  101. package/src/frontend/expressions.ts +1382 -0
  102. package/src/frontend/generated-names.ts +95 -0
  103. package/src/frontend/intrinsics.ts +382 -0
  104. package/src/frontend/lowering-key.ts +23 -0
  105. package/src/frontend/module-graph.ts +156 -0
  106. package/src/frontend/positions.ts +359 -0
  107. package/src/frontend/promise-chains.ts +872 -0
  108. package/src/frontend/promises.ts +419 -0
  109. package/src/frontend/routines.ts +239 -0
  110. package/src/frontend/sdk.ts +187 -0
  111. package/src/frontend/services.ts +609 -0
  112. package/src/frontend/statements.ts +871 -0
  113. package/src/frontend/tasks.ts +526 -0
  114. package/src/frontend/telemetry.ts +174 -0
  115. package/src/frontend/types.ts +1073 -0
  116. package/src/frontend/typescript.ts +651 -0
  117. package/src/index.ts +9 -0
  118. package/src/ir/aggregates.ts +291 -0
  119. package/src/ir/allocation.ts +96 -0
  120. package/src/ir/conditions.ts +855 -0
  121. package/src/ir/core-model.ts +289 -0
  122. package/src/ir/declarations.ts +281 -0
  123. package/src/ir/diagnostics.ts +68 -0
  124. package/src/ir/domains.ts +151 -0
  125. package/src/ir/fold.ts +279 -0
  126. package/src/ir/identity.ts +19 -0
  127. package/src/ir/index.ts +137 -0
  128. package/src/ir/job-errors.ts +69 -0
  129. package/src/ir/layouts.ts +211 -0
  130. package/src/ir/link.ts +302 -0
  131. package/src/ir/model.ts +394 -0
  132. package/src/ir/normalization-error.ts +10 -0
  133. package/src/ir/normalize.ts +52 -0
  134. package/src/ir/numeric.ts +163 -0
  135. package/src/ir/operands.ts +160 -0
  136. package/src/ir/ranges.ts +420 -0
  137. package/src/ir/routine.ts +1116 -0
  138. package/src/ir/scalars.ts +453 -0
  139. package/src/ir/share.ts +790 -0
  140. package/src/ir/short-circuit.ts +140 -0
  141. package/src/ir/tables.ts +111 -0
  142. package/src/ir/temporaries.ts +138 -0
  143. package/src/ir/types.ts +151 -0
  144. package/src/project/artifacts.ts +424 -0
  145. package/src/project/cli.ts +211 -0
  146. package/src/project/debugger.ts +111 -0
  147. package/src/project/deployments.ts +387 -0
  148. package/src/project/flags.ts +14 -0
  149. package/src/project/git.ts +35 -0
  150. package/src/project/plant.ts +629 -0
  151. package/src/project/project-commands.ts +507 -0
  152. package/src/project/project.ts +559 -0
  153. package/src/project/release.ts +152 -0
  154. package/src/project/server-check.ts +54 -0
  155. package/src/project/server.ts +165 -0
  156. package/src/project/terminal.ts +45 -0
  157. package/src/runtime/async.ts +207 -0
  158. package/src/runtime/launch.ts +59 -0
  159. package/src/runtime/main.ts +59 -0
  160. package/src/runtime/missing-file.ts +3 -0
  161. package/src/runtime/process.ts +177 -0
  162. package/src/runtime/program.ts +109 -0
  163. package/src/runtime/retain.ts +108 -0
  164. package/src/runtime/runtime.ts +324 -0
  165. package/src/runtime/settings.ts +27 -0
  166. package/src/runtime/storage.ts +456 -0
  167. package/src/runtime/symbols.ts +97 -0
  168. package/src/runtime/telemetry.ts +154 -0
  169. package/src/runtime/transport.ts +168 -0
  170. package/stdlib/clock.ts +8 -0
  171. package/stdlib/collections.ts +534 -0
  172. package/stdlib/plc-time.ts +2 -0
  173. package/stdlib/retain.ts +4 -0
  174. package/stdlib/signals.ts +142 -0
  175. package/stdlib/telemetry.ts +89 -0
  176. package/types/async.d.ts +87 -0
  177. package/types/clock.d.ts +8 -0
  178. package/types/config.d.ts +2 -0
  179. package/types/data-types.d.ts +31 -0
  180. package/types/dialect.d.ts +49 -0
  181. package/types/globals.d.ts +10 -0
  182. package/types/index.d.ts +212 -0
  183. package/types/retain.d.ts +12 -0
  184. package/types/telemetry.d.ts +47 -0
@@ -0,0 +1,394 @@
1
+ import {
2
+ type BinaryOperator,
3
+ comparisonOperatorNames,
4
+ type UnaryOperator,
5
+ } from "@tsplc/iec/arithmetic";
6
+ import type { Diagnostic, SourceSpan } from "./diagnostics";
7
+ import type { PlcType, SymbolId, TypeId } from "./types";
8
+
9
+ export type Constant =
10
+ | { kind: "bool"; value: boolean }
11
+ | { kind: "integer"; value: string }
12
+ | { kind: "float"; value: number }
13
+ | { kind: "duration"; nanoseconds: string }
14
+ | { kind: "calendar"; value: string }
15
+ | { kind: "string"; value: string }
16
+ | { kind: "array"; items: readonly Constant[] }
17
+ | { kind: "record"; fields: Readonly<Record<string, Constant>> };
18
+
19
+ /**
20
+ * What a variable keeps when the controller restarts: nothing, a warm restart (`RETAIN`), or also
21
+ * a download and a cold reset (`PERSISTENT RETAIN`).
22
+ */
23
+ export type Retention = "none" | "retain" | "persist";
24
+
25
+ export interface Variable {
26
+ id: SymbolId;
27
+ name: string;
28
+ type: TypeId;
29
+ storage:
30
+ | "module"
31
+ | "local"
32
+ | "parameter"
33
+ | "input"
34
+ | "output"
35
+ | "field"
36
+ | "instance"
37
+ | "constant"
38
+ | "blockOutput";
39
+ mutable: boolean;
40
+ retention: Retention;
41
+ exported?: true;
42
+ mode?: "inOut";
43
+ initial?: Constant;
44
+ span: SourceSpan;
45
+ }
46
+
47
+ /** Whether a variable is one of the module's logical inputs and outputs, bound to the process image. */
48
+ export const isLogicalIo = (
49
+ variable: Variable,
50
+ ): variable is Variable & { storage: "input" | "output" } =>
51
+ variable.storage === "input" || variable.storage === "output";
52
+
53
+ /** How `T | undefined` is stored: the record `{ has, value }`, named with this prefix and `T`. */
54
+ export const optionalRecord = {
55
+ prefix: "Optional_",
56
+ has: "has",
57
+ value: "value",
58
+ } as const;
59
+
60
+ export interface Place {
61
+ root: SymbolId;
62
+ path: readonly (
63
+ | { kind: "field"; name: string }
64
+ | { kind: "index"; value: Expression }
65
+ )[];
66
+ }
67
+
68
+ export const comparisonOperators: ReadonlySet<BinaryOperator> = new Set(
69
+ comparisonOperatorNames,
70
+ );
71
+
72
+ export type Expression = { type: TypeId; span: SourceSpan } & (
73
+ | { kind: "constant"; value: Constant }
74
+ | { kind: "load"; place: Place }
75
+ | {
76
+ kind: "unary";
77
+ operator: UnaryOperator;
78
+ operand: Expression;
79
+ }
80
+ | {
81
+ kind: "binary";
82
+ operator: BinaryOperator;
83
+ left: Expression;
84
+ right: Expression;
85
+ policy?: "wrap" | "saturate";
86
+ }
87
+ | {
88
+ kind: "call";
89
+ function: SymbolId;
90
+ instance?: SymbolId;
91
+ index?: Expression;
92
+ arguments: readonly Expression[];
93
+ }
94
+ | {
95
+ kind: "conditional";
96
+ condition: Expression;
97
+ then: Expression;
98
+ else: Expression;
99
+ }
100
+ | {
101
+ kind: "convert";
102
+ operand: Expression;
103
+ policy: "exact" | "wrap" | "saturate";
104
+ }
105
+ | { kind: "borrow"; place: Place }
106
+ | { kind: "length"; operand: Expression }
107
+ | { kind: "copy"; operand: Expression }
108
+ | { kind: "record"; fields: Readonly<Record<string, Expression>> }
109
+ | { kind: "array"; items: readonly Expression[] }
110
+ );
111
+
112
+ export type Statement = { span: SourceSpan } & (
113
+ | { kind: "assign"; destination: Place; value: Expression }
114
+ | {
115
+ kind: "if";
116
+ condition: Expression;
117
+ then: readonly Statement[];
118
+ else: readonly Statement[];
119
+ }
120
+ | {
121
+ kind: "switch";
122
+ value: Expression;
123
+ cases: readonly {
124
+ values: readonly Constant[];
125
+ body: readonly Statement[];
126
+ }[];
127
+ fallback: readonly Statement[];
128
+ }
129
+ | {
130
+ kind: "for";
131
+ counter: SymbolId;
132
+ /** Existing storage remains observable after the loop exits. */
133
+ counterScope?: "existing";
134
+ start: Expression;
135
+ limit: Expression;
136
+ step: string;
137
+ exclusive?: true;
138
+ maxIterations: number;
139
+ body: readonly Statement[];
140
+ }
141
+ | {
142
+ kind: "invoke";
143
+ function: SymbolId;
144
+ instance?: SymbolId;
145
+ index?: Expression;
146
+ arguments: readonly Expression[];
147
+ destination?: Place;
148
+ }
149
+ | {
150
+ kind: "blockUpdate";
151
+ instance: SymbolId;
152
+ index?: Expression;
153
+ inputs: Readonly<Record<string, Expression>>;
154
+ }
155
+ | { kind: "return"; value?: Expression }
156
+ | { kind: "break" | "continue" }
157
+ | ({ kind: "telemetry" } & TelemetryCall<Expression>)
158
+ );
159
+
160
+ /**
161
+ * A `@tsplc/compiler/telemetry` call. `record` is what the record says besides its properties;
162
+ * a property with a `length` is a byte array, borrowed, sent as text up to that length.
163
+ */
164
+ export interface TelemetryCall<E> {
165
+ record:
166
+ | { kind: "event"; event: string }
167
+ | { kind: "log"; level: "info" | "warn" | "error"; message: string }
168
+ | { kind: "exception"; code: E };
169
+ properties: readonly { name: string; value: E; length?: E }[];
170
+ }
171
+
172
+ /** Every value a telemetry call reads, in evaluation order. */
173
+ export const telemetryOperands = <E>({
174
+ record,
175
+ properties,
176
+ }: TelemetryCall<E>): E[] => [
177
+ ...(record.kind === "exception" ? [record.code] : []),
178
+ ...properties.flatMap(({ value, length }) =>
179
+ length ? [value, length] : [value],
180
+ ),
181
+ ];
182
+
183
+ export interface MethodOwner {
184
+ block: SymbolId;
185
+ access: "public" | "private" | "protected";
186
+ }
187
+
188
+ export interface PlcFunction {
189
+ owner?: MethodOwner;
190
+ id: SymbolId;
191
+ name: string;
192
+ parameters: readonly Variable[];
193
+ locals: readonly Variable[];
194
+ result?: TypeId;
195
+ /** The source method this function was specialized from, as `Class.method`, and the TypeScript path of its `this`. */
196
+ origin?: { name: string; instance?: string };
197
+ body: readonly Statement[];
198
+ span: SourceSpan;
199
+ }
200
+
201
+ // Native vendor blocks under their TypeScript names. Ports are [name, native name, type];
202
+ // every output starts at its type's default, matching the vendor library blocks.
203
+ const timer = (input: string, output: string) =>
204
+ ({
205
+ inputs: [
206
+ [input, "IN", "BOOL"],
207
+ ["duration", "PT", "TIME"],
208
+ ],
209
+ outputs: [
210
+ [output, "Q", "BOOL"],
211
+ ["elapsed", "ET", "TIME"],
212
+ ],
213
+ }) as const;
214
+ export const standardBlocks = {
215
+ OnDelayTimer: { native: "TON", ...timer("enabled", "done") },
216
+ OffDelayTimer: { native: "TOF", ...timer("enabled", "active") },
217
+ PulseTimer: { native: "TP", ...timer("start", "active") },
218
+ RisingEdge: {
219
+ native: "R_TRIG",
220
+ inputs: [["signal", "CLK", "BOOL"]],
221
+ outputs: [["rose", "Q", "BOOL"]],
222
+ },
223
+ FallingEdge: {
224
+ native: "F_TRIG",
225
+ inputs: [["signal", "CLK", "BOOL"]],
226
+ outputs: [["fell", "Q", "BOOL"]],
227
+ },
228
+ UpCounter: {
229
+ native: "CTU",
230
+ inputs: [
231
+ ["countUp", "CU", "BOOL"],
232
+ ["reset", "RESET", "BOOL"],
233
+ ["preset", "PV", "WORD"],
234
+ ],
235
+ outputs: [
236
+ ["reachedPreset", "Q", "BOOL"],
237
+ ["value", "CV", "WORD"],
238
+ ],
239
+ },
240
+ DownCounter: {
241
+ native: "CTD",
242
+ inputs: [
243
+ ["countDown", "CD", "BOOL"],
244
+ ["load", "LOAD", "BOOL"],
245
+ ["preset", "PV", "WORD"],
246
+ ],
247
+ outputs: [
248
+ ["atZero", "Q", "BOOL"],
249
+ ["value", "CV", "WORD"],
250
+ ],
251
+ },
252
+ UpDownCounter: {
253
+ native: "CTUD",
254
+ inputs: [
255
+ ["countUp", "CU", "BOOL"],
256
+ ["countDown", "CD", "BOOL"],
257
+ ["reset", "RESET", "BOOL"],
258
+ ["load", "LOAD", "BOOL"],
259
+ ["preset", "PV", "WORD"],
260
+ ],
261
+ outputs: [
262
+ ["reachedPreset", "QU", "BOOL"],
263
+ ["atZero", "QD", "BOOL"],
264
+ ["value", "CV", "WORD"],
265
+ ],
266
+ },
267
+ Blinker: {
268
+ native: "Util.BLINK",
269
+ inputs: [
270
+ ["enabled", "ENABLE", "BOOL"],
271
+ ["offTime", "TIMELOW", "TIME"],
272
+ ["onTime", "TIMEHIGH", "TIME"],
273
+ ],
274
+ outputs: [["on", "OUT", "BOOL"]],
275
+ },
276
+ } as const;
277
+ export type StandardBlock = keyof typeof standardBlocks;
278
+
279
+ /** The methods a service call or `fetch` may use. */
280
+ export const httpMethods = ["GET", "POST", "PUT", "PATCH", "DELETE"] as const;
281
+ export type HttpMethod = (typeof httpMethods)[number];
282
+
283
+ export interface FunctionBlock {
284
+ id: SymbolId;
285
+ name: string;
286
+ inputs: readonly Variable[];
287
+ outputs: readonly Variable[];
288
+ state: readonly Variable[];
289
+ locals: readonly Variable[];
290
+ body: readonly Statement[];
291
+ result?: TypeId;
292
+ standard?: StandardBlock;
293
+ runtime?:
294
+ | { kind: "mailbox" }
295
+ | { kind: "backgroundHost" }
296
+ | { kind: "rpc"; path: string }
297
+ | {
298
+ kind: "http";
299
+ url: string;
300
+ method: HttpMethod;
301
+ json: boolean;
302
+ };
303
+ /** The async function lowered to this block, and the source each `step` value stands for. */
304
+ job?: {
305
+ name: string;
306
+ /** The TypeScript path of `this`, for a method specialized to one instance. */
307
+ instance?: string;
308
+ span: SourceSpan;
309
+ steps: readonly {
310
+ step: number;
311
+ kind: "await" | "return" | "throw" | "statement";
312
+ span: SourceSpan;
313
+ text: string;
314
+ }[];
315
+ };
316
+ span: SourceSpan;
317
+ }
318
+
319
+ export interface PlcProgram {
320
+ id: SymbolId;
321
+ name: string;
322
+ entry: SymbolId;
323
+ continuation?: { instance: string; file: string };
324
+ background?: {
325
+ intervalNanoseconds: string;
326
+ priority: number;
327
+ mailbox: string;
328
+ worker: string;
329
+ };
330
+ }
331
+
332
+ export interface PlcModule {
333
+ /**
334
+ * Fields the elaborator folded into constants: no storage, but a known value at each TypeScript
335
+ * path. `type` is the scalar's PLC type; strings, often enum members, have none.
336
+ */
337
+ folded?: readonly {
338
+ path: string;
339
+ value: Constant;
340
+ type?: TypeId;
341
+ span: SourceSpan;
342
+ }[];
343
+ /**
344
+ * Object references: the module storage path of each object by the id a reference holds (−1 is
345
+ * `undefined`), and the storage paths of the fields that hold a reference.
346
+ */
347
+ references?: {
348
+ objects: readonly { id: number; path: string }[];
349
+ fields: readonly string[];
350
+ };
351
+ types: readonly PlcType[];
352
+ variables: readonly Variable[];
353
+ functions: readonly PlcFunction[];
354
+ blocks: readonly FunctionBlock[];
355
+ programs: readonly PlcProgram[];
356
+ }
357
+
358
+ export interface Task {
359
+ name: string;
360
+ intervalNanoseconds: string;
361
+ priority: number;
362
+ programs: readonly string[];
363
+ }
364
+
365
+ export interface Deployment {
366
+ tasks: readonly Task[];
367
+ }
368
+
369
+ export interface Artifact {
370
+ path: string;
371
+ content: string;
372
+ }
373
+
374
+ export interface GeneratedObject {
375
+ parent?: SymbolId;
376
+ sourcePath?: string;
377
+ id: SymbolId;
378
+ kind:
379
+ | "program"
380
+ | "function"
381
+ | "functionBlock"
382
+ | "method"
383
+ | "globalList"
384
+ | "dataType";
385
+ name: string;
386
+ declaration: string;
387
+ implementation?: string;
388
+ }
389
+
390
+ export interface EmitResult {
391
+ artifacts: readonly Artifact[];
392
+ objects: readonly GeneratedObject[];
393
+ diagnostics: readonly Diagnostic[];
394
+ }
@@ -0,0 +1,10 @@
1
+ import { type Diagnostic, error, type SourceSpan } from "./diagnostics";
2
+
3
+ export class InvalidCore extends Error {
4
+ constructor(readonly diagnostic: Diagnostic) {
5
+ super(diagnostic.message);
6
+ }
7
+ }
8
+ export function reject(message: string, span?: SourceSpan): never {
9
+ throw new InvalidCore(error("PLC6001", message, span));
10
+ }
@@ -0,0 +1,52 @@
1
+ import { checkStaticAllocation } from "./allocation";
2
+ import {
3
+ admitCore,
4
+ type CoreFunction,
5
+ type CoreFunctionBlock,
6
+ isBlockRoutine,
7
+ type VerifiedCoreModule,
8
+ verified,
9
+ } from "./core-model";
10
+ import { ModuleDeclarations } from "./declarations";
11
+ import type { Diagnostic } from "./diagnostics";
12
+ import { linkModule } from "./link";
13
+ import type { PlcModule } from "./model";
14
+ import { InvalidCore } from "./normalization-error";
15
+ import { RoutineNormalizer } from "./routine";
16
+
17
+ export function normalizeModule(module: PlcModule): {
18
+ core?: VerifiedCoreModule;
19
+ diagnostics: readonly Diagnostic[];
20
+ } {
21
+ try {
22
+ const declarations = new ModuleDeclarations(module);
23
+ checkStaticAllocation(module, declarations);
24
+
25
+ const functions: CoreFunction[] = [];
26
+ const blocks: CoreFunctionBlock[] = [];
27
+ const edges = new Map<string, ReadonlySet<string>>();
28
+ for (const source of [...module.functions, ...module.blocks]) {
29
+ const normalized = new RoutineNormalizer(
30
+ source,
31
+ declarations,
32
+ ).normalize();
33
+ edges.set(source.id, normalized.callees);
34
+ if (isBlockRoutine(normalized.routine)) {
35
+ blocks.push(normalized.routine);
36
+ } else {
37
+ functions.push(normalized.routine);
38
+ }
39
+ }
40
+
41
+ const linked = linkModule(module, declarations, functions, blocks, edges);
42
+ return {
43
+ core: admitCore({ ...structuredClone(linked), [verified]: true }),
44
+ diagnostics: [],
45
+ };
46
+ } catch (cause) {
47
+ if (cause instanceof InvalidCore) {
48
+ return { diagnostics: [cause.diagnostic] };
49
+ }
50
+ throw cause;
51
+ }
52
+ }
@@ -0,0 +1,163 @@
1
+ import { roundFloat } from "@tsplc/iec/arithmetic";
2
+ import type { Constant } from "./model";
3
+ import { integerRange, integerType, type PlcType } from "./types";
4
+
5
+ type FloatType = Extract<PlcType, { kind: "float" }>;
6
+
7
+ /**
8
+ * The values from a lowest to a highest, inclusive. `excluded`, when given, is one value strictly
9
+ * between them that the range doesn't hold, as `n !== 0` proves of a signed `n`.
10
+ */
11
+ export type IntegerInterval = readonly [bigint, bigint, excluded?: bigint];
12
+
13
+ export const lowest = (a: bigint, b: bigint): bigint => (a < b ? a : b);
14
+ export const highest = (a: bigint, b: bigint): bigint => (a > b ? a : b);
15
+
16
+ /** Whether every value of `inner` lies in `outer`. */
17
+ export const within = (
18
+ inner: IntegerInterval,
19
+ outer: IntegerInterval,
20
+ ): boolean =>
21
+ inner[0] >= outer[0] &&
22
+ inner[1] <= outer[1] &&
23
+ (outer[2] === undefined || !admits(inner, outer[2]));
24
+
25
+ /** Whether `interval` admits `value`, such as a divisor that may be zero. */
26
+ export const admits = (interval: IntegerInterval, value: bigint): boolean =>
27
+ interval[0] <= value && value <= interval[1] && interval[2] !== value;
28
+
29
+ /** Integer constants are canonical decimal text: no leading zeros and no negative zero. */
30
+ export const canonicalInteger = /^(?:0|-?[1-9][0-9]*)$/;
31
+
32
+ // The significand precision of REAL (IEEE 754 binary32) and LREAL (binary64), which bounds the
33
+ // integers each format holds exactly.
34
+ const floatPrecision = { 32: 24, 64: 53 } as const;
35
+
36
+ /** Every integer from minus this limit to this limit converts to the float type exactly. */
37
+ export const exactIntegerLimit = (type: FloatType): bigint =>
38
+ 1n << BigInt(floatPrecision[type.bits]);
39
+
40
+ type DecimalIssue = "malformed" | "exponent" | "fraction";
41
+
42
+ /**
43
+ * A signed decimal with an optional fraction and exponent, times `scale`, exactly; it must come
44
+ * to a whole number. The exponent is capped so a literal cannot demand a vast power of ten.
45
+ */
46
+ export const exactDecimal = (
47
+ text: string,
48
+ scale: bigint,
49
+ ): bigint | DecimalIssue => {
50
+ const match = /^(-?\d+)(?:\.(\d*))?(?:e([+-]?\d+))?$/i.exec(text);
51
+ if (!match) {
52
+ return "malformed";
53
+ }
54
+ const [, whole, fraction = "", exponentText = "0"] = match;
55
+ const exponent = Number(exponentText) - fraction.length;
56
+ if (!Number.isSafeInteger(exponent) || Math.abs(exponent) > 400) {
57
+ return "exponent";
58
+ }
59
+ const digits = BigInt(`${whole}${fraction}`) * scale;
60
+ if (exponent >= 0) {
61
+ return digits * 10n ** BigInt(exponent);
62
+ }
63
+ const divisor = 10n ** BigInt(-exponent);
64
+ return digits % divisor ? "fraction" : digits / divisor;
65
+ };
66
+
67
+ const integerLiteralIssues: Record<DecimalIssue, string> = {
68
+ malformed: "Expected an exact integer literal.",
69
+ exponent: "Integer literal exponent is out of range.",
70
+ fraction:
71
+ "Integer literals cannot have a fractional part; to hold fractions, annotate the field or variable REAL or LREAL.",
72
+ };
73
+
74
+ /** Whether a numeric literal is written in hexadecimal, octal or binary, which has no fraction or exponent. */
75
+ export const isRadixLiteral = (text: string): boolean =>
76
+ /^-?0[xob]/i.test(text);
77
+
78
+ export const parseInteger = (text: string): bigint => {
79
+ const clean = text.replaceAll("_", "").replace(/n$/, "");
80
+ if (isRadixLiteral(clean)) {
81
+ return clean.startsWith("-") ? -BigInt(clean.slice(1)) : BigInt(clean);
82
+ }
83
+ const value = exactDecimal(clean, 1n);
84
+ if (typeof value !== "bigint") {
85
+ throw new Error(integerLiteralIssues[value]);
86
+ }
87
+ return value;
88
+ };
89
+
90
+ /** A float literal's value, rounded to its type's width. */
91
+ export const parseFloatLiteral = (text: string, type: FloatType): number => {
92
+ const clean = text.replaceAll("_", "");
93
+ const value = isRadixLiteral(clean)
94
+ ? Number(parseInteger(clean))
95
+ : Number(clean);
96
+ return roundFloat(value, type);
97
+ };
98
+
99
+ export const literalOutsideType =
100
+ "Literal is outside its PLC type or has the wrong domain.";
101
+
102
+ export const constantFits = (value: Constant, type: PlcType): boolean => {
103
+ if (type.kind === "bool") {
104
+ return value.kind === "bool";
105
+ }
106
+ if (integerType(type)) {
107
+ return (
108
+ value.kind === "integer" &&
109
+ canonicalInteger.test(value.value) &&
110
+ admits(integerRange(type), BigInt(value.value))
111
+ );
112
+ }
113
+ if (type.kind === "float") {
114
+ return (
115
+ value.kind === "float" &&
116
+ Number.isFinite(value.value) &&
117
+ Object.is(roundFloat(value.value, type), value.value)
118
+ );
119
+ }
120
+ return false;
121
+ };
122
+
123
+ export const canAssign = (
124
+ source: PlcType,
125
+ destination: PlcType,
126
+ value?: Constant,
127
+ ): boolean => {
128
+ if (value) {
129
+ return source.kind === destination.kind && constantFits(value, destination);
130
+ }
131
+ if (source.id === destination.id) {
132
+ return true;
133
+ }
134
+ if (source.kind === "integer" && destination.kind === "integer") {
135
+ return within(integerRange(source), integerRange(destination));
136
+ }
137
+ return (
138
+ source.kind === "float" &&
139
+ destination.kind === "float" &&
140
+ source.bits <= destination.bits
141
+ );
142
+ };
143
+
144
+ /**
145
+ * Integer +, - and *: native IEC arithmetic wraps them on overflow as hand-written ST does, and
146
+ * they are the operations that take an explicit wrap or saturate policy.
147
+ */
148
+ export const wrappingOperators: ReadonlySet<string> = new Set([
149
+ "add",
150
+ "subtract",
151
+ "multiply",
152
+ ]);
153
+
154
+ /** Whether an expression is plain integer +, - or *, which wraps natively. */
155
+ export const wrapsNatively = (expression: {
156
+ kind: string;
157
+ operator?: string;
158
+ policy?: string;
159
+ }): boolean =>
160
+ expression.kind === "binary" &&
161
+ !expression.policy &&
162
+ expression.operator !== undefined &&
163
+ wrappingOperators.has(expression.operator);