@tsplc/compiler 0.2.17 → 0.2.19

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
@@ -1,105 +0,0 @@
1
- import type { PlcType, Variable, VerifiedCoreModule } from "@tsplc/compiler/ir";
2
- import { type IoTarget, ioLayout } from "@tsplc/typegen/hardware";
3
- import { moduleName } from "./storage.ts";
4
-
5
- type StorageSegment =
6
- { kind: "field"; record: string; name: string } | { kind: "index"; value: number };
7
-
8
- /** An `io` key that names a field of authored module storage, e.g. `PlantIO.Motor.Output.Run`. */
9
- export interface StorageBinding {
10
- key: string;
11
- root: Variable;
12
- segments: readonly StorageSegment[];
13
- type: PlcType;
14
- }
15
-
16
- const pathPattern = /^([\w$-]+)\.([A-Za-z_$][\w$]*)((?:\.[A-Za-z_$][\w$]*|\[-?\d+\])*)$/;
17
-
18
- export const isStoragePath = (key: string): boolean => key.includes(".") || key.includes("[");
19
-
20
- /** Resolve a storage path against verified types; the error explains the first unresolvable segment. */
21
- export function resolveStoragePath(
22
- core: VerifiedCoreModule,
23
- key: string,
24
- ): StorageBinding | { error: string } {
25
- const match = pathPattern.exec(key);
26
- if (!match) return { error: `${key}: expected Module.variable followed by .field or [index].` };
27
- const [, module, name, rest] = match;
28
- const roots = core.variables.filter(
29
- (item) => item.storage === "module" && item.name === name && moduleName(item) === module,
30
- );
31
- if (roots.length !== 1)
32
- return {
33
- error: roots.length
34
- ? `${key}: ${module}.${name} is declared by more than one module named ${module}.`
35
- : `${key}: no mutable module variable ${module}.${name}.`,
36
- };
37
- const root = roots[0]!;
38
- const types = new Map(core.types.map((type) => [type.id, type]));
39
- let type = types.get(root.type)!;
40
- const segments: StorageSegment[] = [];
41
- for (const [, field, index] of rest!.matchAll(/\.([A-Za-z_$][\w$]*)|\[(-?\d+)\]/g)) {
42
- if (field !== undefined) {
43
- const member = type.kind === "record" ? type.fields.find((f) => f.name === field) : undefined;
44
- if (!member) return { error: `${key}: no field ${field}.` };
45
- segments.push({ kind: "field", record: type.id, name: field });
46
- type = types.get(member.type)!;
47
- } else {
48
- const value = Number(index);
49
- if (type.kind !== "array") return { error: `${key}: ${index} indexes a non-array value.` };
50
- if (value < type.lowerBound || value >= type.lowerBound + type.length)
51
- return {
52
- error: `${key}: index ${value} is outside ${type.lowerBound}..${type.lowerBound + type.length - 1}.`,
53
- };
54
- segments.push({ kind: "index", value });
55
- type = types.get(type.element)!;
56
- }
57
- }
58
- return { key, root, segments, type };
59
- }
60
-
61
- /** IEC spelling of a bindable type, as typegen spells channels; undefined for records, enums, strings. */
62
- export function iecSpelling(
63
- type: PlcType,
64
- types: ReadonlyMap<string, PlcType>,
65
- ): string | undefined {
66
- if (
67
- type.kind === "bool" ||
68
- type.kind === "integer" ||
69
- type.kind === "bits" ||
70
- type.kind === "float" ||
71
- type.kind === "duration" ||
72
- type.kind === "calendar"
73
- )
74
- return type.id;
75
- if (type.kind !== "array") return undefined;
76
- const element = iecSpelling(types.get(type.element)!, types);
77
- const upper = type.lowerBound + type.length - 1;
78
- return element && !element.startsWith("ARRAY")
79
- ? `ARRAY[${type.lowerBound}..${upper}] OF ${element}`
80
- : undefined;
81
- }
82
-
83
- /** Every key an `io` mapping may use: logical IO names and paths into mutable module storage. */
84
- export function ioTargets(core: VerifiedCoreModule): IoTarget[] {
85
- const types = new Map(core.types.map((type) => [type.id, type]));
86
- const targets: IoTarget[] = [];
87
- const add = (key: string, type: PlcType) => {
88
- const layout = ioLayout(iecSpelling(type, types) ?? "");
89
- if (layout) targets.push({ key, layout });
90
- };
91
- const visit = (key: string, type: PlcType): void => {
92
- add(key, type);
93
- if (type.kind === "record")
94
- for (const field of type.fields) visit(`${key}.${field.name}`, types.get(field.type)!);
95
- // Typegen writes keys as template literal types, so any index matches here.
96
- if (type.kind === "array") visit(`${key}[` + "${number}" + "]", types.get(type.element)!);
97
- };
98
- for (const variable of core.variables) {
99
- if (variable.storage === "input" || variable.storage === "output")
100
- add(variable.name, types.get(variable.type)!);
101
- else if (variable.storage === "module")
102
- visit(`${moduleName(variable)}.${variable.name}`, types.get(variable.type)!);
103
- }
104
- return targets;
105
- }
@@ -1,312 +0,0 @@
1
- import { existsSync, readFileSync } from "node:fs";
2
- import { isAbsolute, relative } from "node:path";
3
- import { standardBlocks } from "@tsplc/compiler/ir";
4
- import type {
5
- Constant,
6
- CoreFunctionBlock,
7
- PlcModule,
8
- PlcType,
9
- SourceSpan,
10
- } from "@tsplc/compiler/ir";
11
- import type { ResolvedTsplcConfig } from "@tsplc/config";
12
- import type {
13
- DebugConstant,
14
- DebugDevice,
15
- DebugIo,
16
- DebugType,
17
- SourceRange,
18
- } from "@tsplc/debug/manifest";
19
- import type { HardwareCatalog } from "@tsplc/typegen/hardware";
20
- import type { CodesysTypes } from "./types.ts";
21
-
22
- /** The configured hardware a manifest describes; `tree` when this build generates the device tree. */
23
- export interface ProjectHardware {
24
- catalog: HardwareCatalog;
25
- config: Pick<ResolvedTsplcConfig, "devices" | "io">;
26
- tree: boolean;
27
- }
28
-
29
- /** Project files by index. Spans outside the project, such as virtual modules and packages, have no range. */
30
- export class Sources {
31
- readonly files: string[] = [];
32
- private readonly loaded = new Map<string, { text: string; lines: number[] } | undefined>();
33
-
34
- constructor(private readonly root: string) {}
35
-
36
- private load(file: string) {
37
- if (this.loaded.has(file)) return this.loaded.get(file);
38
- const path = relative(this.root, file);
39
- const inside =
40
- !path.startsWith("..") && !isAbsolute(path) && !path.split(/[\\/]/).includes("node_modules");
41
- let source: { text: string; lines: number[] } | undefined;
42
- if (inside && existsSync(file)) {
43
- const text = readFileSync(file, "utf8");
44
- const lines = [0];
45
- for (let index = 0; index < text.length; index++)
46
- if (text[index] === "\n") lines.push(index + 1);
47
- source = { text, lines };
48
- }
49
- this.loaded.set(file, source);
50
- return source;
51
- }
52
-
53
- range(span: SourceSpan): SourceRange | undefined {
54
- const source = this.load(span.file);
55
- if (!source || span.end > source.text.length) return undefined;
56
- const position = (offset: number) => {
57
- let low = 0,
58
- high = source.lines.length - 1;
59
- while (low < high) {
60
- const middle = (low + high + 1) >> 1;
61
- if (source.lines[middle]! <= offset) low = middle;
62
- else high = middle - 1;
63
- }
64
- return { line: low + 1, column: offset - source.lines[low]! + 1 };
65
- };
66
- const path = relative(this.root, span.file).replaceAll("\\", "/");
67
- let file = this.files.indexOf(path);
68
- if (file < 0) file = this.files.push(path) - 1;
69
- const start = position(span.start),
70
- end = position(span.end);
71
- return { file, ...start, endLine: end.line, endColumn: end.column };
72
- }
73
-
74
- text(span: SourceSpan): string | undefined {
75
- return this.load(span.file)?.text.slice(span.start, span.end);
76
- }
77
- }
78
-
79
- const scalarTypes: Partial<Record<PlcType["kind"], true>> = {
80
- bool: true,
81
- integer: true,
82
- bits: true,
83
- float: true,
84
- duration: true,
85
- calendar: true,
86
- };
87
-
88
- /** Every verified type by id, with TypeScript names and the target's field names. */
89
- export function debugTypes(
90
- types: readonly PlcType[],
91
- target: CodesysTypes,
92
- blocks: ReadonlyMap<string, CoreFunctionBlock>,
93
- fields: (block: string, variable: string) => string,
94
- extras: (block: string) => readonly { name: string; target: string; type: string }[],
95
- sources: Sources,
96
- ): Record<string, DebugType> {
97
- const name = (id: string) => id.split(":").at(-1)!;
98
- return Object.fromEntries(
99
- types.map((type): [string, DebugType] => {
100
- if (scalarTypes[type.kind]) return [type.id, { kind: "scalar", iec: type.id }];
101
- switch (type.kind) {
102
- case "string":
103
- return [
104
- type.id,
105
- { kind: "scalar", iec: type.encoding === "utf8" ? "STRING" : "WSTRING" },
106
- ];
107
- case "enum":
108
- return [
109
- type.id,
110
- {
111
- kind: "enum",
112
- name: name(type.id),
113
- members: Object.fromEntries(
114
- type.members.map((member) => [member.name, Number(member.value)]),
115
- ),
116
- },
117
- ];
118
- case "array":
119
- return [
120
- type.id,
121
- { kind: "array", element: type.element, length: type.length, lower: type.lowerBound },
122
- ];
123
- case "record":
124
- return [
125
- type.id,
126
- {
127
- kind: "record",
128
- name: name(type.id),
129
- fields: type.fields.map((field) => ({
130
- name: field.name,
131
- target: target.field(type.id, field.name),
132
- type: field.type,
133
- })),
134
- },
135
- ];
136
- case "block": {
137
- const block = blocks.get(type.block)!;
138
- const native = block.standard && standardBlocks[block.standard];
139
- const generated = Boolean(block.job || block.runtime);
140
- const declaration = sources.range(block.span);
141
- return [
142
- type.id,
143
- {
144
- kind: "record",
145
- name: block.job?.name ?? block.name,
146
- ...(declaration && { declaration }),
147
- fields: [
148
- ...[...block.inputs, ...block.outputs, ...block.state].map((variable) => {
149
- const declaration = !native && sources.range(variable.span);
150
- return {
151
- name: variable.name,
152
- target: fields(block.id, variable.id),
153
- type: variable.type,
154
- ...(declaration && { declaration }),
155
- ...(generated && { generated: true as const }),
156
- };
157
- }),
158
- ...extras(block.id).map((field) => ({ ...field, generated: true as const })),
159
- ],
160
- },
161
- ];
162
- }
163
- }
164
- throw new Error(`Unsupported verified type ${type.id}`);
165
- }),
166
- );
167
- }
168
-
169
- /** A folded constant's JSON value; integers beyond doubles' exact range stay strings. */
170
- const constantValue = (value: Constant): unknown => {
171
- switch (value.kind) {
172
- case "integer":
173
- return Number.isSafeInteger(Number(value.value)) ? Number(value.value) : value.value;
174
- case "duration":
175
- return `${BigInt(value.nanoseconds) / 1_000_000n}ms`;
176
- case "array":
177
- return value.items.map(constantValue);
178
- case "record":
179
- return Object.fromEntries(
180
- Object.entries(value.fields).map(([field, item]) => [field, constantValue(item)]),
181
- );
182
- default:
183
- return value.value;
184
- }
185
- };
186
-
187
- /** For folded values without a declared type, such as strings: named by the IEC type that holds them. */
188
- const constantTypes: Record<Constant["kind"], string> = {
189
- bool: "BOOL",
190
- integer: "LINT",
191
- float: "LREAL",
192
- duration: "TIME",
193
- calendar: "DATE_AND_TIME",
194
- string: "STRING",
195
- array: "ARRAY",
196
- record: "STRUCT",
197
- };
198
-
199
- export const debugConstants = (
200
- folded: NonNullable<PlcModule["folded"]>,
201
- sources: Sources,
202
- ): DebugConstant[] =>
203
- folded.map((item) => {
204
- const declaration = sources.range(item.span);
205
- return {
206
- path: item.path,
207
- type: item.type ?? constantTypes[item.value.kind],
208
- value: constantValue(item.value),
209
- ...(declaration && { declaration }),
210
- };
211
- });
212
-
213
- /** The `%I`/`%Q` address a configured binding uses: its own, or its device channel's. */
214
- export const ioAddress = (
215
- { catalog }: ProjectHardware,
216
- binding: ProjectHardware["config"]["io"][string],
217
- ) =>
218
- "address" in binding
219
- ? binding.address
220
- : catalog.devices
221
- .find((device) => device.id === binding.device)
222
- ?.channels.find((item) => item.id === binding.channel)?.address;
223
-
224
- /**
225
- * Each configured `io` binding joined with its device channel and the target that holds its
226
- * value, and each device with its assemblies, named channels and driver state. A generated
227
- * device tree names each adapter after its device, with a `<device>_Modbus` server for its
228
- * registers, so the debugger reads their state there.
229
- */
230
- export function debugHardware(
231
- hardware: ProjectHardware,
232
- io: (key: string) => { target: string; type: string } | undefined,
233
- /** The byte array over each of a device's assemblies. */
234
- raw: (id: string) => Partial<Record<"input" | "output", string>>,
235
- ): { io: DebugIo[]; devices: DebugDevice[] } {
236
- const { catalog, config } = hardware;
237
- const rows = Object.entries(config.io).flatMap(([key, binding]): DebugIo[] => {
238
- const held = io(key);
239
- if (!held) return [];
240
- const address = ioAddress(hardware, binding);
241
- return [
242
- {
243
- path: key,
244
- ...held,
245
- direction: address?.startsWith("%Q") ? "output" : "input",
246
- ...("device" in binding && { device: binding.device, channel: binding.channel }),
247
- ...(address && { address }),
248
- ...(binding.inverted && { inverted: true as const }),
249
- ...(binding.shared && { shared: true as const }),
250
- },
251
- ];
252
- });
253
- return {
254
- io: rows,
255
- devices: catalog.devices.map((device) => {
256
- const descriptor = catalog.descriptors.find((item) => item.file === device.descriptor);
257
- const network = config.devices[device.id]?.network;
258
- const bytes = raw(device.id);
259
- const status = {
260
- ...device.statusSymbols,
261
- ...(hardware.tree &&
262
- device.modbus && {
263
- "Modbus error": `${device.id}_Modbus.xError`,
264
- "Modbus error code": `${device.id}_Modbus.byModbusError`,
265
- }),
266
- };
267
- return {
268
- id: device.id,
269
- ...(descriptor && {
270
- product: descriptor.name,
271
- vendor: descriptor.vendor,
272
- productCode: descriptor.productCode,
273
- }),
274
- ...(network?.address && {
275
- network: {
276
- address: network.address,
277
- ...(network.rpi && { rpiMs: Number(BigInt(network.rpi.nanoseconds)) / 1e6 }),
278
- },
279
- }),
280
- ...(device.connection && { connection: device.connection.name }),
281
- assemblies: device.assemblies.map((assembly) => ({
282
- direction: assembly.direction,
283
- bytes: assembly.size,
284
- address: assembly.address,
285
- ...(bytes[assembly.direction] && { raw: bytes[assembly.direction] }),
286
- })),
287
- ...(hardware.tree && {
288
- health: {
289
- state: `${device.id}.eState`,
290
- diagnostic: `${device.id}.xDiagnosticAvailable`,
291
- message: `${device.id}.sDiagString`,
292
- },
293
- }),
294
- ...(Object.keys(status).length && { status }),
295
- // Byte and bit expansions of an assembly are covered by its raw bytes.
296
- channels: device.channels
297
- .filter((channel) => !channel.parent && !/^(inputs|outputs)\.Byte\d+$/.test(channel.id))
298
- .map((channel) => ({
299
- id: channel.id,
300
- name: channel.name,
301
- direction: channel.direction,
302
- type: channel.type,
303
- offsetBits: channel.offsetBits,
304
- bits: channel.bits,
305
- ...(channel.address && { address: channel.address }),
306
- ...(channel.unit && { unit: channel.unit }),
307
- ...(channel.description && { description: channel.description }),
308
- })),
309
- };
310
- }),
311
- };
312
- }
@@ -1,76 +0,0 @@
1
- // CODESYS declaration, statement, operator and elementary-type keywords.
2
- // https://content.helpme-codesys.com/en/CODESYS%20Development%20System/_cds_keywords.html
3
- const keywords = new Set(
4
- `
5
- ACTION END_ACTION PROGRAM END_PROGRAM FUNCTION END_FUNCTION FUNCTION_BLOCK END_FUNCTION_BLOCK
6
- INTERFACE END_INTERFACE METHOD END_METHOD PROPERTY END_PROPERTY
7
- TYPE END_TYPE STRUCT END_STRUCT UNION END_UNION ARRAY POINTER REFERENCE
8
- VAR END_VAR VAR_INPUT VAR_OUTPUT VAR_IN_OUT VAR_TEMP VAR_GLOBAL VAR_EXTERNAL
9
- VAR_ACCESS VAR_CONFIG VAR_STAT VAR_INST VAR_GENERIC
10
- CONSTANT RETAIN NON_RETAIN PERSISTENT AT READ_ONLY READ_WRITE PARAMS
11
- CONFIGURATION END_CONFIGURATION RESOURCE END_RESOURCE TASK WITH SINGLE INTERVAL PRIORITY
12
- PRIVATE PUBLIC PROTECTED INTERNAL ABSTRACT FINAL OVERRIDE EXTENDS IMPLEMENTS THIS SUPER
13
- IF THEN ELSIF ELSE END_IF CASE OF END_CASE FOR TO BY DO END_FOR
14
- WHILE END_WHILE REPEAT UNTIL END_REPEAT RETURN EXIT CONTINUE JMP
15
- TRUE FALSE BOOL BYTE WORD DWORD LWORD SINT USINT INT UINT DINT UDINT LINT ULINT
16
- REAL LREAL TIME LTIME DATE LDATE DATE_AND_TIME LDATE_AND_TIME TIME_OF_DAY LTIME_OF_DAY
17
- DT LDT TOD LTOD STRING WSTRING CHAR WCHAR
18
- ANY ANY_BIT ANY_DATE ANY_DERIVED ANY_ELEMENTARY ANY_INT ANY_MAGNITUDE ANY_NUM
19
- ANY_REAL ANY_STRING ANY_UNSIGNED
20
- AND AND_THEN OR OR_ELSE XOR NOT MOD ADD SUB MUL DIV MOVE SEL MIN MAX LIMIT
21
- ABS ACOS ASIN ATAN COS SIN TAN EXP EXPT LN LOG SQRT TRUNC SHL SHR ROL ROR
22
- ADR SIZEOF CONCAT DELETE FIND INSERT LEFT LEN MID REPLACE RIGHT
23
- `
24
- .trim()
25
- .split(/\s+/),
26
- );
27
- const types =
28
- "(?:BOOL|BYTE|WORD|DWORD|LWORD|SINT|USINT|INT|UINT|DINT|UDINT|LINT|ULINT|REAL|LREAL|TIME|LTIME|DATE|LDATE|DATE_AND_TIME|LDATE_AND_TIME|TIME_OF_DAY|LTIME_OF_DAY|DT|LDT|TOD|LTOD|STRING|WSTRING|CHAR|WCHAR)";
29
- const conversion = new RegExp(`^(?:${types}_TO_${types}|TO_${types}|TRUNC_${types})$`);
30
- export function isIecIdentifier(name: string): boolean {
31
- const upper = name.toUpperCase();
32
- return (
33
- /^[A-Za-z][A-Za-z0-9_]*$/.test(name) &&
34
- !name.includes("__") &&
35
- !keywords.has(upper) &&
36
- !conversion.test(upper)
37
- );
38
- }
39
-
40
- const identifierBody = (label: string): string =>
41
- label
42
- .replace(/[^A-Za-z0-9_]/g, "_")
43
- .replace(/_+/g, "_")
44
- .replace(/^_+|_+$/g, "") || "name";
45
-
46
- /** Capitals inside a word are kept, so `PlantIO` stays as written while `plant-io` is `PlantIo`. */
47
- export const pascalCase = (label: string): string =>
48
- label
49
- .split(/[^A-Za-z0-9]+/)
50
- .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
51
- .join("");
52
-
53
- export class Names {
54
- private readonly used = new Set<string>();
55
- allocateObject(prefix: "FB" | "F" | "PRG" | "ST" | "E" | "GVL", label: string): string {
56
- const source = prefix === "F" ? label.replace(/^PRG_/, "") : label;
57
- const kind = prefix === "F" && source.startsWith("FUN_") ? "FUN" : prefix;
58
- const body = source.startsWith(`${kind}_`) ? source.slice(kind.length + 1) : source;
59
- return this.allocate(`${kind}_${identifierBody(body)}`);
60
- }
61
-
62
- reserve(name: string): void {
63
- this.used.add(name.toUpperCase());
64
- // Qualified native types must keep their library prefix resolvable in the
65
- // declaration scope, not merely reserve the complete dotted spelling.
66
- const prefix = name.split(".")[0];
67
- if (prefix) this.used.add(prefix.toUpperCase());
68
- }
69
- allocate(label: string, preserve = true): string {
70
- const base = preserve && isIecIdentifier(label) ? label : `plc_${identifierBody(label)}`;
71
- let name = base;
72
- for (let suffix = 2; this.used.has(name.toUpperCase()); suffix++) name = `${base}_${suffix}`;
73
- this.reserve(name);
74
- return name;
75
- }
76
- }