@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.
Files changed (185) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +41 -2
  3. package/dist/cli.js +2325 -0
  4. package/dist/cli.js.map +26 -0
  5. package/dist/clock.js +11 -0
  6. package/dist/clock.js.map +11 -0
  7. package/dist/codesys.js +6563 -0
  8. package/dist/codesys.js.map +51 -0
  9. package/dist/collections.js +399 -0
  10. package/dist/collections.js.map +10 -0
  11. package/dist/index.js +16198 -0
  12. package/dist/index.js.map +62 -0
  13. package/dist/ir.js +3948 -0
  14. package/dist/ir.js.map +35 -0
  15. package/dist/retain.js +10 -0
  16. package/dist/retain.js.map +10 -0
  17. package/dist/signals.js +115 -0
  18. package/dist/signals.js.map +10 -0
  19. package/dist/telemetry.js +121 -0
  20. package/dist/telemetry.js.map +12 -0
  21. package/package.json +122 -4
  22. package/src/codesys/config.ts +50 -0
  23. package/src/codesys/debug.ts +655 -0
  24. package/src/codesys/emit.ts +185 -0
  25. package/src/codesys/endpoints.ts +111 -0
  26. package/src/codesys/engineering.ts +96 -0
  27. package/src/codesys/explain/expressions.ts +445 -0
  28. package/src/codesys/explain/flags.ts +134 -0
  29. package/src/codesys/explain/parameters.ts +53 -0
  30. package/src/codesys/explain/rows.ts +182 -0
  31. package/src/codesys/explain/tables.ts +79 -0
  32. package/src/codesys/explain/tasks.ts +68 -0
  33. package/src/codesys/explain/writes.ts +497 -0
  34. package/src/codesys/explain.ts +149 -0
  35. package/src/codesys/expressions.ts +100 -0
  36. package/src/codesys/global-lists.ts +284 -0
  37. package/src/codesys/global-names.ts +66 -0
  38. package/src/codesys/http.ts +1090 -0
  39. package/src/codesys/index.ts +13 -0
  40. package/src/codesys/instrumentation.ts +574 -0
  41. package/src/codesys/io-paths.ts +149 -0
  42. package/src/codesys/loops.ts +101 -0
  43. package/src/codesys/manifest.ts +684 -0
  44. package/src/codesys/names.ts +58 -0
  45. package/src/codesys/numeric.ts +516 -0
  46. package/src/codesys/plan.ts +688 -0
  47. package/src/codesys/programs.ts +138 -0
  48. package/src/codesys/publication.ts +99 -0
  49. package/src/codesys/required.ts +8 -0
  50. package/src/codesys/routines.ts +247 -0
  51. package/src/codesys/scan-clock.ts +103 -0
  52. package/src/codesys/scheduling.ts +96 -0
  53. package/src/codesys/service-channels.ts +24 -0
  54. package/src/codesys/sources.ts +118 -0
  55. package/src/codesys/st-files.ts +219 -0
  56. package/src/codesys/statements.ts +409 -0
  57. package/src/codesys/storage.ts +150 -0
  58. package/src/codesys/symbols.ts +240 -0
  59. package/src/codesys/task-access.ts +186 -0
  60. package/src/codesys/telemetry-settings.ts +19 -0
  61. package/src/codesys/telemetry.ts +852 -0
  62. package/src/codesys/types.ts +310 -0
  63. package/src/codesys/vendor.ts +113 -0
  64. package/src/frontend/analyzer.ts +779 -0
  65. package/src/frontend/async.ts +530 -0
  66. package/src/frontend/blocks.ts +578 -0
  67. package/src/frontend/configuration.ts +83 -0
  68. package/src/frontend/const-enums.ts +196 -0
  69. package/src/frontend/const-functions.ts +204 -0
  70. package/src/frontend/control-flow.ts +787 -0
  71. package/src/frontend/cooperative.ts +114 -0
  72. package/src/frontend/coroutines.ts +1344 -0
  73. package/src/frontend/dialect-names.ts +104 -0
  74. package/src/frontend/elaborate/array-searches.ts +224 -0
  75. package/src/frontend/elaborate/assignments.ts +343 -0
  76. package/src/frontend/elaborate/calls.ts +1342 -0
  77. package/src/frontend/elaborate/capture-protocol.ts +237 -0
  78. package/src/frontend/elaborate/capture.ts +388 -0
  79. package/src/frontend/elaborate/declarations.ts +124 -0
  80. package/src/frontend/elaborate/dialect.ts +473 -0
  81. package/src/frontend/elaborate/expressions.ts +2177 -0
  82. package/src/frontend/elaborate/filtered-arrays.ts +643 -0
  83. package/src/frontend/elaborate/frame.ts +145 -0
  84. package/src/frontend/elaborate/generics.ts +123 -0
  85. package/src/frontend/elaborate/graph.ts +141 -0
  86. package/src/frontend/elaborate/imports.ts +105 -0
  87. package/src/frontend/elaborate/index.ts +851 -0
  88. package/src/frontend/elaborate/initializers.ts +235 -0
  89. package/src/frontend/elaborate/iterators.ts +1541 -0
  90. package/src/frontend/elaborate/layouts.ts +1025 -0
  91. package/src/frontend/elaborate/model.ts +478 -0
  92. package/src/frontend/elaborate/names.ts +134 -0
  93. package/src/frontend/elaborate/reduce.ts +900 -0
  94. package/src/frontend/elaborate/references.ts +727 -0
  95. package/src/frontend/elaborate/retention.ts +284 -0
  96. package/src/frontend/elaborate/specialize.ts +1137 -0
  97. package/src/frontend/elaborate/statements.ts +1220 -0
  98. package/src/frontend/elaborate/storage.ts +836 -0
  99. package/src/frontend/elaborate/time-constructors.ts +34 -0
  100. package/src/frontend/elaborate/values.ts +200 -0
  101. package/src/frontend/elaborate/writes.ts +415 -0
  102. package/src/frontend/expressions.ts +1382 -0
  103. package/src/frontend/generated-names.ts +95 -0
  104. package/src/frontend/intrinsics.ts +382 -0
  105. package/src/frontend/lowering-key.ts +23 -0
  106. package/src/frontend/module-graph.ts +156 -0
  107. package/src/frontend/positions.ts +359 -0
  108. package/src/frontend/promise-chains.ts +872 -0
  109. package/src/frontend/promises.ts +419 -0
  110. package/src/frontend/routines.ts +239 -0
  111. package/src/frontend/sdk.ts +187 -0
  112. package/src/frontend/services.ts +612 -0
  113. package/src/frontend/statements.ts +871 -0
  114. package/src/frontend/tasks.ts +526 -0
  115. package/src/frontend/telemetry.ts +174 -0
  116. package/src/frontend/types.ts +1073 -0
  117. package/src/frontend/typescript.ts +659 -0
  118. package/src/index.ts +9 -0
  119. package/src/ir/aggregates.ts +291 -0
  120. package/src/ir/allocation.ts +96 -0
  121. package/src/ir/conditions.ts +855 -0
  122. package/src/ir/core-model.ts +289 -0
  123. package/src/ir/declarations.ts +281 -0
  124. package/src/ir/diagnostics.ts +68 -0
  125. package/src/ir/domains.ts +151 -0
  126. package/src/ir/fold.ts +279 -0
  127. package/src/ir/identity.ts +19 -0
  128. package/src/ir/index.ts +137 -0
  129. package/src/ir/job-errors.ts +69 -0
  130. package/src/ir/layouts.ts +211 -0
  131. package/src/ir/link.ts +302 -0
  132. package/src/ir/model.ts +394 -0
  133. package/src/ir/normalization-error.ts +10 -0
  134. package/src/ir/normalize.ts +52 -0
  135. package/src/ir/numeric.ts +163 -0
  136. package/src/ir/operands.ts +160 -0
  137. package/src/ir/ranges.ts +420 -0
  138. package/src/ir/routine.ts +1116 -0
  139. package/src/ir/scalars.ts +453 -0
  140. package/src/ir/share.ts +790 -0
  141. package/src/ir/short-circuit.ts +140 -0
  142. package/src/ir/tables.ts +111 -0
  143. package/src/ir/temporaries.ts +138 -0
  144. package/src/ir/types.ts +151 -0
  145. package/src/project/artifacts.ts +424 -0
  146. package/src/project/cli.ts +211 -0
  147. package/src/project/debugger.ts +111 -0
  148. package/src/project/deployments.ts +387 -0
  149. package/src/project/flags.ts +14 -0
  150. package/src/project/git.ts +35 -0
  151. package/src/project/plant.ts +629 -0
  152. package/src/project/project-commands.ts +507 -0
  153. package/src/project/project.ts +559 -0
  154. package/src/project/release.ts +152 -0
  155. package/src/project/server-check.ts +54 -0
  156. package/src/project/server.ts +165 -0
  157. package/src/project/terminal.ts +45 -0
  158. package/src/runtime/async.ts +207 -0
  159. package/src/runtime/launch.ts +59 -0
  160. package/src/runtime/main.ts +59 -0
  161. package/src/runtime/missing-file.ts +3 -0
  162. package/src/runtime/process.ts +177 -0
  163. package/src/runtime/program.ts +109 -0
  164. package/src/runtime/retain.ts +108 -0
  165. package/src/runtime/runtime.ts +324 -0
  166. package/src/runtime/settings.ts +27 -0
  167. package/src/runtime/storage.ts +456 -0
  168. package/src/runtime/symbols.ts +97 -0
  169. package/src/runtime/telemetry.ts +154 -0
  170. package/src/runtime/transport.ts +168 -0
  171. package/stdlib/clock.ts +8 -0
  172. package/stdlib/collections.ts +534 -0
  173. package/stdlib/plc-time.ts +2 -0
  174. package/stdlib/retain.ts +4 -0
  175. package/stdlib/signals.ts +142 -0
  176. package/stdlib/telemetry.ts +89 -0
  177. package/types/async.d.ts +87 -0
  178. package/types/clock.d.ts +8 -0
  179. package/types/config.d.ts +2 -0
  180. package/types/data-types.d.ts +31 -0
  181. package/types/dialect.d.ts +49 -0
  182. package/types/globals.d.ts +10 -0
  183. package/types/index.d.ts +212 -0
  184. package/types/retain.d.ts +12 -0
  185. package/types/telemetry.d.ts +47 -0
@@ -0,0 +1,145 @@
1
+ import type ts from "typescript";
2
+ import { from, type Mapped, mapped, type Part } from "../positions";
3
+ import type { ArrayLayout } from "./layouts";
4
+ import type { ModelNode } from "./model";
5
+ import { unusedName } from "./names";
6
+ import type { Env, Value } from "./values";
7
+
8
+ /** Indented lines of one generated routine, with the local names it has used. */
9
+ export class Emitter {
10
+ readonly lines: Mapped[] = [];
11
+ private depth = 1;
12
+ private readonly used = new Set<string>();
13
+ private temporaries = 0;
14
+
15
+ /** @param origin The source the next lines come from: the statement being specialized. */
16
+ constructor(public origin: ts.Node) {}
17
+
18
+ line(text: Part): void {
19
+ this.lines.push(
20
+ from(this.origin, mapped`${" ".repeat(this.depth)}${text}`),
21
+ );
22
+ }
23
+ open(text: Part): void {
24
+ this.line(text);
25
+ this.depth++;
26
+ }
27
+ close(text: Part = "}"): void {
28
+ this.depth--;
29
+ this.line(text);
30
+ }
31
+ /** Ends one block and starts the next on the same line, as `} else {` does. */
32
+ reopen(text: Part): void {
33
+ this.depth--;
34
+ this.line(text);
35
+ this.depth++;
36
+ }
37
+ local(name: string): string {
38
+ const unused = unusedName(name, (candidate) => this.used.has(candidate));
39
+ this.used.add(unused);
40
+ return unused;
41
+ }
42
+ temporary(): string {
43
+ return this.local(`tsplcTemp${++this.temporaries}`);
44
+ }
45
+ /** Whether code reads a local this routine has named. */
46
+ names(text: Part): boolean {
47
+ return namesIn(text).some((name) => this.used.has(name));
48
+ }
49
+ /** Whether a line this routine has written reads `name`. */
50
+ reads(name: string): boolean {
51
+ return this.lines.some((line) => namesIn(line).includes(name));
52
+ }
53
+ /**
54
+ * Runs `write` and takes the lines it wrote instead of keeping them, for a caller that places
55
+ * them once it knows what surrounds them. `nested` indents them for a block the caller opens.
56
+ */
57
+ detached<T>(
58
+ { nested }: { nested: boolean },
59
+ write: () => T,
60
+ ): { result: T; lines: Mapped[] } {
61
+ const start = this.lines.length;
62
+ const depth = this.depth;
63
+ this.depth += nested ? 1 : 0;
64
+ try {
65
+ const result = write();
66
+ return { result, lines: this.lines.splice(start) };
67
+ } finally {
68
+ this.depth = depth;
69
+ }
70
+ }
71
+ /** Places lines `detached` took. */
72
+ append(lines: readonly Mapped[]): void {
73
+ this.lines.push(...lines);
74
+ }
75
+ /** An if…else if chain, one arm for each test. */
76
+ chain(arms: readonly { test: Part; body: VoidFunction }[]): void {
77
+ arms.forEach((arm, index) => {
78
+ if (index === 0) {
79
+ this.open(mapped`if (${arm.test}) {`);
80
+ } else {
81
+ this.reopen(mapped`} else if (${arm.test}) {`);
82
+ }
83
+ arm.body();
84
+ });
85
+ if (arms.length > 0) {
86
+ this.close();
87
+ }
88
+ }
89
+ }
90
+
91
+ /** The names code reads: not a member's, nor the digits of a typed literal such as `16#FF`. */
92
+ const namesIn = (text: Part): string[] =>
93
+ String(text).match(/(?<![\w.#])[A-Za-z_]\w*/g) ?? [];
94
+
95
+ export interface Frame {
96
+ emitter: Emitter;
97
+ env: Env;
98
+ /**
99
+ * How many times the body of each PLC loop being written can run, outermost first; undefined for
100
+ * a loop with no counted bound. Frames within one routine share it.
101
+ */
102
+ loops: (number | undefined)[];
103
+ self?: ModelNode;
104
+ /** The routine's declared return type, for literal and optional results. */
105
+ returns?: ts.Type;
106
+ async: boolean;
107
+ /**
108
+ * In a generator run inline for a for…of: what each yield runs, the loop's body over the value,
109
+ * and the labelled block a return leaves.
110
+ */
111
+ generator?: { yields: (value: Value) => void; exit: string };
112
+ /** An array result's layout, at the length the routine's return statements give it. */
113
+ resultLayout?: ArrayLayout;
114
+ resultLength?: number;
115
+ /** Whether a return statement returned a stored record or array, which a caller only gets a copy of. */
116
+ returnsStored?: boolean;
117
+ /**
118
+ * In a routine whose result is a reference: the objects its return statements return, and
119
+ * whether one returns undefined.
120
+ */
121
+ referents?: Referents;
122
+ }
123
+
124
+ /**
125
+ * Writes the body of a loop that stays a loop in the PLC. A yield in it runs up to `runs` times,
126
+ * which sizes a snapshot of the generator; an unrolled loop needs none, as each step is written out.
127
+ */
128
+ export const looping = <T>(
129
+ frame: Frame,
130
+ runs: number | undefined,
131
+ body: () => T,
132
+ ): T => {
133
+ frame.loops.push(runs);
134
+ try {
135
+ return body();
136
+ } finally {
137
+ frame.loops.pop();
138
+ }
139
+ };
140
+
141
+ /** What a reference a routine returns can be. */
142
+ export interface Referents {
143
+ options: Set<ModelNode>;
144
+ optional: boolean;
145
+ }
@@ -0,0 +1,123 @@
1
+ import ts from "typescript";
2
+
3
+ const isTypeReference = (type: ts.Type): type is ts.TypeReference =>
4
+ Boolean(type.flags & ts.TypeFlags.Object) &&
5
+ "objectFlags" in type &&
6
+ typeof type.objectFlags === "number" &&
7
+ Boolean(type.objectFlags & ts.ObjectFlags.Reference);
8
+
9
+ /**
10
+ * Generic classes specialize per instance. While an instance's methods are specialized, the checker
11
+ * the elaborator reads through answers with that instance's type arguments in place of its class's
12
+ * type parameters, so `Ring<number>`'s `T[]` lays out as `number[]`.
13
+ */
14
+ export class GenericTypes {
15
+ readonly checker: ts.TypeChecker;
16
+ private readonly scopes: Map<ts.Type, ts.Type>[] = [];
17
+
18
+ constructor(private readonly base: ts.TypeChecker) {
19
+ this.checker = new Proxy(base, {
20
+ get: (target, property, receiver) => {
21
+ const value: unknown = Reflect.get(target, property, receiver);
22
+ if (typeof value !== "function") {
23
+ return value;
24
+ }
25
+ // Any answer that is a type, or a list of them, can name a type parameter.
26
+ return (...args: unknown[]) => {
27
+ const result: unknown = value.apply(target, args);
28
+ if (isType(result)) {
29
+ return this.substitute(result);
30
+ }
31
+ if (Array.isArray(result) && result.every(isType)) {
32
+ return result.map((type) => this.substitute(type));
33
+ }
34
+ return result;
35
+ };
36
+ },
37
+ });
38
+ }
39
+
40
+ /** Runs `work` with the type arguments of `instanceType`, a generic class's instance, in scope. */
41
+ within<T>(
42
+ declaration: ts.ClassLikeDeclaration | undefined,
43
+ instanceType: ts.Type | undefined,
44
+ work: () => T,
45
+ ): T {
46
+ const parameters = declaration?.typeParameters ?? [];
47
+ if (!parameters.length || !instanceType || !isTypeReference(instanceType)) {
48
+ return work();
49
+ }
50
+ const args = this.base.getTypeArguments(instanceType);
51
+ const scope = new Map(
52
+ parameters.flatMap((parameter, index): [ts.Type, ts.Type][] => {
53
+ const arg = args[index];
54
+ return arg
55
+ ? [[this.base.getTypeAtLocation(parameter), this.substitute(arg)]]
56
+ : [];
57
+ }),
58
+ );
59
+ this.scopes.push(scope);
60
+ try {
61
+ return work();
62
+ } finally {
63
+ this.scopes.pop();
64
+ }
65
+ }
66
+
67
+ /**
68
+ * Calls one of the checker's type constructors. TypeScript 6 has them on every checker but leaves
69
+ * them out of its public declarations, so they are looked up by name.
70
+ */
71
+ private construct(
72
+ name: "getUnionType" | "createArrayType",
73
+ argument: ts.Type | readonly ts.Type[],
74
+ ): ts.Type {
75
+ const make: unknown = Reflect.get(this.base, name);
76
+ if (typeof make !== "function") {
77
+ throw new Error(`This TypeScript's checker has no ${name}.`);
78
+ }
79
+ const made: unknown = make.call(this.base, argument);
80
+ if (!isType(made)) {
81
+ throw new Error(`${name} made no type.`);
82
+ }
83
+ return made;
84
+ }
85
+
86
+ /** A type with the type parameters in scope replaced, through unions and arrays. */
87
+ substitute(type: ts.Type): ts.Type {
88
+ if (!this.scopes.length) {
89
+ return type;
90
+ }
91
+ if (type.flags & ts.TypeFlags.TypeParameter) {
92
+ for (let index = this.scopes.length - 1; index >= 0; index--) {
93
+ const found = this.scopes[index]?.get(type);
94
+ if (found) {
95
+ return found;
96
+ }
97
+ }
98
+ return type;
99
+ }
100
+ if (type.isUnion()) {
101
+ const members = type.types.map((member) => this.substitute(member));
102
+ return members.some((member, index) => member !== type.types[index])
103
+ ? this.construct("getUnionType", members)
104
+ : type;
105
+ }
106
+ if (this.base.isArrayType(type) && isTypeReference(type)) {
107
+ const [element] = this.base.getTypeArguments(type);
108
+ const replaced = element && this.substitute(element);
109
+ return replaced && replaced !== element
110
+ ? this.construct("createArrayType", replaced)
111
+ : type;
112
+ }
113
+ return type;
114
+ }
115
+ }
116
+
117
+ /** Whether a checker's answer is a type; a signature also has flags and its checker, but no type's methods. */
118
+ const isType = (value: unknown): value is ts.Type =>
119
+ typeof value === "object" &&
120
+ value !== null &&
121
+ "flags" in value &&
122
+ "checker" in value &&
123
+ "isUnion" in value;
@@ -0,0 +1,141 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import ts from "typescript";
7
+ import { z } from "zod";
8
+ import { valueSymbol } from "../sdk";
9
+ import { isPropertyName } from "../types";
10
+ import {
11
+ bindingNames,
12
+ type CapturedGraph,
13
+ type CaptureRequest,
14
+ type ClosureSite,
15
+ capturedGraphSchema,
16
+ } from "./capture-protocol";
17
+ import { within } from "./writes";
18
+
19
+ /**
20
+ * Every arrow and function expression not bound at module level, which setup may store, with the
21
+ * names it captures from the functions around it, and `this` when it reads it. Setup notes what each
22
+ * captured when it made it, so the PLC can call it with those values.
23
+ */
24
+ export const closureSites = (
25
+ source: ts.SourceFile,
26
+ checker: ts.TypeChecker,
27
+ ): ClosureSite[] => {
28
+ const sites: ClosureSite[] = [];
29
+ const visit = (node: ts.Node, enclosing: ts.Node | undefined): void => {
30
+ const closure = ts.isArrowFunction(node) || ts.isFunctionExpression(node);
31
+ // A module-level const's function is captured by its name instead.
32
+ if (closure && !moduleFunction(node)) {
33
+ sites.push({
34
+ start: node.getStart(source),
35
+ end: node.end,
36
+ captures: enclosing ? captures(node, enclosing, checker) : [],
37
+ });
38
+ }
39
+ const scope =
40
+ ts.isFunctionLike(node) || ts.isClassLike(node) ? node : enclosing;
41
+ ts.forEachChild(node, (child) => visit(child, scope));
42
+ };
43
+ visit(source, undefined);
44
+ return sites;
45
+ };
46
+
47
+ /** The names a closure reads that the functions around it declare, and `this` if an arrow reads it. */
48
+ const captures = (
49
+ closure: ts.ArrowFunction | ts.FunctionExpression,
50
+ enclosing: ts.Node,
51
+ checker: ts.TypeChecker,
52
+ ): string[] => {
53
+ const names = new Set<string>();
54
+ const visit = (node: ts.Node): void => {
55
+ if (
56
+ node.kind === ts.SyntaxKind.ThisKeyword &&
57
+ ts.isArrowFunction(closure)
58
+ ) {
59
+ names.add("this");
60
+ }
61
+ if (ts.isIdentifier(node) && !isPropertyName(node)) {
62
+ const declaration = valueSymbol(checker, node)?.valueDeclaration;
63
+ if (
64
+ declaration &&
65
+ !within(declaration, closure) &&
66
+ within(declaration, enclosing) &&
67
+ !ts.isClassLike(declaration)
68
+ ) {
69
+ names.add(node.text);
70
+ }
71
+ }
72
+ if (!ts.isTypeNode(node)) {
73
+ ts.forEachChild(node, visit);
74
+ }
75
+ };
76
+ visit(closure.body);
77
+ return [...names];
78
+ };
79
+
80
+ /** A function a module-level const names, which capture finds by that name. */
81
+ const moduleFunction = (
82
+ node: ts.ArrowFunction | ts.FunctionExpression,
83
+ ): boolean => {
84
+ const declaration = node.parent;
85
+ const statement = declaration?.parent?.parent;
86
+ return (
87
+ ts.isVariableDeclaration(declaration) &&
88
+ statement !== undefined &&
89
+ ts.isVariableStatement(statement) &&
90
+ ts.isSourceFile(statement.parent)
91
+ );
92
+ };
93
+
94
+ /** Runs the setup of the program's runtime `sources` in a Bun subprocess and returns the object graph it built. */
95
+ export const captureGraph = (
96
+ entry: string,
97
+ sources: readonly ts.SourceFile[],
98
+ checker: ts.TypeChecker,
99
+ configuration: Readonly<Record<string, string>>,
100
+ ): CapturedGraph => {
101
+ const request: CaptureRequest = {
102
+ entry,
103
+ configuration,
104
+ files: sources.map((source) => source.fileName),
105
+ closures: Object.fromEntries(
106
+ sources.map((source) => [source.fileName, closureSites(source, checker)]),
107
+ ),
108
+ bindings: Object.fromEntries(
109
+ sources.map((source) => [source.fileName, bindingNames(source)]),
110
+ ),
111
+ };
112
+ const directory = mkdtempSync(join(tmpdir(), "tsplc-capture-"));
113
+ try {
114
+ const file = join(directory, "request.json");
115
+ writeFileSync(file, JSON.stringify(request));
116
+ const script = fileURLToPath(import.meta.resolve("#elaborate-capture"));
117
+ // The graph has its own file, so setup code is free to write to standard output.
118
+ const output = join(directory, "graph.json");
119
+ const result = spawnSync(process.execPath, [script, file, output], {
120
+ encoding: "utf8",
121
+ stdio: ["ignore", "ignore", "pipe"],
122
+ maxBuffer: 256 * 1024 * 1024,
123
+ });
124
+ if (result.status !== 0) {
125
+ throw new Error(
126
+ `Running the program's setup failed:\n${result.stderr.trim()}`,
127
+ );
128
+ }
129
+ const graph = capturedGraphSchema.safeParse(
130
+ JSON.parse(readFileSync(output, "utf8")),
131
+ );
132
+ if (!graph.success) {
133
+ throw new Error(
134
+ `The program's setup produced an invalid object graph:\n${z.prettifyError(graph.error)}`,
135
+ );
136
+ }
137
+ return graph.data;
138
+ } finally {
139
+ rmSync(directory, { recursive: true, force: true });
140
+ }
141
+ };
@@ -0,0 +1,105 @@
1
+ import { dirname, relative } from "node:path";
2
+ import type { Names } from "./names";
3
+
4
+ /** The specifier a generated module imports `to` by: relative, dot-prefixed and without its extension. */
5
+ export const importPath = (from: string, to: string): string => {
6
+ const path = relative(dirname(from), to)
7
+ .replace(/\\/g, "/")
8
+ .replace(/\.tsx?$/, "");
9
+ return path.startsWith("./") || path.startsWith("../") ? path : `./${path}`;
10
+ };
11
+
12
+ /** Names generated code imports from other modules, by module file. */
13
+ export class ModuleImports {
14
+ /** Each module's imported names, with the name generated code reads each by. */
15
+ private readonly imported = new Map<string, Map<string, string>>();
16
+
17
+ constructor(
18
+ private readonly names: Names,
19
+ /** Names the modules that import these declare themselves, which an import gives way to. */
20
+ private readonly avoided: ReadonlySet<string> = new Set(),
21
+ ) {}
22
+
23
+ /** Whether `name` of `file` is imported. */
24
+ has(file: string, name: string): boolean {
25
+ return this.imported.get(file)?.has(name) ?? false;
26
+ }
27
+
28
+ /**
29
+ * Records an import of `name` from `file`, and returns the name to read it by: its own, unless
30
+ * the generated modules already use that name for something else.
31
+ */
32
+ add(file: string, name: string): string {
33
+ const names = this.imported.get(file) ?? new Map<string, string>();
34
+ this.imported.set(file, names);
35
+ const local = this.names.import(`${file}\0${name}`, name, this.avoided);
36
+ names.set(name, local);
37
+ return local;
38
+ }
39
+
40
+ /** One import statement per module, as `importer` reaches it. */
41
+ lines(importer: string, keyword: "import" | "import type"): string[] {
42
+ return [...this.imported].flatMap(([file, names]) => {
43
+ const list = [...names]
44
+ // A module already has what it declares itself, under its own name.
45
+ .filter(([name, local]) => file !== importer || name !== local)
46
+ .map(([name, local]) =>
47
+ name === local ? name : `${name} as ${local}`,
48
+ );
49
+ return list.length
50
+ ? [
51
+ `${keyword} { ${list.join(", ")} } from "${importPath(importer, file)}";`,
52
+ ]
53
+ : [];
54
+ });
55
+ }
56
+ }
57
+
58
+ /**
59
+ * What the generated entry module imports besides the generated types: the storage modules,
60
+ * kept modules' bindings, and the SDK functions scan code and generated conversions call.
61
+ */
62
+ export class EntryImports {
63
+ /** Storage modules generated code reads through a namespace import, by import name. */
64
+ private readonly namespaces = new Map<string, string>();
65
+ /** Bindings of kept modules, read by their own names unless something else has them. */
66
+ readonly kept: ModuleImports;
67
+ /** SDK functions by the module that declares them, such as `@tsplc/compiler/clock`. */
68
+ private readonly sdk = new Map<string, Set<string>>();
69
+
70
+ constructor(private readonly names: Names) {
71
+ this.kept = new ModuleImports(names);
72
+ }
73
+
74
+ /**
75
+ * Records a namespace import of a storage module, and returns the name to read it by: `name`,
76
+ * unless the generated modules already use that for something else, as two roots whose names
77
+ * differ only in their separators would.
78
+ */
79
+ namespace(file: string, name: string): string {
80
+ const local = this.names.import(file, name);
81
+ this.namespaces.set(local, file);
82
+ return local;
83
+ }
84
+
85
+ /** Records a call of `name`, which `module` of the SDK declares. */
86
+ addSdk(module: string, name: string): void {
87
+ const names = this.sdk.get(module) ?? new Set<string>();
88
+ names.add(name);
89
+ this.sdk.set(module, names);
90
+ }
91
+
92
+ lines(entryFile: string): string[] {
93
+ return [
94
+ ...[...this.namespaces].map(
95
+ ([name, file]) =>
96
+ `import * as ${name} from "${importPath(entryFile, file)}";`,
97
+ ),
98
+ ...this.kept.lines(entryFile, "import"),
99
+ ...[...this.sdk].map(
100
+ ([module, names]) =>
101
+ `import { ${[...names].join(", ")} } from "${module}";`,
102
+ ),
103
+ ];
104
+ }
105
+ }