@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
@@ -0,0 +1,250 @@
1
+ import { instancedBlock, nanosecondsPerMillisecond } from "@tsplc/compiler/ir";
2
+ import type { Constant, GeneratedObject, PlcType } from "@tsplc/compiler/ir";
3
+ import { escapeString } from "@tsplc/iec/st";
4
+ import { Names } from "./names.ts";
5
+ import { scalarLiteral } from "./numeric.ts";
6
+
7
+ /** A type's name as its source declares it: the last segment of its id. */
8
+ export const sourceTypeName = (id: string) => id.slice(id.lastIndexOf(":") + 1);
9
+
10
+ /** The elementary type that holds a string type's text. */
11
+ export const stringTypeName = (type: Extract<PlcType, { kind: "string" }>) =>
12
+ type.encoding === "utf8" ? "STRING" : "WSTRING";
13
+
14
+ const stEscapes: ReadonlyMap<string, string> = new Map([
15
+ ["$", "$$"],
16
+ ["'", "$'"],
17
+ ["\r", "$R"],
18
+ ["\n", "$N"],
19
+ ]);
20
+ /**
21
+ * An ST STRING literal of text the compiler generates, such as an HTTP request line. Program
22
+ * constants go through `CodesysTypes.literal`, which writes every control character as its code.
23
+ */
24
+ export const stStringLiteral = (text: string) =>
25
+ `'${[...text].map((character) => stEscapes.get(character) ?? character).join("")}'`;
26
+
27
+ export class CodesysTypes {
28
+ readonly objects: GeneratedObject[] = [];
29
+ private readonly names = new Map<string, string>();
30
+ private readonly fields = new Map<string, Map<string, string>>();
31
+
32
+ constructor(
33
+ private readonly types: ReadonlyMap<string, PlcType>,
34
+ names: Names,
35
+ blockNames: ReadonlyMap<string, string>,
36
+ ) {
37
+ // Register every type and member name before following layout dependencies.
38
+ for (const type of types.values()) {
39
+ if (type.kind === "block") {
40
+ const name = blockNames.get(type.block);
41
+ if (!name) {
42
+ throw new Error("Missing verified block name");
43
+ }
44
+ this.names.set(type.id, name);
45
+ }
46
+ if (["record", "array", "enum", "string"].includes(type.kind)) {
47
+ const label = sourceTypeName(type.id);
48
+ if (type.kind === "record" || type.kind === "enum") {
49
+ const prefix = type.kind === "record" ? "ST" : "E";
50
+ this.names.set(type.id, names.allocateObject(prefix, label));
51
+ } else {
52
+ this.names.set(type.id, names.allocate(`T_${label}`));
53
+ }
54
+ }
55
+ if (type.kind === "record" || type.kind === "enum") {
56
+ const names = new Names();
57
+ const fields = new Map<string, string>();
58
+ for (const member of type.kind === "record"
59
+ ? type.fields
60
+ : type.members) {
61
+ fields.set(member.name, names.allocate(member.name));
62
+ }
63
+ this.fields.set(type.id, fields);
64
+ }
65
+ }
66
+
67
+ // A block array is declared in place: a function block cannot be a data type's element.
68
+ for (const type of types.values()) {
69
+ if (type.kind === "array" && instancedBlock(type.id, types)) {
70
+ this.names.set(
71
+ type.id,
72
+ `ARRAY[${type.lowerBound}..${type.lowerBound + type.length - 1}] OF ${this.name(type.element)}`,
73
+ );
74
+ }
75
+ }
76
+
77
+ // Verified layouts are acyclic. Emit child DUTs first, then their containing DUT.
78
+ const emitted = new Set<string>();
79
+ const emit = (type: PlcType): void => {
80
+ if (
81
+ instancedBlock(type.id, types) ||
82
+ !this.names.has(type.id) ||
83
+ emitted.has(type.id)
84
+ ) {
85
+ return;
86
+ }
87
+ if (type.kind === "array") {
88
+ emit(this.type(type.element));
89
+ }
90
+ if (type.kind === "record") {
91
+ for (const field of type.fields) {
92
+ emit(this.type(field.type));
93
+ }
94
+ }
95
+ emitted.add(type.id);
96
+ const name = this.name(type.id);
97
+ const declaration = this.dutDeclaration(type, name);
98
+ this.objects.push({ id: type.id, kind: "dataType", name, declaration });
99
+ };
100
+ for (const type of types.values()) {
101
+ emit(type);
102
+ }
103
+ }
104
+
105
+ /** The declaration of a data type's DUT. */
106
+ private dutDeclaration(type: PlcType, name: string): string {
107
+ if (type.kind === "record") {
108
+ const fields = type.fields
109
+ .map(
110
+ (field) =>
111
+ ` ${this.field(type.id, field.name)} : ${this.name(field.type)};`,
112
+ )
113
+ .join("\n");
114
+ return `TYPE ${name} :
115
+ STRUCT
116
+ ${fields}
117
+ END_STRUCT
118
+ END_TYPE
119
+ `;
120
+ }
121
+ if (type.kind === "array") {
122
+ // Typegen publishes each key of a `Record<Enum, T>` as its own contract variable.
123
+ return `${type.index ? "{attribute 'tsplc_keyed'}\n" : ""}TYPE ${name} : ARRAY[${type.lowerBound}..${type.lowerBound + type.length - 1}] OF ${this.name(type.element)};
124
+ END_TYPE
125
+ `;
126
+ }
127
+ if (type.kind === "string") {
128
+ return `TYPE ${name} : ${stringTypeName(type)}(${type.capacity});
129
+ END_TYPE
130
+ `;
131
+ }
132
+ if (type.kind === "enum") {
133
+ const members = type.members
134
+ .map(
135
+ (member) =>
136
+ ` ${this.field(type.id, member.name)} := ${member.value}`,
137
+ )
138
+ .join(",\n");
139
+ return `{attribute 'qualified_only'}
140
+ {attribute 'strict'}
141
+ TYPE ${name} : (
142
+ ${members}
143
+ ) DINT;
144
+ END_TYPE
145
+ `;
146
+ }
147
+ throw new Error("Unsupported verified data type");
148
+ }
149
+
150
+ private type(id: string): PlcType {
151
+ const type = this.types.get(id);
152
+ if (!type) {
153
+ throw new Error("Missing verified type");
154
+ }
155
+ return type;
156
+ }
157
+
158
+ name(id: string): string {
159
+ return this.names.get(id) ?? id;
160
+ }
161
+
162
+ field(id: string, name: string): string {
163
+ const field = this.fields.get(id)?.get(name);
164
+ if (!field) {
165
+ throw new Error("Missing verified field");
166
+ }
167
+ return field;
168
+ }
169
+
170
+ declarationInitializer(value: Constant, id: string): string {
171
+ const type = this.type(id);
172
+ // Our DUT fields have no custom initializers. CODESYS initializes their
173
+ // numbers/BOOL/strings to zero/false/empty, including nested arrays/records.
174
+ // Keep explicit nonzero enum members and signed floating zero: omission must
175
+ // not change the initial value selected by PLC semantics.
176
+ if (
177
+ (type.kind === "record" || type.kind === "array") &&
178
+ this.isZero(value)
179
+ ) {
180
+ return "";
181
+ }
182
+ return ` := ${this.literal(value, id)}`;
183
+ }
184
+
185
+ private isZero(value: Constant): boolean {
186
+ if (value.kind === "bool") {
187
+ return !value.value;
188
+ }
189
+ if (value.kind === "integer") {
190
+ return value.value === "0";
191
+ }
192
+ if (value.kind === "float") {
193
+ return Object.is(value.value, 0);
194
+ }
195
+ if (value.kind === "string") {
196
+ return value.value === "";
197
+ }
198
+ if (value.kind === "array") {
199
+ return value.items.every((item) => this.isZero(item));
200
+ }
201
+ if (value.kind === "record") {
202
+ return Object.values(value.fields).every((item) => this.isZero(item));
203
+ }
204
+ // Time/calendar values remain explicit without relying on target defaults.
205
+ return false;
206
+ }
207
+
208
+ literal(value: Constant, id: string): string {
209
+ const type = this.type(id);
210
+ if (type.kind === "enum" && value.kind === "integer") {
211
+ const member = type.members.find(
212
+ (member) => member.value === value.value,
213
+ );
214
+ if (!member) {
215
+ throw new Error("Missing verified enum member");
216
+ }
217
+ return `${this.name(id)}.${this.field(id, member.name)}`;
218
+ }
219
+ if (type.kind === "string" && value.kind === "string") {
220
+ const delimiter = type.encoding === "utf16" ? '"' : "'";
221
+ return `${delimiter}${escapeString(value.value, delimiter)}${delimiter}`;
222
+ }
223
+ if (type.kind === "array" && value.kind === "array") {
224
+ return `[${value.items.map((item) => this.literal(item, type.element)).join(", ")}]`;
225
+ }
226
+ if (type.kind === "record" && value.kind === "record") {
227
+ const fields = type.fields.map((field) => {
228
+ const initial = value.fields[field.name];
229
+ if (!initial) {
230
+ throw new Error("Missing verified record initializer");
231
+ }
232
+ return `${this.field(id, field.name)} := ${this.literal(initial, field.type)}`;
233
+ });
234
+ return `(${fields.join(", ")})`;
235
+ }
236
+ if (type.kind === "duration" && value.kind === "duration") {
237
+ return `T#${BigInt(value.nanoseconds) / nanosecondsPerMillisecond}ms`;
238
+ }
239
+ if (type.kind === "calendar" && value.kind === "calendar") {
240
+ if (type.domain === "date") {
241
+ return `D#${value.value}`;
242
+ }
243
+ if (type.domain === "timeOfDay") {
244
+ return `TOD#${value.value}`;
245
+ }
246
+ return `DT#${value.value.replace("T", "-")}`;
247
+ }
248
+ return scalarLiteral(value, id);
249
+ }
250
+ }
@@ -0,0 +1,150 @@
1
+ import type {
2
+ Diagnostic,
3
+ EmitResult,
4
+ GeneratedObject,
5
+ } from "@tsplc/compiler/ir";
6
+ import { CodesysCompilerError } from "@tsplc/build";
7
+ import type { SourceMapping } from "./emit.ts";
8
+ import { declarationFile } from "./st-files.ts";
9
+
10
+ type MappedBundle = Pick<EmitResult, "objects"> & {
11
+ mappings: readonly SourceMapping[];
12
+ };
13
+
14
+ /** The generated file a vendor location is in: its object's declaration, or its implementation when it has one. */
15
+ const sectionFile = (
16
+ match: { object: GeneratedObject; declaration: string } | undefined,
17
+ section: "declaration" | "implementation",
18
+ ): string | undefined => {
19
+ if (section === "declaration") {
20
+ return match?.declaration;
21
+ }
22
+ return match?.object.implementation === undefined
23
+ ? undefined
24
+ : match.declaration.replace(/declaration\.st$/, "implementation.st");
25
+ };
26
+
27
+ /** An object's path below the Application, when the vendor's identity of it proves one. */
28
+ const applicationObjectPath = (
29
+ identity: NonNullable<CodesysCompilerError["diagnostics"][number]["object"]>,
30
+ ): string | undefined => {
31
+ if (identity.path.at(-1) !== identity.name) {
32
+ return undefined;
33
+ }
34
+ const relative = identity.applicationPath;
35
+ if (
36
+ Array.isArray(relative) &&
37
+ relative.length > 0 &&
38
+ relative.every((part) => typeof part === "string") &&
39
+ identity.isApplicationChild === (relative.length === 1) &&
40
+ identity.path.length > relative.length &&
41
+ identity.path
42
+ .slice(-relative.length)
43
+ .every((part, index) => part === relative[index])
44
+ ) {
45
+ return relative.join("/");
46
+ }
47
+ if (
48
+ relative === undefined &&
49
+ identity.isApplicationChild === true &&
50
+ identity.path.length >= 2
51
+ ) {
52
+ // A verified immediate Application parent proves the root identity.
53
+ return identity.name;
54
+ }
55
+ return undefined;
56
+ };
57
+
58
+ /** Map verified vendor locations; preserve raw context for everything else. */
59
+ export function diagnoseCodesys(
60
+ cause: unknown,
61
+ bundle: MappedBundle,
62
+ ): readonly Diagnostic[] {
63
+ const notes: string[] = [];
64
+ let current = cause;
65
+ while (current instanceof Error) {
66
+ if (current instanceof CodesysCompilerError && current.diagnostics.length) {
67
+ return current.diagnostics.map((item) => {
68
+ // Observed in CODESYS 3.5 SP22. position itself is an opaque vendor value.
69
+ const location =
70
+ item.positionText &&
71
+ /^Line ([1-9][0-9]*)(?:, Column ([1-9][0-9]*))? \((Decl|Impl)\)$/.exec(
72
+ item.positionText,
73
+ );
74
+ const identity = item.object;
75
+ const objectPath = identity && applicationObjectPath(identity);
76
+ const objects = objectPath
77
+ ? bundle.objects.flatMap((object) => {
78
+ const declaration =
79
+ object.sourcePath ?? declarationFile(object.name, object);
80
+ const nativePath = (
81
+ object.kind === "method"
82
+ ? declaration.replace(
83
+ /\/methods\/([^/]+\/declaration\.st)$/,
84
+ "/$1",
85
+ )
86
+ : declaration
87
+ ).replace(
88
+ object.implementation === undefined
89
+ ? /\.st$/
90
+ : /\/declaration\.st$/,
91
+ "",
92
+ );
93
+ return object.name === identity?.name && nativePath === objectPath
94
+ ? [{ object, declaration }]
95
+ : [];
96
+ })
97
+ : [];
98
+ const match = objects.length === 1 ? objects[0] : undefined;
99
+ const section =
100
+ location?.[3] === "Decl" ? "declaration" : "implementation";
101
+ const path = sectionFile(match, section);
102
+ const mappings =
103
+ location && path
104
+ ? bundle.mappings.filter(
105
+ (mapping) =>
106
+ mapping.path === path && mapping.line === Number(location[1]),
107
+ )
108
+ : [];
109
+ const mapping = mappings.length === 1 ? mappings[0] : undefined;
110
+ return {
111
+ origin: "vendor",
112
+ code: "PLC8001",
113
+ severity: "error",
114
+ message: item.text,
115
+ ...(mapping && { span: mapping.span }),
116
+ notes: [
117
+ ...notes,
118
+ ...(location && path
119
+ ? [
120
+ "Generated ST: " +
121
+ path +
122
+ ":" +
123
+ location[1] +
124
+ (location[2] ? `:${location[2]}` : ""),
125
+ ]
126
+ : []),
127
+ `CODESYS diagnostic: ${JSON.stringify(item)}`,
128
+ ],
129
+ };
130
+ });
131
+ }
132
+ notes.push(current.message);
133
+ if (current.cause === undefined) {
134
+ break;
135
+ }
136
+ current = current.cause;
137
+ if (!(current instanceof Error)) {
138
+ notes.push(String(current));
139
+ }
140
+ }
141
+ return [
142
+ {
143
+ origin: "vendor",
144
+ code: "PLC8001",
145
+ severity: "error",
146
+ message: cause instanceof Error ? cause.message : String(cause),
147
+ ...(notes.length > 1 && { notes: notes.slice(1) }),
148
+ },
149
+ ];
150
+ }