@tsplc/compiler 0.2.16 → 0.2.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/README.md +2 -2
  2. package/dist/cli.js +920 -943
  3. package/dist/cli.js.map +13 -10
  4. package/dist/codesys.js +3893 -3352
  5. package/dist/codesys.js.map +29 -20
  6. package/dist/elaborate-capture.js +33 -17
  7. package/dist/elaborate-capture.js.map +3 -3
  8. package/dist/index.js +8787 -6855
  9. package/dist/index.js.map +40 -20
  10. package/dist/ir.js +1575 -1072
  11. package/dist/ir.js.map +21 -17
  12. package/dist/math.js.map +2 -2
  13. package/dist/project.js +154 -60
  14. package/dist/project.js.map +5 -5
  15. package/dist/telemetry.js +27 -9
  16. package/dist/telemetry.js.map +5 -5
  17. package/package.json +112 -112
  18. package/src/codesys/config.ts +50 -0
  19. package/src/codesys/debug.ts +670 -0
  20. package/src/codesys/emit.ts +142 -0
  21. package/src/codesys/engineering.ts +109 -0
  22. package/src/codesys/expressions.ts +92 -0
  23. package/src/codesys/global-lists.ts +250 -0
  24. package/src/codesys/global-names.ts +68 -0
  25. package/src/codesys/http.ts +890 -0
  26. package/src/codesys/index.ts +30 -0
  27. package/src/codesys/instrumentation.ts +430 -0
  28. package/src/codesys/io-paths.ts +140 -0
  29. package/src/codesys/manifest.ts +643 -0
  30. package/src/codesys/names.ts +81 -0
  31. package/src/codesys/numeric.ts +409 -0
  32. package/src/codesys/operands.ts +62 -0
  33. package/src/codesys/plan.ts +605 -0
  34. package/src/codesys/programs.ts +53 -0
  35. package/src/codesys/publication.ts +171 -0
  36. package/src/codesys/routines.ts +603 -0
  37. package/src/codesys/sources.ts +71 -0
  38. package/src/codesys/st-files.ts +115 -0
  39. package/src/codesys/storage.ts +97 -0
  40. package/src/codesys/symbols.ts +220 -0
  41. package/src/codesys/task-access.ts +320 -0
  42. package/src/codesys/telemetry.ts +732 -0
  43. package/src/codesys/types.ts +250 -0
  44. package/src/codesys/vendor.ts +150 -0
  45. package/src/frontend/analyzer.ts +794 -0
  46. package/src/frontend/async.ts +317 -1137
  47. package/src/frontend/blocks.ts +537 -403
  48. package/src/frontend/configuration.ts +176 -144
  49. package/src/frontend/const-functions.ts +183 -148
  50. package/src/frontend/cooperative.ts +73 -43
  51. package/src/frontend/coroutines.ts +1032 -0
  52. package/src/frontend/elaborate/calls.ts +535 -0
  53. package/src/frontend/elaborate/capture.ts +157 -101
  54. package/src/frontend/elaborate/dialect.ts +257 -0
  55. package/src/frontend/elaborate/expressions.ts +992 -0
  56. package/src/frontend/elaborate/frame.ts +53 -0
  57. package/src/frontend/elaborate/graph.ts +116 -71
  58. package/src/frontend/elaborate/imports.ts +70 -0
  59. package/src/frontend/elaborate/index.ts +435 -331
  60. package/src/frontend/elaborate/initializers.ts +198 -0
  61. package/src/frontend/elaborate/layouts.ts +591 -384
  62. package/src/frontend/elaborate/model.ts +264 -169
  63. package/src/frontend/elaborate/specialize.ts +343 -2586
  64. package/src/frontend/elaborate/statements.ts +606 -0
  65. package/src/frontend/elaborate/storage.ts +546 -0
  66. package/src/frontend/elaborate/values.ts +58 -0
  67. package/src/frontend/elaborate/writes.ts +100 -0
  68. package/src/frontend/exposure.ts +172 -140
  69. package/src/frontend/expressions.ts +1383 -0
  70. package/src/frontend/intrinsics.ts +337 -0
  71. package/src/frontend/module-graph.ts +89 -59
  72. package/src/frontend/positions.ts +271 -200
  73. package/src/frontend/promise-chains.ts +897 -0
  74. package/src/frontend/promises.ts +390 -747
  75. package/src/frontend/routines.ts +181 -0
  76. package/src/frontend/sdk.ts +82 -0
  77. package/src/frontend/services.ts +506 -372
  78. package/src/frontend/statements.ts +855 -0
  79. package/src/frontend/tasks.ts +471 -0
  80. package/src/frontend/telemetry.ts +174 -0
  81. package/src/frontend/types.ts +845 -551
  82. package/src/frontend/typescript.ts +323 -2543
  83. package/src/index.ts +5 -5
  84. package/src/ir/aggregates.ts +275 -0
  85. package/src/ir/allocation.ts +84 -0
  86. package/src/ir/core-model.ts +146 -0
  87. package/src/ir/declarations.ts +295 -0
  88. package/src/ir/diagnostics.ts +61 -0
  89. package/src/ir/domains.ts +152 -0
  90. package/src/ir/fold.ts +342 -0
  91. package/src/ir/index.ts +90 -0
  92. package/{ir/errors.ts → src/ir/job-errors.ts} +12 -10
  93. package/src/ir/layouts.ts +181 -0
  94. package/src/ir/link.ts +354 -0
  95. package/src/ir/model.ts +386 -0
  96. package/{ir → src/ir}/normalization-error.ts +4 -4
  97. package/src/ir/normalize.ts +70 -0
  98. package/src/ir/numeric.ts +171 -0
  99. package/src/ir/ranges.ts +256 -0
  100. package/src/ir/routine.ts +1163 -0
  101. package/src/ir/scalars.ts +321 -0
  102. package/src/ir/types.ts +127 -0
  103. package/src/project/artifacts.ts +342 -0
  104. package/src/project/cli.ts +177 -0
  105. package/src/project/debugger.ts +82 -0
  106. package/src/project/index.ts +6 -0
  107. package/src/project/plant.ts +467 -0
  108. package/src/project/project-commands.ts +372 -0
  109. package/src/project/project.ts +457 -0
  110. package/src/project/release.ts +153 -0
  111. package/src/project/server.ts +150 -0
  112. package/src/project/terminal.ts +32 -0
  113. package/stdlib/math.ts +14 -10
  114. package/stdlib/telemetry.ts +71 -47
  115. package/types/async.d.ts +46 -40
  116. package/types/data-types.d.ts +26 -26
  117. package/types/globals.d.ts +41 -38
  118. package/types/index.d.ts +96 -51
  119. package/types/plc.d.ts +3 -4
  120. package/types/telemetry.d.ts +14 -14
  121. package/backends/codesys/config.ts +0 -54
  122. package/backends/codesys/debug.ts +0 -509
  123. package/backends/codesys/emit.ts +0 -1738
  124. package/backends/codesys/engineering.ts +0 -88
  125. package/backends/codesys/global-names.ts +0 -49
  126. package/backends/codesys/http.ts +0 -675
  127. package/backends/codesys/index.ts +0 -13
  128. package/backends/codesys/io-paths.ts +0 -105
  129. package/backends/codesys/manifest.ts +0 -312
  130. package/backends/codesys/names.ts +0 -76
  131. package/backends/codesys/numeric.ts +0 -356
  132. package/backends/codesys/plan.ts +0 -457
  133. package/backends/codesys/publication.ts +0 -59
  134. package/backends/codesys/storage.ts +0 -70
  135. package/backends/codesys/task-access.ts +0 -293
  136. package/backends/codesys/telemetry.ts +0 -593
  137. package/backends/codesys/types.ts +0 -179
  138. package/backends/codesys/vendor.ts +0 -108
  139. package/ir/aggregates.ts +0 -333
  140. package/ir/allocation.ts +0 -74
  141. package/ir/core-model.ts +0 -129
  142. package/ir/core.ts +0 -64
  143. package/ir/declarations.ts +0 -208
  144. package/ir/diagnostics.ts +0 -43
  145. package/ir/domains.ts +0 -96
  146. package/ir/index.ts +0 -8
  147. package/ir/link.ts +0 -185
  148. package/ir/model.ts +0 -346
  149. package/ir/routine.ts +0 -859
  150. package/ir/scalars.ts +0 -675
  151. package/ir/types.ts +0 -76
  152. package/project/artifacts.ts +0 -277
  153. package/project/cli.ts +0 -395
  154. package/project/index.ts +0 -1
  155. package/project/plant.ts +0 -509
  156. package/project/project.ts +0 -358
  157. package/project/server.ts +0 -113
@@ -0,0 +1,295 @@
1
+ import type { SourceSpan } from "./diagnostics.ts";
2
+ import {
3
+ standardBlocks,
4
+ type PlcModule,
5
+ type Variable,
6
+ type FunctionBlock,
7
+ type PlcFunction,
8
+ type StandardBlock,
9
+ } from "./model.ts";
10
+ import { instancedBlock, type PlcType } from "./types.ts";
11
+ import { valueFits } from "./aggregates.ts";
12
+ import { admitLayouts } from "./layouts.ts";
13
+ import { reject } from "./normalization-error.ts";
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.retain,
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 = Object.hasOwn(standardBlocks, standard)
36
+ ? standardBlocks[standard]
37
+ : undefined;
38
+ if (
39
+ !expected ||
40
+ block.name !== standard ||
41
+ block.body.length ||
42
+ block.state.length ||
43
+ block.locals.length ||
44
+ !matchesPorts(block.inputs, expected.inputs) ||
45
+ !matchesPorts(block.outputs, expected.outputs) ||
46
+ block.outputs.some(({ initial }) => {
47
+ switch (initial?.kind) {
48
+ case "bool":
49
+ return initial.value !== false;
50
+ case "duration":
51
+ return initial.nanoseconds !== "0";
52
+ case "integer":
53
+ return initial.value !== "0";
54
+ default:
55
+ return true;
56
+ }
57
+ })
58
+ ) {
59
+ reject("Invalid canonical standard block definition.", block.span);
60
+ }
61
+ };
62
+
63
+ // This index owns the module namespace and storage declarations. Routine
64
+ // lowering may claim temporary identifiers, but cannot weaken admission rules.
65
+ export class ModuleDeclarations {
66
+ private readonly ids = new Set<string>();
67
+ readonly types = new Map<string, PlcType>();
68
+ /** Each type's by-value size in scalar elements. */
69
+ readonly layoutSizes: ReadonlyMap<string, number>;
70
+ readonly globals = new Map<string, Variable>();
71
+ readonly blocks: Map<string, FunctionBlock>;
72
+ readonly signatures: Map<string, PlcFunction>;
73
+
74
+ constructor(module: PlcModule) {
75
+ for (const type of module.types) {
76
+ if (this.types.has(type.id)) {
77
+ reject(`Duplicate type ${type.id}.`);
78
+ }
79
+ this.types.set(type.id, type);
80
+ }
81
+ this.layoutSizes = admitLayouts(this.types);
82
+ if (this.types.get("BOOL")?.kind !== "bool") {
83
+ reject("Missing canonical BOOL type.");
84
+ }
85
+
86
+ this.blocks = new Map(module.blocks.map((block) => [block.id, block]));
87
+ for (const item of module.variables) {
88
+ this.checkVariable(item, [
89
+ "module",
90
+ "instance",
91
+ "input",
92
+ "output",
93
+ "constant",
94
+ ]);
95
+ this.globals.set(item.id, item);
96
+ }
97
+
98
+ this.signatures = new Map(module.functions.map((fn) => [fn.id, fn]));
99
+ for (const fn of module.functions) {
100
+ this.claimId(fn.id, fn.span);
101
+ if (
102
+ fn.owner &&
103
+ (!this.blocks.has(fn.owner.block) ||
104
+ this.blocks.get(fn.owner.block)?.standard ||
105
+ !["public", "private", "protected"].includes(fn.owner.access))
106
+ ) {
107
+ reject(
108
+ "Methods require a user block owner and a valid access modifier.",
109
+ fn.span,
110
+ );
111
+ }
112
+ if (fn.result && !this.isValueType(fn.result)) {
113
+ reject("Unknown or non-value function result type.", fn.span);
114
+ }
115
+ for (const parameter of fn.parameters) {
116
+ this.checkVariable(parameter, ["parameter"], true);
117
+ if (parameter.mutable && !parameter.mode) {
118
+ reject("Value parameters are readonly.", parameter.span);
119
+ }
120
+ }
121
+ for (const local of fn.locals) {
122
+ this.checkVariable(local, ["local"]);
123
+ }
124
+ }
125
+
126
+ for (const block of module.blocks) {
127
+ this.claimId(block.id, block.span);
128
+ for (const input of block.inputs) {
129
+ this.checkVariable(input, ["parameter"], true);
130
+ if (!input.mode && input.mutable) {
131
+ reject("Value block inputs are readonly.", input.span);
132
+ }
133
+ }
134
+ for (const output of block.outputs) {
135
+ this.checkVariable(output, ["blockOutput"]);
136
+ }
137
+ for (const state of block.state) {
138
+ this.checkVariable(state, ["field", "instance"]);
139
+ }
140
+ for (const local of block.locals) {
141
+ this.checkVariable(local, ["local"]);
142
+ }
143
+ for (const ports of [block.inputs, block.outputs]) {
144
+ if (
145
+ new Set(ports.map((variable) => variable.name)).size !== ports.length
146
+ ) {
147
+ reject(
148
+ "Block input and output names must each be unique within their schema.",
149
+ block.span,
150
+ );
151
+ }
152
+ }
153
+ const result = block.result ? this.types.get(block.result) : undefined;
154
+ if (
155
+ block.outputs.length
156
+ ? result?.kind !== "record" ||
157
+ !this.isValueType(result.id) ||
158
+ result.fields.length !== block.outputs.length ||
159
+ result.fields.some(
160
+ (field) =>
161
+ !block.outputs.some(
162
+ (output) =>
163
+ output.name === field.name && output.type === field.type,
164
+ ),
165
+ )
166
+ : Boolean(block.result)
167
+ ) {
168
+ reject(
169
+ "Block output schema differs from its result record.",
170
+ block.span,
171
+ );
172
+ }
173
+ if (block.standard) {
174
+ checkStandardBlock(block, block.standard);
175
+ }
176
+ }
177
+
178
+ for (const type of this.types.values()) {
179
+ if (type.kind === "block") {
180
+ const definition = this.blocks.get(type.block);
181
+ if (!definition || definition.result !== type.output) {
182
+ reject("Block type differs from its definition.");
183
+ }
184
+ }
185
+ }
186
+ }
187
+
188
+ hasId(id: string): boolean {
189
+ return this.ids.has(id);
190
+ }
191
+
192
+ public claimId(id: string, span?: SourceSpan): void {
193
+ if (this.ids.has(id)) {
194
+ reject(`Duplicate symbol ${id}.`, span);
195
+ }
196
+ this.ids.add(id);
197
+ }
198
+
199
+ public isValueType(id: string, seen = new Set<string>()): boolean {
200
+ if (seen.has(id)) {
201
+ return true;
202
+ }
203
+ seen.add(id);
204
+ const type = this.types.get(id);
205
+ return Boolean(
206
+ type &&
207
+ type.kind !== "block" &&
208
+ (type.kind !== "record" ||
209
+ type.fields.every(
210
+ (field) => !field.mode && this.isValueType(field.type, seen),
211
+ )) &&
212
+ (type.kind !== "array" || this.isValueType(type.element, seen)),
213
+ );
214
+ }
215
+
216
+ private checkVariable(
217
+ item: Variable,
218
+ storage: readonly Variable["storage"][],
219
+ allowBorrow = false,
220
+ ): void {
221
+ this.claimId(item.id, item.span);
222
+ const type = this.types.get(item.type);
223
+ if (!type || !storage.includes(item.storage)) {
224
+ reject("Invalid storage type or class.", item.span);
225
+ }
226
+ if (
227
+ item.mode &&
228
+ (item.mode !== "inOut" ||
229
+ !allowBorrow ||
230
+ !item.mutable ||
231
+ item.storage !== "parameter")
232
+ ) {
233
+ reject("InOut belongs only on mutable parameters.", item.span);
234
+ }
235
+ const mutableState =
236
+ item.mutable ||
237
+ type.kind === "array" ||
238
+ (type.kind === "record" && type.fields.some((field) => !field.readonly));
239
+ if (
240
+ item.retain &&
241
+ !(
242
+ item.storage === "instance" ||
243
+ (["module", "field"].includes(item.storage) && mutableState)
244
+ )
245
+ ) {
246
+ reject(
247
+ "Only mutable static state or block instances may retain.",
248
+ item.span,
249
+ );
250
+ }
251
+ if (item.storage === "instance") {
252
+ const instanced = instancedBlock(item.type, this.types);
253
+ if (
254
+ !instanced ||
255
+ !this.blocks.has(instanced.block) ||
256
+ item.initial ||
257
+ item.mode
258
+ ) {
259
+ reject(
260
+ "Instances require a known static block and cannot have value initializers.",
261
+ item.span,
262
+ );
263
+ }
264
+ } else if (
265
+ !this.isValueType(item.type) &&
266
+ !(allowBorrow && item.mode === "inOut" && type.kind === "block")
267
+ ) {
268
+ reject(
269
+ "Block instances and reference schemas cannot be stored as values.",
270
+ item.span,
271
+ );
272
+ }
273
+ if (item.storage === "parameter" && item.initial) {
274
+ reject(
275
+ "Inputs are supplied at each invocation and cannot have stored initializers.",
276
+ item.span,
277
+ );
278
+ }
279
+ if (item.initial && !valueFits(item.initial, type, this.types)) {
280
+ reject("Initializer has the wrong type or is out of range.", item.span);
281
+ }
282
+ if (
283
+ ["module", "field", "constant", "blockOutput"].includes(item.storage) &&
284
+ !item.initial
285
+ ) {
286
+ reject("Persistent storage requires initialization.", item.span);
287
+ }
288
+ if (
289
+ ["input", "constant", "blockOutput"].includes(item.storage) &&
290
+ item.mutable
291
+ ) {
292
+ reject("Readonly storage marked mutable.", item.span);
293
+ }
294
+ }
295
+ }
@@ -0,0 +1,61 @@
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
+ let result = `${location}${diagnostic.code}: ${diagnostic.message}`;
44
+ if (source !== undefined && span) {
45
+ const line = source.split(/\r?\n/)[span.line - 1];
46
+ if (line !== undefined) {
47
+ const width = Math.max(
48
+ 1,
49
+ Math.min(span.end - span.start, line.length - span.column + 2),
50
+ );
51
+ result += `\n${span.line} | ${line}\n${" ".repeat(String(span.line).length + 3 + span.column - 1)}${"^".repeat(width)}`;
52
+ }
53
+ }
54
+ for (const related of diagnostic.related ?? []) {
55
+ result += `\n ${related.span.file}:${related.span.line}:${related.span.column}: ${related.message}`;
56
+ }
57
+ for (const note of diagnostic.notes ?? []) {
58
+ result += `\n ${note}`;
59
+ }
60
+ return result;
61
+ }
@@ -0,0 +1,152 @@
1
+ import { elementaryType, integerRange } from "@tsplc/iec";
2
+ import {
3
+ comparisonOperators,
4
+ type Constant,
5
+ type Expression,
6
+ } from "./model.ts";
7
+ import { canonicalInteger, exactDecimal } from "./numeric.ts";
8
+ import type { PlcType } from "./types.ts";
9
+
10
+ export const nanosecondsPerMillisecond = 1_000_000n;
11
+
12
+ // TIME stores unsigned milliseconds.
13
+ const [, latestMillisecond] = integerRange({
14
+ bits: elementaryType("TIME").bits,
15
+ signed: false,
16
+ });
17
+
18
+ // DATE and DATE_AND_TIME store unsigned seconds since 1970-01-01T00:00:00 UTC.
19
+ const [, latestSecond] = integerRange({
20
+ bits: elementaryType("DATE_AND_TIME").bits,
21
+ signed: false,
22
+ });
23
+ const latestDateTime = new Date(Number(latestSecond) * 1000)
24
+ .toISOString()
25
+ .slice(0, "YYYY-MM-DDTHH:mm:ss".length);
26
+ const latestDate = latestDateTime.slice(0, "YYYY-MM-DD".length);
27
+
28
+ /** Each calendar domain's zero value, which is also its earliest. */
29
+ export const calendarZero: Record<
30
+ Extract<PlcType, { kind: "calendar" }>["domain"],
31
+ string
32
+ > = {
33
+ date: "1970-01-01",
34
+ timeOfDay: "00:00:00.000",
35
+ dateTime: "1970-01-01T00:00:00",
36
+ };
37
+
38
+ export function durationLiteral(
39
+ text: string,
40
+ scaleNanoseconds: bigint,
41
+ ): Constant | undefined {
42
+ const clean = text
43
+ .replaceAll("_", "")
44
+ .replace(/^(-?)\./, (_, sign: string) => `${sign}0.`);
45
+ const value = exactDecimal(clean, scaleNanoseconds);
46
+ return typeof value === "bigint" && validDuration(value)
47
+ ? { kind: "duration", nanoseconds: String(value) }
48
+ : undefined;
49
+ }
50
+ function validDuration(nanoseconds: bigint): boolean {
51
+ return (
52
+ nanoseconds >= 0n &&
53
+ nanoseconds <= latestMillisecond * nanosecondsPerMillisecond &&
54
+ nanoseconds % nanosecondsPerMillisecond === 0n
55
+ );
56
+ }
57
+ function validDate(text: string): boolean {
58
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text);
59
+ if (!match) {
60
+ return false;
61
+ }
62
+ const year = Number(match[1]);
63
+ const month = Number(match[2]);
64
+ const day = Number(match[3]);
65
+ const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
66
+ const length = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][
67
+ month - 1
68
+ ];
69
+ return Boolean(
70
+ length &&
71
+ day >= 1 &&
72
+ day <= length &&
73
+ text >= calendarZero.date &&
74
+ text <= latestDate,
75
+ );
76
+ }
77
+ function validClock(text: string, milliseconds: boolean): boolean {
78
+ const match = (
79
+ milliseconds
80
+ ? /^(\d{2}):(\d{2}):(\d{2})\.(\d{3})$/
81
+ : /^(\d{2}):(\d{2}):(\d{2})$/
82
+ ).exec(text);
83
+ return Boolean(
84
+ match &&
85
+ Number(match[1]) < 24 &&
86
+ Number(match[2]) < 60 &&
87
+ Number(match[3]) < 60,
88
+ );
89
+ }
90
+ export function calendarLiteral(
91
+ domain: Extract<PlcType, { kind: "calendar" }>["domain"],
92
+ text: string,
93
+ ): Constant | undefined {
94
+ if (domain === "date") {
95
+ return validDate(text) ? { kind: "calendar", value: text } : undefined;
96
+ }
97
+ if (domain === "timeOfDay") {
98
+ const canonical = /^\d{2}:\d{2}:\d{2}$/.test(text) ? `${text}.000` : text;
99
+ return validClock(canonical, true)
100
+ ? { kind: "calendar", value: canonical }
101
+ : undefined;
102
+ }
103
+ return text.length === 19 &&
104
+ text[10] === "T" &&
105
+ validDate(text.slice(0, 10)) &&
106
+ validClock(text.slice(11), false) &&
107
+ text <= latestDateTime
108
+ ? { kind: "calendar", value: text }
109
+ : undefined;
110
+ }
111
+ export function domainConstantFits(value: Constant, type: PlcType): boolean {
112
+ if (type.kind === "duration") {
113
+ return (
114
+ value.kind === "duration" &&
115
+ canonicalInteger.test(value.nanoseconds) &&
116
+ validDuration(BigInt(value.nanoseconds))
117
+ );
118
+ }
119
+ if (type.kind === "calendar" && value.kind === "calendar") {
120
+ const parsed = calendarLiteral(type.domain, value.value);
121
+ return parsed?.kind === "calendar" && parsed.value === value.value;
122
+ }
123
+ return false;
124
+ }
125
+ export function domainIssue(
126
+ value: Expression,
127
+ types: ReadonlyMap<string, PlcType>,
128
+ ): string | undefined {
129
+ const type = types.get(value.type);
130
+ if (value.kind === "constant") {
131
+ return type && domainConstantFits(value.value, type)
132
+ ? undefined
133
+ : "Invalid TIME/calendar constant.";
134
+ }
135
+ if (
136
+ value.kind === "load" ||
137
+ value.kind === "call" ||
138
+ value.kind === "conditional"
139
+ ) {
140
+ return undefined;
141
+ }
142
+ if (value.kind === "binary" && comparisonOperators.has(value.operator)) {
143
+ const left = types.get(value.left.type);
144
+ return value.type === "BOOL" &&
145
+ left &&
146
+ ["duration", "calendar"].includes(left.kind) &&
147
+ value.left.type === value.right.type
148
+ ? undefined
149
+ : "Time comparisons require matching domains.";
150
+ }
151
+ return "TIME and calendar domains permit storage, typed copies and comparisons; implicit numeric arithmetic is unsupported.";
152
+ }