@tsplc/compiler 0.2.17 → 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
@@ -7,9 +7,16 @@
7
7
  */
8
8
  import { plugin } from "bun";
9
9
  import { readFileSync, realpathSync } from "node:fs";
10
- import type { CaptureRequest, CapturedGraph, CapturedValue, CapturedNode } from "./graph.ts";
10
+ import type {
11
+ CaptureRequest,
12
+ CapturedGraph,
13
+ CapturedValue,
14
+ CapturedNode,
15
+ } from "./graph.ts";
11
16
 
12
- const request: CaptureRequest = JSON.parse(readFileSync(process.argv[2]!, "utf8"));
17
+ const request: CaptureRequest = JSON.parse(
18
+ readFileSync(process.argv[2]!, "utf8"),
19
+ );
13
20
  // Bun loads modules by their real path; the compiler may name them through a symlink.
14
21
  const real = new Map(request.files.map((file) => [realpathSync(file), file]));
15
22
  const runtime = new Set(real.keys());
@@ -17,129 +24,178 @@ const exportName = "__tsplcCapture";
17
24
 
18
25
  /** Top-level bindings a module declares, so captured state can be traced back to its source. */
19
26
  const bindings = (source: string, names: CaptureRequest["bindings"][string]) =>
20
- `${source}\n;export const ${exportName} = { values: { ${names.values
21
- .map((name) => `${JSON.stringify(name)}: () => ${name}`)
22
- .join(", ")} }, classes: { ${names.classes
23
- .map((name) => `${JSON.stringify(name)}: ${name}`)
24
- .join(", ")} }, functions: { ${names.functions
25
- .map((name) => `${JSON.stringify(name)}: ${name}`)
26
- .join(", ")} } };\n`;
27
+ `${source}\n;export const ${exportName} = { values: { ${names.values
28
+ .map((name) => `${JSON.stringify(name)}: () => ${name}`)
29
+ .join(", ")} }, classes: { ${names.classes
30
+ .map((name) => `${JSON.stringify(name)}: ${name}`)
31
+ .join(", ")} }, functions: { ${names.functions
32
+ .map((name) => `${JSON.stringify(name)}: ${name}`)
33
+ .join(", ")} } };\n`;
27
34
 
28
35
  const servicePath = Symbol("tsplc service path");
29
36
  /** A service client: any property is a deeper procedure path, and its identity names that path. */
30
37
  const service = (path: readonly string[]): unknown =>
31
- new Proxy(function serviceProcedure() {}, {
32
- get: (_, key) => (key === servicePath ? path.join(".") : service([...path, String(key)])),
33
- apply: () => {
34
- throw new Error(`Setup code called the PLC service ${path.join(".")}.`);
35
- },
36
- });
38
+ new Proxy(function serviceProcedure() {}, {
39
+ get: (_, key) =>
40
+ key === servicePath ? path.join(".") : service([...path, String(key)]),
41
+ apply: () => {
42
+ throw new Error(`Setup code called the PLC service ${path.join(".")}.`);
43
+ },
44
+ });
37
45
 
38
46
  plugin({
39
- name: "tsplc-capture",
40
- setup(build) {
41
- build.onLoad(
42
- {
43
- filter: new RegExp(
44
- `^(${[...runtime].map((file) => file.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})$`,
45
- ),
46
- },
47
- ({ path }) => ({
48
- contents: bindings(readFileSync(path, "utf8"), request.bindings[real.get(path)!]!),
49
- loader: "ts",
50
- }),
51
- );
52
- // Setup runs before the first scan, so the clock reads 0 there.
53
- build.module("@tsplc/compiler/clock", () => ({
54
- contents: "export const now = () => 0;",
55
- loader: "js",
56
- }));
57
- // Records describe scans, so setup has none to make.
58
- build.module("@tsplc/compiler/telemetry", () => ({
59
- contents: `const unsupported = (name) => () => { throw new Error("telemetry." + name + " cannot run during PLC setup."); };
47
+ name: "tsplc-capture",
48
+ setup(build) {
49
+ build.onLoad(
50
+ {
51
+ filter: new RegExp(
52
+ `^(${[...runtime].map((file) => file.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})$`,
53
+ ),
54
+ },
55
+ ({ path }) => ({
56
+ contents: bindings(
57
+ readFileSync(path, "utf8"),
58
+ request.bindings[real.get(path)!]!,
59
+ ),
60
+ loader: "ts",
61
+ }),
62
+ );
63
+ // Setup runs before the first scan, so the clock reads 0 there.
64
+ build.module("@tsplc/compiler/clock", () => ({
65
+ contents: "export const now = () => 0;",
66
+ loader: "js",
67
+ }));
68
+ // Records describe scans, so setup has none to make.
69
+ build.module("@tsplc/compiler/telemetry", () => ({
70
+ contents: `const unsupported = (name) => () => { throw new Error("telemetry." + name + " cannot run during PLC setup."); };
60
71
  export const telemetry = Object.fromEntries(["capture", "info", "warn", "error", "captureException", "text"].map((name) => [name, unsupported(name)]));
61
72
  export const onTelemetry = () => () => {};`,
62
- loader: "js",
63
- }));
64
- build.module("@tsplc/compiler/async", () => ({
65
- contents: `export const createServiceClient = () => globalThis.__tsplcService([]);
73
+ loader: "js",
74
+ }));
75
+ build.module("@tsplc/compiler/async", () => ({
76
+ contents: `export const createServiceClient = () => globalThis.__tsplcService([]);
66
77
  const unsupported = (name) => () => { throw new Error(name + " cannot run during PLC setup."); };
67
78
  export const sleep = unsupported("sleep"), fetch = unsupported("fetch"), cancelAsync = unsupported("cancelAsync");`,
68
- loader: "js",
69
- }));
70
- },
79
+ loader: "js",
80
+ }));
81
+ },
71
82
  });
72
83
  (globalThis as { __tsplcService?: unknown }).__tsplcService = service;
73
84
 
74
- const modules = new Map<string, Record<string, Record<string, unknown>>>();
75
- for (const file of [request.entry, ...request.files.filter((file) => file !== request.entry)]) {
76
- const loaded = (await import(realpathSync(file))) as Record<string, unknown>;
77
- modules.set(file, loaded[exportName] as Record<string, Record<string, unknown>>);
85
+ /** The bindings each runtime module exports for capture, as `bindings` above adds them. */
86
+ interface Registry {
87
+ values: Record<string, () => unknown>;
88
+ classes: Record<string, unknown>;
89
+ functions: Record<string, unknown>;
90
+ }
91
+
92
+ const modules = new Map<string, Registry>();
93
+ for (const file of [
94
+ request.entry,
95
+ ...request.files.filter((file) => file !== request.entry),
96
+ ]) {
97
+ const loaded = (await import(realpathSync(file))) as Record<string, unknown>;
98
+ modules.set(file, loaded[exportName] as Registry);
78
99
  }
79
100
 
80
101
  const classes = new Map<unknown, { file: string; name: string }>();
81
102
  const functions = new Map<unknown, { file: string; name: string }>();
82
103
  for (const [file, registry] of modules) {
83
- for (const [name, value] of Object.entries(registry.classes!)) classes.set(value, { file, name });
84
- for (const [name, value] of Object.entries(registry.functions!))
85
- functions.set(value, { file, name });
104
+ for (const [name, value] of Object.entries(registry.classes)) {
105
+ classes.set(value, { file, name });
106
+ }
107
+ for (const [name, value] of Object.entries(registry.functions)) {
108
+ functions.set(value, { file, name });
109
+ }
86
110
  }
87
111
 
88
112
  const nodes: CapturedNode[] = [];
89
113
  const ids = new Map<object, number>();
90
114
  const capture = (value: unknown, where: string): CapturedValue => {
91
- if (value === undefined) return { kind: "undefined" };
92
- if (value === null) throw new Error(`${where}: null has no PLC value; use undefined.`);
93
- if (typeof value === "number" || typeof value === "boolean" || typeof value === "string")
94
- return { kind: typeof value, value } as CapturedValue;
95
- if (typeof value === "bigint") return { kind: "bigint", value: String(value) };
96
- if (typeof value !== "object" && typeof value !== "function")
97
- throw new Error(`${where}: a ${typeof value} has no PLC value.`);
98
- const known = ids.get(value);
99
- if (known !== undefined) return { kind: "node", id: known };
100
- const id = nodes.length;
101
- ids.set(value, id);
102
- nodes.push({ kind: "object", fields: {} });
103
- if (typeof value === "function") {
104
- const path = (value as { [servicePath]?: string })[servicePath];
105
- const named = functions.get(value) ?? classes.get(value);
106
- if (path !== undefined) nodes[id] = { kind: "service", path };
107
- else if (named) nodes[id] = { kind: "function", ...named };
108
- else
109
- throw new Error(
110
- `${where}: setup stored a function that is not a module-level function, so the PLC can't call it.`,
111
- );
112
- return { kind: "node", id };
113
- }
114
- if (Array.isArray(value)) {
115
- nodes[id] = {
116
- kind: "array",
117
- items: value.map((item, index) => capture(item, `${where}[${index}]`)),
118
- };
119
- return { kind: "node", id };
120
- }
121
- const prototype = Object.getPrototypeOf(value);
122
- const owner =
123
- prototype === Object.prototype || prototype === null ? undefined : prototype.constructor;
124
- const registered = owner && classes.get(owner);
125
- if (owner && !registered)
126
- throw new Error(`${where}: a ${owner.name} has no PLC layout; use a class from the program.`);
127
- const fields: Record<string, CapturedValue> = {};
128
- for (const [key, field] of Object.entries(value)) fields[key] = capture(field, `${where}.${key}`);
129
- nodes[id] = registered ? { kind: "instance", ...registered, fields } : { kind: "object", fields };
130
- return { kind: "node", id };
115
+ if (value === undefined) {
116
+ return { kind: "undefined" };
117
+ }
118
+ if (value === null) {
119
+ throw new Error(`${where}: null has no PLC value; use undefined.`);
120
+ }
121
+ if (
122
+ typeof value === "number" ||
123
+ typeof value === "boolean" ||
124
+ typeof value === "string"
125
+ ) {
126
+ return { kind: typeof value, value } as CapturedValue;
127
+ }
128
+ if (typeof value === "bigint") {
129
+ return { kind: "bigint", value: String(value) };
130
+ }
131
+ if (typeof value !== "object" && typeof value !== "function") {
132
+ throw new Error(`${where}: a ${typeof value} has no PLC value.`);
133
+ }
134
+ const known = ids.get(value);
135
+ if (known !== undefined) {
136
+ return { kind: "node", id: known };
137
+ }
138
+ const id = nodes.length;
139
+ ids.set(value, id);
140
+ nodes.push({ kind: "object", fields: {} });
141
+ if (typeof value === "function") {
142
+ const path = (value as { [servicePath]?: string })[servicePath];
143
+ const named = functions.get(value) ?? classes.get(value);
144
+ if (path !== undefined) {
145
+ nodes[id] = { kind: "service", path };
146
+ } else if (named) {
147
+ nodes[id] = { kind: "function", ...named };
148
+ } else {
149
+ throw new Error(
150
+ `${where}: setup stored a function that is not a module-level function, so the PLC can't call it.`,
151
+ );
152
+ }
153
+ return { kind: "node", id };
154
+ }
155
+ if (Array.isArray(value)) {
156
+ nodes[id] = {
157
+ kind: "array",
158
+ items: value.map((item, index) => capture(item, `${where}[${index}]`)),
159
+ };
160
+ return { kind: "node", id };
161
+ }
162
+ const prototype = Object.getPrototypeOf(value);
163
+ const owner =
164
+ prototype === Object.prototype || prototype === null
165
+ ? undefined
166
+ : prototype.constructor;
167
+ const registered = owner && classes.get(owner);
168
+ if (owner && !registered) {
169
+ throw new Error(
170
+ `${where}: a ${owner.name} has no PLC layout; use a class from the program.`,
171
+ );
172
+ }
173
+ const fields: Record<string, CapturedValue> = {};
174
+ for (const [key, field] of Object.entries(value)) {
175
+ fields[key] = capture(field, `${where}.${key}`);
176
+ }
177
+ nodes[id] = registered
178
+ ? { kind: "instance", ...registered, fields }
179
+ : { kind: "object", fields };
180
+ return { kind: "node", id };
131
181
  };
132
182
 
133
183
  const graph: CapturedGraph = { nodes, bindings: [] };
134
- for (const [file, registry] of modules)
135
- for (const [name, read] of Object.entries(registry.values!)) {
136
- let value: unknown;
137
- try {
138
- value = (read as () => unknown)();
139
- } catch {
140
- continue; // A binding the module never initialized.
141
- }
142
- if (typeof value === "function" && (functions.has(value) || classes.has(value))) continue;
143
- graph.bindings.push({ file, name, value: capture(value, name) });
144
- }
184
+ for (const [file, registry] of modules) {
185
+ for (const [name, read] of Object.entries(registry.values)) {
186
+ let value: unknown;
187
+ try {
188
+ value = read();
189
+ } catch {
190
+ continue; // A binding the module never initialized.
191
+ }
192
+ if (
193
+ typeof value === "function" &&
194
+ (functions.has(value) || classes.has(value))
195
+ ) {
196
+ continue;
197
+ }
198
+ graph.bindings.push({ file, name, value: capture(value, name) });
199
+ }
200
+ }
145
201
  process.stdout.write(JSON.stringify(graph));
@@ -0,0 +1,257 @@
1
+ import ts from "typescript";
2
+ import { canAssign, integerType, primitiveTypes } from "@tsplc/compiler/ir";
3
+ import { joined, mapped, type Mapped } from "../positions.ts";
4
+ import type { EntryImports } from "./imports.ts";
5
+ import type { Initializers } from "./initializers.ts";
6
+ import type { Layouts } from "./layouts.ts";
7
+ import type { Model } from "./model.ts";
8
+ import type { Storage } from "./storage.ts";
9
+ import type { Value } from "./values.ts";
10
+
11
+ /**
12
+ * Specialized values as dialect text, in a place of a declared type: literals as enum members,
13
+ * optionals as `{ has, value }`, records with every field, and numbers converted as IEC does.
14
+ */
15
+ export class DialectText {
16
+ constructor(
17
+ private readonly model: Model,
18
+ private readonly checker: ts.TypeChecker,
19
+ private readonly layouts: Layouts,
20
+ private readonly storage: Storage,
21
+ private readonly initializers: Initializers,
22
+ private readonly imports: EntryImports,
23
+ ) {}
24
+
25
+ /** Dialect text for a value, in a place of `expected` type when known. */
26
+ code(value: Value, expected: ts.Type | undefined): string | Mapped {
27
+ switch (value.kind) {
28
+ case "code":
29
+ if (
30
+ expected &&
31
+ value.declared &&
32
+ this.layouts.isOptionalRecord(value.declared) &&
33
+ !this.layouts.isOptionalRecord(expected)
34
+ ) {
35
+ return mapped`${value.text}.value`;
36
+ }
37
+ return value.text;
38
+ case "const": {
39
+ const literal = expected && this.layouts.literalEnum(expected);
40
+ if (
41
+ literal &&
42
+ (typeof value.value === "string" || value.value === undefined)
43
+ ) {
44
+ return this.layouts.member(literal, value.value);
45
+ }
46
+ if (
47
+ expected &&
48
+ this.layouts.isOptionalRecord(expected) &&
49
+ value.value === undefined
50
+ ) {
51
+ return `defaultValue<${this.layouts.text(expected)}>()`;
52
+ }
53
+ if (
54
+ expected &&
55
+ this.layouts.enumDeclaration(expected) &&
56
+ typeof value.value === "number"
57
+ ) {
58
+ const member = this.layouts.enumMemberName(expected, value.value);
59
+ if (member) {
60
+ return `${this.layouts.text(expected)}.${member}`;
61
+ }
62
+ }
63
+ if (value.value === undefined) {
64
+ throw new Error("undefined has no PLC value here.");
65
+ }
66
+ if (typeof value.value === "string") {
67
+ return JSON.stringify(value.value);
68
+ }
69
+ if (typeof value.value === "bigint") {
70
+ return `${value.value}n`;
71
+ }
72
+ return String(value.value);
73
+ }
74
+ case "static": {
75
+ const node = value.node;
76
+ if (this.storage.storedNode(node)) {
77
+ return this.storage.pathText(node);
78
+ }
79
+ if (node.type) {
80
+ return this.initializers.valueText(
81
+ { kind: "node", id: node.id },
82
+ expected ?? node.type,
83
+ );
84
+ }
85
+ throw new Error("This object has no PLC value.");
86
+ }
87
+ case "virtual": {
88
+ if (value.fields) {
89
+ const type = expected && this.checker.getNonNullableType(expected);
90
+ if (!type) {
91
+ throw new Error("A record literal needs a declared type.");
92
+ }
93
+ return this.recordLiteral(value.fields, type);
94
+ }
95
+ if (value.items) {
96
+ const element = expected && this.model.elementType(expected);
97
+ return mapped`[${joined(
98
+ value.items.map((item) => this.code(item, element)),
99
+ ", ",
100
+ )}]`;
101
+ }
102
+ throw new Error("Empty value.");
103
+ }
104
+ case "function":
105
+ throw new Error("A function has no PLC value; call it.");
106
+ }
107
+ }
108
+
109
+ /** A record literal of `type`, every field written; a tagged union fills the other variants' fields. */
110
+ private recordLiteral(fields: Map<string, Value>, type: ts.Type): Mapped {
111
+ const tagged = this.layouts.tagged(type);
112
+ const fieldTypes: [string, ts.Type][] = tagged
113
+ ? this.layouts
114
+ .taggedFields(tagged)
115
+ .map((name) => [
116
+ name,
117
+ name === tagged.tag
118
+ ? this.layouts.tagType(type, tagged)
119
+ : this.layouts.taggedFieldType(type, tagged, name),
120
+ ])
121
+ : this.checker
122
+ .getPropertiesOfType(type)
123
+ .map((property) => [
124
+ property.name,
125
+ this.checker.getTypeOfSymbol(property),
126
+ ]);
127
+ return mapped`{ ${joined(
128
+ fieldTypes.map(([name, fieldType]) => {
129
+ const value = fields.get(name);
130
+ if (!value) {
131
+ return `${name}: ${this.initializers.defaultOf(fieldType)}`;
132
+ }
133
+ const property = this.checker.getPropertyOfType(type, name);
134
+ return mapped`${name}: ${this.assignmentText(value, fieldType, this.layouts.iecName(property?.valueDeclaration))}`;
135
+ }),
136
+ ", ",
137
+ )} }`;
138
+ }
139
+
140
+ /** The text stored into a place of `declared` type, wrapping an optional's value. */
141
+ assignmentText(
142
+ value: Value,
143
+ declared: ts.Type | undefined,
144
+ iec?: string,
145
+ ): string | Mapped {
146
+ const target =
147
+ iec ??
148
+ (declared && declared.flags & ts.TypeFlags.Number ? "DINT" : undefined);
149
+ if (
150
+ target &&
151
+ value.kind === "code" &&
152
+ needsConversion(value.iec ?? "DINT", target)
153
+ ) {
154
+ // A TypeScript number holds any of these; in the PLC a value converts as an IEC assignment does.
155
+ this.imports.conversions.add("wrap");
156
+ return mapped`wrap<${target}>(${this.code(value, undefined)})`;
157
+ }
158
+ if (declared && this.layouts.isOptionalRecord(declared)) {
159
+ if (value.kind === "const" && value.value === undefined) {
160
+ return `defaultValue<${this.layouts.text(declared)}>()`;
161
+ }
162
+ if (
163
+ value.kind === "code" &&
164
+ value.declared &&
165
+ this.layouts.isOptionalRecord(value.declared)
166
+ ) {
167
+ return value.text;
168
+ }
169
+ return this.wrapDefined(
170
+ this.code(value, this.checker.getNonNullableType(declared)),
171
+ declared,
172
+ );
173
+ }
174
+ return this.code(value, declared);
175
+ }
176
+
177
+ wrapDefined(
178
+ text: string | Mapped,
179
+ declared: ts.Type | undefined,
180
+ ): string | Mapped {
181
+ return declared && this.layouts.isOptionalRecord(declared)
182
+ ? mapped`{ has: true, value: ${text} }`
183
+ : text;
184
+ }
185
+
186
+ isUndefinedText(
187
+ text: string | Mapped,
188
+ declared: ts.Type | undefined,
189
+ ): Mapped {
190
+ if (declared && this.layouts.isOptionalRecord(declared)) {
191
+ return mapped`!${text}.has`;
192
+ }
193
+ const literal = declared && this.layouts.literalEnum(declared);
194
+ if (literal) {
195
+ return mapped`${text} === ${this.layouts.member(literal, undefined)}`;
196
+ }
197
+ throw new Error("Only optional values can be undefined.");
198
+ }
199
+
200
+ /** A boolean condition, including JavaScript truthiness of optionals and enums. */
201
+ condition(value: Value, at: ts.Node): string | Mapped {
202
+ if (value.kind === "code" && value.declared) {
203
+ const declared = value.declared;
204
+ if (
205
+ this.layouts.isOptionalRecord(declared) &&
206
+ !ts.isPrefixUnaryExpression(at)
207
+ ) {
208
+ const type = this.checker.getTypeAtLocation(at);
209
+ if (!(type.flags & ts.TypeFlags.BooleanLike)) {
210
+ return mapped`${value.text}.has`;
211
+ }
212
+ }
213
+ const literal = this.layouts.literalEnum(declared);
214
+ if (literal?.optional) {
215
+ return mapped`${value.text} !== ${this.layouts.member(literal, undefined)}`;
216
+ }
217
+ }
218
+ return this.code(value, undefined);
219
+ }
220
+
221
+ /**
222
+ * Both sides of a comparison as text. Integers of different signedness, which TypeScript
223
+ * compares as numbers, both widen to LINT so the PLC compares them exactly.
224
+ */
225
+ comparable(
226
+ left: Value,
227
+ right: Value,
228
+ declared: ts.Type | undefined,
229
+ ): [string | Mapped, string | Mapped] {
230
+ const leftText = this.code(left, declared);
231
+ const rightText = this.code(right, declared);
232
+ if (left.kind !== "code" || right.kind !== "code") {
233
+ return [leftText, rightText];
234
+ }
235
+ const from = left.iec ?? "DINT";
236
+ const to = right.iec ?? "DINT";
237
+ if (!needsConversion(from, to) || !needsConversion(to, from)) {
238
+ return [leftText, rightText];
239
+ }
240
+ this.imports.conversions.add("wrap");
241
+ return [mapped`wrap<LINT>(${leftText})`, mapped`wrap<LINT>(${rightText})`];
242
+ }
243
+ }
244
+
245
+ /** IEC integer and bit-string types by name. */
246
+ const integerTypes = new Map(
247
+ primitiveTypes.filter(integerType).map((type) => [type.id, type]),
248
+ );
249
+
250
+ /** Whether IEC needs an explicit conversion from one integer type to another; widening is implicit. */
251
+ const needsConversion = (from: string, to: string): boolean => {
252
+ const source = integerTypes.get(from);
253
+ const target = integerTypes.get(to);
254
+ return (
255
+ source !== undefined && target !== undefined && !canAssign(source, target)
256
+ );
257
+ };