@tsplc/tmp-compiler 0.0.0-stage → 0.6.3
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.
- package/LICENSE +21 -0
- package/README.md +41 -2
- package/dist/cli.js +2325 -0
- package/dist/cli.js.map +26 -0
- package/dist/clock.js +11 -0
- package/dist/clock.js.map +11 -0
- package/dist/codesys.js +6563 -0
- package/dist/codesys.js.map +51 -0
- package/dist/collections.js +399 -0
- package/dist/collections.js.map +10 -0
- package/dist/index.js +16198 -0
- package/dist/index.js.map +62 -0
- package/dist/ir.js +3948 -0
- package/dist/ir.js.map +35 -0
- package/dist/retain.js +10 -0
- package/dist/retain.js.map +10 -0
- package/dist/signals.js +115 -0
- package/dist/signals.js.map +10 -0
- package/dist/telemetry.js +121 -0
- package/dist/telemetry.js.map +12 -0
- package/package.json +122 -4
- package/src/codesys/config.ts +50 -0
- package/src/codesys/debug.ts +655 -0
- package/src/codesys/emit.ts +185 -0
- package/src/codesys/endpoints.ts +111 -0
- package/src/codesys/engineering.ts +96 -0
- package/src/codesys/explain/expressions.ts +445 -0
- package/src/codesys/explain/flags.ts +134 -0
- package/src/codesys/explain/parameters.ts +53 -0
- package/src/codesys/explain/rows.ts +182 -0
- package/src/codesys/explain/tables.ts +79 -0
- package/src/codesys/explain/tasks.ts +68 -0
- package/src/codesys/explain/writes.ts +497 -0
- package/src/codesys/explain.ts +149 -0
- package/src/codesys/expressions.ts +100 -0
- package/src/codesys/global-lists.ts +284 -0
- package/src/codesys/global-names.ts +66 -0
- package/src/codesys/http.ts +1090 -0
- package/src/codesys/index.ts +13 -0
- package/src/codesys/instrumentation.ts +574 -0
- package/src/codesys/io-paths.ts +149 -0
- package/src/codesys/loops.ts +101 -0
- package/src/codesys/manifest.ts +684 -0
- package/src/codesys/names.ts +58 -0
- package/src/codesys/numeric.ts +516 -0
- package/src/codesys/plan.ts +688 -0
- package/src/codesys/programs.ts +138 -0
- package/src/codesys/publication.ts +99 -0
- package/src/codesys/required.ts +8 -0
- package/src/codesys/routines.ts +247 -0
- package/src/codesys/scan-clock.ts +103 -0
- package/src/codesys/scheduling.ts +96 -0
- package/src/codesys/service-channels.ts +24 -0
- package/src/codesys/sources.ts +118 -0
- package/src/codesys/st-files.ts +219 -0
- package/src/codesys/statements.ts +409 -0
- package/src/codesys/storage.ts +150 -0
- package/src/codesys/symbols.ts +240 -0
- package/src/codesys/task-access.ts +186 -0
- package/src/codesys/telemetry-settings.ts +19 -0
- package/src/codesys/telemetry.ts +852 -0
- package/src/codesys/types.ts +310 -0
- package/src/codesys/vendor.ts +113 -0
- package/src/frontend/analyzer.ts +779 -0
- package/src/frontend/async.ts +530 -0
- package/src/frontend/blocks.ts +578 -0
- package/src/frontend/configuration.ts +83 -0
- package/src/frontend/const-enums.ts +196 -0
- package/src/frontend/const-functions.ts +204 -0
- package/src/frontend/control-flow.ts +787 -0
- package/src/frontend/cooperative.ts +114 -0
- package/src/frontend/coroutines.ts +1344 -0
- package/src/frontend/dialect-names.ts +104 -0
- package/src/frontend/elaborate/array-searches.ts +224 -0
- package/src/frontend/elaborate/assignments.ts +343 -0
- package/src/frontend/elaborate/calls.ts +1342 -0
- package/src/frontend/elaborate/capture-protocol.ts +237 -0
- package/src/frontend/elaborate/capture.ts +388 -0
- package/src/frontend/elaborate/declarations.ts +124 -0
- package/src/frontend/elaborate/dialect.ts +473 -0
- package/src/frontend/elaborate/expressions.ts +2177 -0
- package/src/frontend/elaborate/filtered-arrays.ts +643 -0
- package/src/frontend/elaborate/frame.ts +145 -0
- package/src/frontend/elaborate/generics.ts +123 -0
- package/src/frontend/elaborate/graph.ts +141 -0
- package/src/frontend/elaborate/imports.ts +105 -0
- package/src/frontend/elaborate/index.ts +851 -0
- package/src/frontend/elaborate/initializers.ts +235 -0
- package/src/frontend/elaborate/iterators.ts +1541 -0
- package/src/frontend/elaborate/layouts.ts +1025 -0
- package/src/frontend/elaborate/model.ts +478 -0
- package/src/frontend/elaborate/names.ts +134 -0
- package/src/frontend/elaborate/reduce.ts +900 -0
- package/src/frontend/elaborate/references.ts +727 -0
- package/src/frontend/elaborate/retention.ts +284 -0
- package/src/frontend/elaborate/specialize.ts +1137 -0
- package/src/frontend/elaborate/statements.ts +1220 -0
- package/src/frontend/elaborate/storage.ts +836 -0
- package/src/frontend/elaborate/time-constructors.ts +34 -0
- package/src/frontend/elaborate/values.ts +200 -0
- package/src/frontend/elaborate/writes.ts +415 -0
- package/src/frontend/expressions.ts +1382 -0
- package/src/frontend/generated-names.ts +95 -0
- package/src/frontend/intrinsics.ts +382 -0
- package/src/frontend/lowering-key.ts +23 -0
- package/src/frontend/module-graph.ts +156 -0
- package/src/frontend/positions.ts +359 -0
- package/src/frontend/promise-chains.ts +872 -0
- package/src/frontend/promises.ts +419 -0
- package/src/frontend/routines.ts +239 -0
- package/src/frontend/sdk.ts +187 -0
- package/src/frontend/services.ts +612 -0
- package/src/frontend/statements.ts +871 -0
- package/src/frontend/tasks.ts +526 -0
- package/src/frontend/telemetry.ts +174 -0
- package/src/frontend/types.ts +1073 -0
- package/src/frontend/typescript.ts +659 -0
- package/src/index.ts +9 -0
- package/src/ir/aggregates.ts +291 -0
- package/src/ir/allocation.ts +96 -0
- package/src/ir/conditions.ts +855 -0
- package/src/ir/core-model.ts +289 -0
- package/src/ir/declarations.ts +281 -0
- package/src/ir/diagnostics.ts +68 -0
- package/src/ir/domains.ts +151 -0
- package/src/ir/fold.ts +279 -0
- package/src/ir/identity.ts +19 -0
- package/src/ir/index.ts +137 -0
- package/src/ir/job-errors.ts +69 -0
- package/src/ir/layouts.ts +211 -0
- package/src/ir/link.ts +302 -0
- package/src/ir/model.ts +394 -0
- package/src/ir/normalization-error.ts +10 -0
- package/src/ir/normalize.ts +52 -0
- package/src/ir/numeric.ts +163 -0
- package/src/ir/operands.ts +160 -0
- package/src/ir/ranges.ts +420 -0
- package/src/ir/routine.ts +1116 -0
- package/src/ir/scalars.ts +453 -0
- package/src/ir/share.ts +790 -0
- package/src/ir/short-circuit.ts +140 -0
- package/src/ir/tables.ts +111 -0
- package/src/ir/temporaries.ts +138 -0
- package/src/ir/types.ts +151 -0
- package/src/project/artifacts.ts +424 -0
- package/src/project/cli.ts +211 -0
- package/src/project/debugger.ts +111 -0
- package/src/project/deployments.ts +387 -0
- package/src/project/flags.ts +14 -0
- package/src/project/git.ts +35 -0
- package/src/project/plant.ts +629 -0
- package/src/project/project-commands.ts +507 -0
- package/src/project/project.ts +559 -0
- package/src/project/release.ts +152 -0
- package/src/project/server-check.ts +54 -0
- package/src/project/server.ts +165 -0
- package/src/project/terminal.ts +45 -0
- package/src/runtime/async.ts +207 -0
- package/src/runtime/launch.ts +59 -0
- package/src/runtime/main.ts +59 -0
- package/src/runtime/missing-file.ts +3 -0
- package/src/runtime/process.ts +177 -0
- package/src/runtime/program.ts +109 -0
- package/src/runtime/retain.ts +108 -0
- package/src/runtime/runtime.ts +324 -0
- package/src/runtime/settings.ts +27 -0
- package/src/runtime/storage.ts +456 -0
- package/src/runtime/symbols.ts +97 -0
- package/src/runtime/telemetry.ts +154 -0
- package/src/runtime/transport.ts +168 -0
- package/stdlib/clock.ts +8 -0
- package/stdlib/collections.ts +534 -0
- package/stdlib/plc-time.ts +2 -0
- package/stdlib/retain.ts +4 -0
- package/stdlib/signals.ts +142 -0
- package/stdlib/telemetry.ts +89 -0
- package/types/async.d.ts +87 -0
- package/types/clock.d.ts +8 -0
- package/types/config.d.ts +2 -0
- package/types/data-types.d.ts +31 -0
- package/types/dialect.d.ts +49 -0
- package/types/globals.d.ts +10 -0
- package/types/index.d.ts +212 -0
- package/types/retain.d.ts +12 -0
- package/types/telemetry.d.ts +47 -0
|
@@ -0,0 +1,612 @@
|
|
|
1
|
+
import { dirname, join } from "node:path";
|
|
2
|
+
import { type Diagnostic, error } from "@tsplc/compiler/ir";
|
|
3
|
+
import type { ServerConfig } from "@tsplc/config";
|
|
4
|
+
import {
|
|
5
|
+
isIntegerType,
|
|
6
|
+
plcProcedureKind,
|
|
7
|
+
type ServiceContract,
|
|
8
|
+
serviceContract,
|
|
9
|
+
type WireField,
|
|
10
|
+
type WireScalar,
|
|
11
|
+
wireLayout,
|
|
12
|
+
wireRecord,
|
|
13
|
+
} from "@tsplc/server/contract";
|
|
14
|
+
import { servicePath } from "@tsplc/server/wire";
|
|
15
|
+
import ts from "typescript";
|
|
16
|
+
import { importSpecifier, plcSources, runtimeImport } from "./module-graph";
|
|
17
|
+
import {
|
|
18
|
+
type Edit,
|
|
19
|
+
edited,
|
|
20
|
+
from,
|
|
21
|
+
type Mapped,
|
|
22
|
+
mapped,
|
|
23
|
+
type Positions,
|
|
24
|
+
} from "./positions";
|
|
25
|
+
import { namesSdk, sdkModules, symbolAt } from "./sdk";
|
|
26
|
+
import type { ServiceRecord } from "./types";
|
|
27
|
+
|
|
28
|
+
/** The server section's transport; each client's type argument names its router. */
|
|
29
|
+
export type ServiceOptions = Pick<ServerConfig, "transport" | "baseUrlEnv">;
|
|
30
|
+
|
|
31
|
+
/** Why a procedure's input or output cannot cross the wire to the PLC; the message names the field. */
|
|
32
|
+
class WireLayoutError extends Error {}
|
|
33
|
+
|
|
34
|
+
/** A server contract check, whose every Error describes a schema the PLC cannot exchange. */
|
|
35
|
+
const contractCheck = <T>(check: () => T): T => {
|
|
36
|
+
try {
|
|
37
|
+
return check();
|
|
38
|
+
} catch (cause) {
|
|
39
|
+
throw cause instanceof Error ? new WireLayoutError(cause.message) : cause;
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
/** What `read` returns, or the WireLayoutError it rejected the schema with. */
|
|
44
|
+
const wireLayoutOf = <T>(read: () => T): T | WireLayoutError => {
|
|
45
|
+
try {
|
|
46
|
+
return read();
|
|
47
|
+
} catch (cause) {
|
|
48
|
+
if (cause instanceof WireLayoutError) {
|
|
49
|
+
return cause;
|
|
50
|
+
}
|
|
51
|
+
throw cause;
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
/** The longest server base URL the PLC holds. */
|
|
56
|
+
const baseUrlCapacity = 512;
|
|
57
|
+
|
|
58
|
+
/** A procedure record read from its type, with the PLC enum each enum field names. */
|
|
59
|
+
interface RecordLayout {
|
|
60
|
+
fields: Record<string, WireField>;
|
|
61
|
+
enums: Record<string, ts.EnumDeclaration>;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const property = (checker: ts.TypeChecker, type: ts.Type, name: string) => {
|
|
65
|
+
const symbol = type.getProperty(name);
|
|
66
|
+
return symbol && checker.getTypeOfSymbol(symbol);
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
/** An `iec.*` schema's layout, which its type carries as an optional phantom property. */
|
|
70
|
+
const layoutNumber = (
|
|
71
|
+
checker: ts.TypeChecker,
|
|
72
|
+
type: ts.Type,
|
|
73
|
+
name: string,
|
|
74
|
+
label: string,
|
|
75
|
+
) => {
|
|
76
|
+
const brand = property(checker, type, wireLayout);
|
|
77
|
+
const value =
|
|
78
|
+
brand && property(checker, checker.getNonNullableType(brand), name);
|
|
79
|
+
if (!value) {
|
|
80
|
+
return undefined;
|
|
81
|
+
}
|
|
82
|
+
if (!value.isNumberLiteral()) {
|
|
83
|
+
throw new WireLayoutError(`${label}: ${name} must be a literal number.`);
|
|
84
|
+
}
|
|
85
|
+
return value.value;
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
const scalarLayout = (
|
|
89
|
+
checker: ts.TypeChecker,
|
|
90
|
+
type: ts.Type,
|
|
91
|
+
label: string,
|
|
92
|
+
): { field: WireScalar; enumeration?: ts.EnumDeclaration } => {
|
|
93
|
+
if (type.flags & ts.TypeFlags.Boolean) {
|
|
94
|
+
return { field: { kind: "boolean" } };
|
|
95
|
+
}
|
|
96
|
+
// An enum type is the union of its member literals.
|
|
97
|
+
const first = type.isUnion() ? type.types[0] : type;
|
|
98
|
+
const member = first?.symbol?.valueDeclaration;
|
|
99
|
+
if (
|
|
100
|
+
first &&
|
|
101
|
+
first.flags & ts.TypeFlags.EnumLiteral &&
|
|
102
|
+
member &&
|
|
103
|
+
ts.isEnumMember(member)
|
|
104
|
+
) {
|
|
105
|
+
const members: Record<string, number> = {};
|
|
106
|
+
for (const item of member.parent.members) {
|
|
107
|
+
const value = checker.getConstantValue(item);
|
|
108
|
+
if (typeof value !== "number") {
|
|
109
|
+
throw new WireLayoutError(
|
|
110
|
+
`${label}: PLC enums require numeric members.`,
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
members[item.name.getText()] = value;
|
|
114
|
+
}
|
|
115
|
+
return { field: { kind: "enum", members }, enumeration: member.parent };
|
|
116
|
+
}
|
|
117
|
+
const capacity = layoutNumber(checker, type, "capacity", label);
|
|
118
|
+
if (capacity !== undefined) {
|
|
119
|
+
return { field: { kind: "string", capacity } };
|
|
120
|
+
}
|
|
121
|
+
const brand = property(checker, type, wireLayout);
|
|
122
|
+
const iec =
|
|
123
|
+
brand && property(checker, checker.getNonNullableType(brand), "iec");
|
|
124
|
+
if (iec?.isStringLiteral() && isIntegerType(iec.value)) {
|
|
125
|
+
const minimum = layoutNumber(checker, type, "minimum", label);
|
|
126
|
+
const maximum = layoutNumber(checker, type, "maximum", label);
|
|
127
|
+
if (minimum !== undefined && maximum !== undefined) {
|
|
128
|
+
return { field: { kind: "integer", iec: iec.value, minimum, maximum } };
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
throw new WireLayoutError(
|
|
132
|
+
`${label}: use z.boolean(), z.enum() of a numeric enum, iec.STRING(), or an integer such as iec.INT().`,
|
|
133
|
+
);
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
const recordLayout = (
|
|
137
|
+
checker: ts.TypeChecker,
|
|
138
|
+
type: ts.Type,
|
|
139
|
+
label: string,
|
|
140
|
+
output: boolean,
|
|
141
|
+
): RecordLayout => {
|
|
142
|
+
const fields: Record<string, WireField> = {};
|
|
143
|
+
const enums: Record<string, ts.EnumDeclaration> = {};
|
|
144
|
+
// A procedure without `.input()` takes `void`.
|
|
145
|
+
if (!(type.flags & ts.TypeFlags.Void)) {
|
|
146
|
+
if (
|
|
147
|
+
!(type.flags & ts.TypeFlags.Object) ||
|
|
148
|
+
type.getStringIndexType() ||
|
|
149
|
+
type.getNumberIndexType() ||
|
|
150
|
+
type.getCallSignatures().length
|
|
151
|
+
) {
|
|
152
|
+
throw new WireLayoutError(
|
|
153
|
+
`${label}: PLC procedures exchange one closed z.strictObject() record.`,
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
for (const field of type.getProperties()) {
|
|
157
|
+
const key = `${label}.${field.name}`;
|
|
158
|
+
if (field.flags & ts.SymbolFlags.Optional) {
|
|
159
|
+
throw new WireLayoutError(
|
|
160
|
+
`${key}: optional wire fields are unsupported.`,
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
const value = checker.getTypeOfSymbol(field);
|
|
164
|
+
const length = layoutNumber(checker, value, "length", key);
|
|
165
|
+
const element =
|
|
166
|
+
length === undefined ? undefined : value.getNumberIndexType();
|
|
167
|
+
const scalar = scalarLayout(checker, element ?? value, key);
|
|
168
|
+
fields[field.name] =
|
|
169
|
+
length === undefined
|
|
170
|
+
? scalar.field
|
|
171
|
+
: { kind: "array", length, element: scalar.field };
|
|
172
|
+
if (scalar.enumeration) {
|
|
173
|
+
enums[field.name] = scalar.enumeration;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return {
|
|
178
|
+
fields: contractCheck(() => wireRecord(fields, label, output)).fields,
|
|
179
|
+
enums,
|
|
180
|
+
};
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
/** Identifies a record by layout, so every name for it lowers to one PLC struct. */
|
|
184
|
+
const recordKey = (layout: RecordLayout) =>
|
|
185
|
+
JSON.stringify([
|
|
186
|
+
layout.fields,
|
|
187
|
+
Object.entries(layout.enums)
|
|
188
|
+
.map(([field, value]) => [
|
|
189
|
+
field,
|
|
190
|
+
value.getSourceFile().fileName,
|
|
191
|
+
value.name.text,
|
|
192
|
+
])
|
|
193
|
+
.sort(),
|
|
194
|
+
]);
|
|
195
|
+
|
|
196
|
+
const procedureAt = (
|
|
197
|
+
checker: ts.TypeChecker,
|
|
198
|
+
router: ts.Type,
|
|
199
|
+
path: readonly string[],
|
|
200
|
+
) => {
|
|
201
|
+
const type = ["_def", "record", ...path].reduce<ts.Type | undefined>(
|
|
202
|
+
(parent, name) => parent && property(checker, parent, name),
|
|
203
|
+
router,
|
|
204
|
+
);
|
|
205
|
+
const definition = type && property(checker, type, "_def");
|
|
206
|
+
if (!definition || !property(checker, definition, "procedure")) {
|
|
207
|
+
return undefined;
|
|
208
|
+
}
|
|
209
|
+
const kind = property(checker, definition, "type");
|
|
210
|
+
const types = property(checker, definition, "$types");
|
|
211
|
+
const input = types && property(checker, types, "input");
|
|
212
|
+
const output = types && property(checker, types, "output");
|
|
213
|
+
if (!kind?.isStringLiteral() || !input || !output) {
|
|
214
|
+
return undefined;
|
|
215
|
+
}
|
|
216
|
+
return { kind: kind.value, input, output };
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
// Unlike the backend's pascalCase, this keeps underscores: `line_state.get` names `Line_stateGet`.
|
|
220
|
+
const pascalServicePath = (path: string) =>
|
|
221
|
+
path
|
|
222
|
+
.split(".")
|
|
223
|
+
.map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1))
|
|
224
|
+
.join("");
|
|
225
|
+
|
|
226
|
+
/** The export of the generated service module that calls the procedure at `path`. */
|
|
227
|
+
const serviceExportName = (path: string) =>
|
|
228
|
+
`tsplcService_${path.replaceAll(".", "_")}`;
|
|
229
|
+
|
|
230
|
+
interface ServiceCall {
|
|
231
|
+
contract: ServiceContract;
|
|
232
|
+
input: string;
|
|
233
|
+
/** Null when the procedure answers nothing. */
|
|
234
|
+
output: string | null;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** tRPC infers `void` for a procedure without `.output()` or with `z.void()`, and `undefined` with `z.undefined()`. */
|
|
238
|
+
const answersNothing = (type: ts.Type) =>
|
|
239
|
+
Boolean(type.flags & (ts.TypeFlags.Void | ts.TypeFlags.Undefined));
|
|
240
|
+
|
|
241
|
+
/** A called procedure's contract with the record names it exchanges, or why the PLC cannot call it. */
|
|
242
|
+
const serviceCall = (
|
|
243
|
+
checker: ts.TypeChecker,
|
|
244
|
+
path: string,
|
|
245
|
+
procedure: NonNullable<ReturnType<typeof procedureAt>>,
|
|
246
|
+
record: (layout: RecordLayout, name: string) => string,
|
|
247
|
+
): ServiceCall | WireLayoutError =>
|
|
248
|
+
wireLayoutOf(() => {
|
|
249
|
+
const kind = contractCheck(() => plcProcedureKind(path, procedure.kind));
|
|
250
|
+
const input = recordLayout(
|
|
251
|
+
checker,
|
|
252
|
+
procedure.input,
|
|
253
|
+
`${path}.input`,
|
|
254
|
+
false,
|
|
255
|
+
);
|
|
256
|
+
const output = answersNothing(procedure.output)
|
|
257
|
+
? null
|
|
258
|
+
: recordLayout(checker, procedure.output, `${path}.output`, true);
|
|
259
|
+
const contract = contractCheck(() =>
|
|
260
|
+
serviceContract(
|
|
261
|
+
path,
|
|
262
|
+
kind,
|
|
263
|
+
{ fields: input.fields },
|
|
264
|
+
output && { fields: output.fields },
|
|
265
|
+
),
|
|
266
|
+
);
|
|
267
|
+
return {
|
|
268
|
+
contract,
|
|
269
|
+
input: record(input, `${pascalServicePath(path)}Input`),
|
|
270
|
+
output: output && record(output, `${pascalServicePath(path)}Output`),
|
|
271
|
+
};
|
|
272
|
+
});
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* Replaces each `createServiceClient<Router>()` call with an in-memory module of the called
|
|
276
|
+
* procedures, read from the router's type: the server never runs and no file is written.
|
|
277
|
+
*/
|
|
278
|
+
export const lowerServices = (
|
|
279
|
+
program: ts.Program,
|
|
280
|
+
sdk: string,
|
|
281
|
+
positions: Positions,
|
|
282
|
+
options: ServiceOptions | undefined,
|
|
283
|
+
) => {
|
|
284
|
+
const sources = new Map<string, Mapped>();
|
|
285
|
+
const diagnostics: Diagnostic[] = [];
|
|
286
|
+
const records = new Map<string, { name: string; layout: RecordLayout }>();
|
|
287
|
+
const calls = new Map<string, ServiceCall>();
|
|
288
|
+
const checker = program.getTypeChecker();
|
|
289
|
+
const fail = (node: ts.Node, code: string, message: string) =>
|
|
290
|
+
diagnostics.push(error(code, message, positions.node(node)));
|
|
291
|
+
const record = (layout: RecordLayout, name: string) => {
|
|
292
|
+
const key = recordKey(layout);
|
|
293
|
+
const existing = records.get(key);
|
|
294
|
+
if (existing) {
|
|
295
|
+
return existing.name;
|
|
296
|
+
}
|
|
297
|
+
records.set(key, { name, layout });
|
|
298
|
+
return name;
|
|
299
|
+
};
|
|
300
|
+
|
|
301
|
+
const clients = new Map<ts.Symbol, ts.Type>();
|
|
302
|
+
/** The generated service module, and the first client's creation it stands for. */
|
|
303
|
+
let module: { file: string; client: ts.CallExpression } | undefined;
|
|
304
|
+
const sourceFiles = plcSources(program);
|
|
305
|
+
for (const source of sourceFiles) {
|
|
306
|
+
for (const statement of source.statements) {
|
|
307
|
+
if (!ts.isVariableStatement(statement)) {
|
|
308
|
+
continue;
|
|
309
|
+
}
|
|
310
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
311
|
+
const call = declaration.initializer;
|
|
312
|
+
if (
|
|
313
|
+
!call ||
|
|
314
|
+
!ts.isCallExpression(call) ||
|
|
315
|
+
!namesSdk(checker, sdk, call.expression, "createServiceClient")
|
|
316
|
+
) {
|
|
317
|
+
continue;
|
|
318
|
+
}
|
|
319
|
+
const router = call.typeArguments?.[0];
|
|
320
|
+
const client = symbolAt(checker, declaration.name);
|
|
321
|
+
if (
|
|
322
|
+
!router ||
|
|
323
|
+
!client ||
|
|
324
|
+
!(statement.declarationList.flags & ts.NodeFlags.Const)
|
|
325
|
+
) {
|
|
326
|
+
fail(
|
|
327
|
+
declaration,
|
|
328
|
+
"PLC1013",
|
|
329
|
+
"Create a service client as a module constant: const services = createServiceClient<AppRouter>().",
|
|
330
|
+
);
|
|
331
|
+
} else if (!options) {
|
|
332
|
+
fail(
|
|
333
|
+
call,
|
|
334
|
+
"PLC1013",
|
|
335
|
+
"Configure server in tsplc.config.ts to call the server.",
|
|
336
|
+
);
|
|
337
|
+
} else if (options.transport === "http" && !options.baseUrlEnv) {
|
|
338
|
+
fail(
|
|
339
|
+
call,
|
|
340
|
+
"PLC1013",
|
|
341
|
+
"HTTP service transport requires server.baseUrlEnv.",
|
|
342
|
+
);
|
|
343
|
+
} else {
|
|
344
|
+
clients.set(client, checker.getTypeFromTypeNode(router));
|
|
345
|
+
module ??= {
|
|
346
|
+
file: join(dirname(source.fileName), ".tsplc-services.ts"),
|
|
347
|
+
client: call,
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
for (const source of sourceFiles) {
|
|
355
|
+
const edits: Edit[] = [];
|
|
356
|
+
const imports = new Map<string, string>();
|
|
357
|
+
const visit = (node: ts.Node): void => {
|
|
358
|
+
if (
|
|
359
|
+
ts.isImportDeclaration(node) &&
|
|
360
|
+
ts.isStringLiteral(node.moduleSpecifier)
|
|
361
|
+
) {
|
|
362
|
+
const clause = node.importClause;
|
|
363
|
+
const bindings = clause?.namedBindings;
|
|
364
|
+
const runtime = runtimeImport(node, checker);
|
|
365
|
+
if (runtime && clause && bindings && ts.isNamedImports(bindings)) {
|
|
366
|
+
const elements = bindings.elements.filter((element) => {
|
|
367
|
+
const imported = symbolAt(checker, element.name);
|
|
368
|
+
return !imported || !clients.has(imported);
|
|
369
|
+
});
|
|
370
|
+
if (elements.length !== bindings.elements.length) {
|
|
371
|
+
edits.push({
|
|
372
|
+
start: node.getStart(source),
|
|
373
|
+
end: node.end,
|
|
374
|
+
text:
|
|
375
|
+
elements.length || clause.name
|
|
376
|
+
? ts
|
|
377
|
+
.createPrinter()
|
|
378
|
+
.printNode(
|
|
379
|
+
ts.EmitHint.Unspecified,
|
|
380
|
+
ts.factory.updateImportDeclaration(
|
|
381
|
+
node,
|
|
382
|
+
node.modifiers,
|
|
383
|
+
ts.factory.updateImportClause(
|
|
384
|
+
clause,
|
|
385
|
+
clause.isTypeOnly,
|
|
386
|
+
clause.name,
|
|
387
|
+
ts.factory.updateNamedImports(bindings, elements),
|
|
388
|
+
),
|
|
389
|
+
node.moduleSpecifier,
|
|
390
|
+
node.attributes,
|
|
391
|
+
),
|
|
392
|
+
source,
|
|
393
|
+
)
|
|
394
|
+
: "",
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
if (
|
|
399
|
+
runtime &&
|
|
400
|
+
(node.moduleSpecifier.text.startsWith("node:") ||
|
|
401
|
+
[
|
|
402
|
+
"@tsplc/server",
|
|
403
|
+
"@trpc/server",
|
|
404
|
+
"zod",
|
|
405
|
+
"fs",
|
|
406
|
+
"http",
|
|
407
|
+
"https",
|
|
408
|
+
"net",
|
|
409
|
+
"tls",
|
|
410
|
+
].includes(node.moduleSpecifier.text))
|
|
411
|
+
) {
|
|
412
|
+
fail(
|
|
413
|
+
node,
|
|
414
|
+
"PLC1013",
|
|
415
|
+
`Server runtime import ${node.moduleSpecifier.text} cannot execute in PLC code. Expose a PLC procedure on the server router and call it through createServiceClient instead.`,
|
|
416
|
+
);
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
if (ts.isVariableStatement(node)) {
|
|
420
|
+
const clientStatement = node.declarationList.declarations.some(
|
|
421
|
+
(declaration) => {
|
|
422
|
+
const declared = symbolAt(checker, declaration.name);
|
|
423
|
+
return declared && clients.has(declared);
|
|
424
|
+
},
|
|
425
|
+
);
|
|
426
|
+
if (clientStatement) {
|
|
427
|
+
edits.push({ start: node.getStart(source), end: node.end, text: "" });
|
|
428
|
+
return;
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
// The client's binding is removed, so a type of it, as `typeof services`, has nothing to name.
|
|
432
|
+
if (clients.size && ts.isTypeQueryNode(node)) {
|
|
433
|
+
const named = ts.isQualifiedName(node.exprName)
|
|
434
|
+
? undefined
|
|
435
|
+
: symbolAt(checker, node.exprName);
|
|
436
|
+
if (named && clients.has(named)) {
|
|
437
|
+
edits.push({
|
|
438
|
+
start: node.getStart(source),
|
|
439
|
+
end: node.end,
|
|
440
|
+
text: "unknown",
|
|
441
|
+
});
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
if (clients.size && ts.isPropertyAccessExpression(node)) {
|
|
446
|
+
const parts: string[] = [];
|
|
447
|
+
let root: ts.Expression = node;
|
|
448
|
+
while (ts.isPropertyAccessExpression(root)) {
|
|
449
|
+
parts.unshift(root.name.text);
|
|
450
|
+
root = root.expression;
|
|
451
|
+
}
|
|
452
|
+
const client = symbolAt(checker, root);
|
|
453
|
+
const router = client && clients.get(client);
|
|
454
|
+
const procedure = router && procedureAt(checker, router, parts);
|
|
455
|
+
if (router) {
|
|
456
|
+
const path = parts.join(".");
|
|
457
|
+
if (!procedure) {
|
|
458
|
+
fail(
|
|
459
|
+
node,
|
|
460
|
+
"PLC1013",
|
|
461
|
+
`${path} is not a procedure of the client's router.`,
|
|
462
|
+
);
|
|
463
|
+
return;
|
|
464
|
+
}
|
|
465
|
+
const call =
|
|
466
|
+
calls.get(path) ?? serviceCall(checker, path, procedure, record);
|
|
467
|
+
if (call instanceof WireLayoutError) {
|
|
468
|
+
fail(node, "PLC2001", call.message);
|
|
469
|
+
return;
|
|
470
|
+
}
|
|
471
|
+
calls.set(path, call);
|
|
472
|
+
const name = serviceExportName(path);
|
|
473
|
+
const local = imports.get(name) ?? `tsplcRemote${imports.size}`;
|
|
474
|
+
imports.set(name, local);
|
|
475
|
+
edits.push({
|
|
476
|
+
start: node.getStart(source),
|
|
477
|
+
end: node.end,
|
|
478
|
+
text: local,
|
|
479
|
+
});
|
|
480
|
+
return;
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
ts.forEachChild(node, visit);
|
|
484
|
+
};
|
|
485
|
+
visit(source);
|
|
486
|
+
if (!edits.length) {
|
|
487
|
+
continue;
|
|
488
|
+
}
|
|
489
|
+
const text = edited(source, edits);
|
|
490
|
+
sources.set(
|
|
491
|
+
source.fileName,
|
|
492
|
+
imports.size && module
|
|
493
|
+
? mapped`${text}\nimport {${[...imports].map(([name, local]) => `${name} as ${local}`).join(",")}} from ${importSpecifier(source.fileName, module.file)};\n`
|
|
494
|
+
: text,
|
|
495
|
+
);
|
|
496
|
+
}
|
|
497
|
+
if (module && options) {
|
|
498
|
+
sources.set(
|
|
499
|
+
module.file,
|
|
500
|
+
from(module.client, serviceModule(records, calls, options)),
|
|
501
|
+
);
|
|
502
|
+
}
|
|
503
|
+
return {
|
|
504
|
+
sources,
|
|
505
|
+
diagnostics,
|
|
506
|
+
file: module?.file,
|
|
507
|
+
records: new Map([...records].map(([key, { name }]) => [key, name])),
|
|
508
|
+
};
|
|
509
|
+
};
|
|
510
|
+
|
|
511
|
+
const serviceModule = (
|
|
512
|
+
records: ReadonlyMap<string, { name: string; layout: RecordLayout }>,
|
|
513
|
+
calls: ReadonlyMap<string, ServiceCall>,
|
|
514
|
+
options: ServiceOptions,
|
|
515
|
+
) => {
|
|
516
|
+
const enums = new Map<ts.EnumDeclaration, string>();
|
|
517
|
+
const enumName = (declaration: ts.EnumDeclaration) => {
|
|
518
|
+
const name = enums.get(declaration) ?? `tsplcEnum${enums.size}`;
|
|
519
|
+
enums.set(declaration, name);
|
|
520
|
+
return name;
|
|
521
|
+
};
|
|
522
|
+
const scalar = (
|
|
523
|
+
field: WireScalar,
|
|
524
|
+
enumeration: ts.EnumDeclaration | undefined,
|
|
525
|
+
) => {
|
|
526
|
+
switch (field.kind) {
|
|
527
|
+
case "boolean":
|
|
528
|
+
return "BOOL";
|
|
529
|
+
case "integer":
|
|
530
|
+
return field.iec;
|
|
531
|
+
case "string":
|
|
532
|
+
return `STRING<${field.capacity}>`;
|
|
533
|
+
case "enum":
|
|
534
|
+
if (!enumeration) {
|
|
535
|
+
throw new Error("An enum wire field has no PLC enum declaration.");
|
|
536
|
+
}
|
|
537
|
+
return enumName(enumeration);
|
|
538
|
+
}
|
|
539
|
+
};
|
|
540
|
+
const interfaces = [...records.values()].map(({ name, layout }) => {
|
|
541
|
+
const fields = Object.entries(layout.fields).map(([key, field]) => {
|
|
542
|
+
const enumeration = layout.enums[key];
|
|
543
|
+
const type =
|
|
544
|
+
field.kind === "array"
|
|
545
|
+
? `FixedArray<${scalar(field.element, enumeration)},${field.length}>`
|
|
546
|
+
: scalar(field, enumeration);
|
|
547
|
+
return `${key}:${type}`;
|
|
548
|
+
});
|
|
549
|
+
return `export interface ${name}{${fields.join(";")}}`;
|
|
550
|
+
});
|
|
551
|
+
const functions = [...calls.values()]
|
|
552
|
+
.sort((left, right) =>
|
|
553
|
+
left.contract.path.localeCompare(right.contract.path),
|
|
554
|
+
)
|
|
555
|
+
.map(({ contract, input, output }) => {
|
|
556
|
+
const hasInput = Object.keys(contract.input.fields).length > 0;
|
|
557
|
+
const request = hasInput ? "input" : `defaultValue<${input}>()`;
|
|
558
|
+
const answer = output ?? "void";
|
|
559
|
+
const operation =
|
|
560
|
+
options.transport === "http"
|
|
561
|
+
? `tsplcServiceFetch<${answer}>(\`\${tsplcServiceBaseUrl}${servicePath(contract)}\`,{method:"POST",json:${request}})`
|
|
562
|
+
: `tsplcServiceCall<${answer},${input}>(${JSON.stringify(servicePath(contract))},${request})`;
|
|
563
|
+
return `export const ${serviceExportName(contract.path)}=async(${hasInput ? `input:${input}` : ""}):Promise<${answer}>=>{${output ? "return " : ""}await ${operation};};`;
|
|
564
|
+
});
|
|
565
|
+
const transport =
|
|
566
|
+
options.transport === "http"
|
|
567
|
+
? `import {fetch as tsplcServiceFetch} from "${sdkModules.async}";\nimport {env as tsplcServiceEnv} from "${sdkModules.config}";`
|
|
568
|
+
: `import {opcuaCall as tsplcServiceCall} from "${sdkModules.async}";`;
|
|
569
|
+
const enumImports = [...enums].map(
|
|
570
|
+
([declaration, name]) =>
|
|
571
|
+
`import type {${declaration.name.text} as ${name}} from ${JSON.stringify(declaration.getSourceFile().fileName)};`,
|
|
572
|
+
);
|
|
573
|
+
const baseUrl =
|
|
574
|
+
options.transport === "http"
|
|
575
|
+
? `const tsplcServiceBaseUrl:STRING<${baseUrlCapacity}>=tsplcServiceEnv<STRING<${baseUrlCapacity}>>(${JSON.stringify(options.baseUrlEnv)});`
|
|
576
|
+
: "";
|
|
577
|
+
return `${[
|
|
578
|
+
transport,
|
|
579
|
+
...enumImports,
|
|
580
|
+
baseUrl,
|
|
581
|
+
...interfaces,
|
|
582
|
+
...functions,
|
|
583
|
+
].join("\n")}\n`;
|
|
584
|
+
};
|
|
585
|
+
|
|
586
|
+
/** Lowers a type that names a called procedure's record, such as `inferRouterOutputs<AppRouter>["a"]["b"]`. */
|
|
587
|
+
export const serviceRecords = (
|
|
588
|
+
program: ts.Program,
|
|
589
|
+
lowering: { file: string | undefined; records: ReadonlyMap<string, string> },
|
|
590
|
+
): ServiceRecord | null => {
|
|
591
|
+
const source = lowering.file && program.getSourceFile(lowering.file);
|
|
592
|
+
if (!source) {
|
|
593
|
+
return null;
|
|
594
|
+
}
|
|
595
|
+
const checker = program.getTypeChecker();
|
|
596
|
+
const declarations = new Map(
|
|
597
|
+
source.statements
|
|
598
|
+
.filter(ts.isInterfaceDeclaration)
|
|
599
|
+
.map((value) => [value.name.text, value]),
|
|
600
|
+
);
|
|
601
|
+
return (type) => {
|
|
602
|
+
const layout = wireLayoutOf(() =>
|
|
603
|
+
recordLayout(checker, type, "record", false),
|
|
604
|
+
);
|
|
605
|
+
if (layout instanceof WireLayoutError) {
|
|
606
|
+
return undefined;
|
|
607
|
+
}
|
|
608
|
+
const name = lowering.records.get(recordKey(layout));
|
|
609
|
+
const declaration = name === undefined ? undefined : declarations.get(name);
|
|
610
|
+
return declaration && checker.getSymbolAtLocation(declaration.name);
|
|
611
|
+
};
|
|
612
|
+
};
|