xbintsc 0.3.5 → 0.3.7

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 (60) hide show
  1. package/README.md +81 -8
  2. package/README.zh-CN.md +78 -8
  3. package/dist/src/cli/main.d.ts +1 -0
  4. package/dist/src/cli/main.js +13 -1
  5. package/dist/src/cli/main.js.map +1 -1
  6. package/dist/src/codegen/generator/context.d.ts +12 -0
  7. package/dist/src/codegen/generator/context.js +28 -1
  8. package/dist/src/codegen/generator/context.js.map +1 -1
  9. package/dist/src/codegen/generator/state.d.ts +8 -0
  10. package/dist/src/codegen/generator/state.js.map +1 -1
  11. package/dist/src/codegen/generator/statements/control-flow.js +1 -8
  12. package/dist/src/codegen/generator/statements/control-flow.js.map +1 -1
  13. package/dist/src/codegen/generator/tables.d.ts +11 -0
  14. package/dist/src/codegen/generator/tables.js +13 -0
  15. package/dist/src/codegen/generator/tables.js.map +1 -1
  16. package/dist/src/driver/compiler.js +22 -4
  17. package/dist/src/driver/compiler.js.map +1 -1
  18. package/dist/src/driver/toolchain-download.js +26 -0
  19. package/dist/src/driver/toolchain-download.js.map +1 -1
  20. package/dist/src/extensions/native.d.ts +92 -0
  21. package/dist/src/extensions/native.js +217 -0
  22. package/dist/src/extensions/native.js.map +1 -0
  23. package/dist/src/extensions/registry.d.ts +13 -0
  24. package/dist/src/extensions/registry.js +10 -0
  25. package/dist/src/extensions/registry.js.map +1 -1
  26. package/dist/src/index.d.ts +1 -0
  27. package/dist/src/index.js +1 -0
  28. package/dist/src/index.js.map +1 -1
  29. package/dist/tests/cli/main.test.js +15 -0
  30. package/dist/tests/cli/main.test.js.map +1 -1
  31. package/dist/tests/codegen/llvm.test.js +24 -0
  32. package/dist/tests/codegen/llvm.test.js.map +1 -1
  33. package/dist/tests/driver/toolchain-download.test.js +15 -0
  34. package/dist/tests/driver/toolchain-download.test.js.map +1 -1
  35. package/dist/tests/driver/toolchain-provider.test.js +21 -1
  36. package/dist/tests/driver/toolchain-provider.test.js.map +1 -1
  37. package/dist/tests/e2e/native-extensions.test.d.ts +13 -0
  38. package/dist/tests/e2e/native-extensions.test.js +175 -0
  39. package/dist/tests/e2e/native-extensions.test.js.map +1 -0
  40. package/dist/tests/extensions/native.test.d.ts +1 -0
  41. package/dist/tests/extensions/native.test.js +101 -0
  42. package/dist/tests/extensions/native.test.js.map +1 -0
  43. package/dist/tests/helpers.d.ts +4 -1
  44. package/dist/tests/helpers.js +2 -1
  45. package/dist/tests/helpers.js.map +1 -1
  46. package/package.json +1 -1
  47. package/runtime/rt_internal.h +5 -3
  48. package/runtime/xt_ext.h +109 -0
  49. package/runtime/xt_ext.rs +173 -0
  50. package/runtime/xt_io.c +15 -14
  51. package/src/cli/main.ts +13 -1
  52. package/src/codegen/generator/context.ts +29 -1
  53. package/src/codegen/generator/state.ts +5 -0
  54. package/src/codegen/generator/statements/control-flow.ts +1 -8
  55. package/src/codegen/generator/tables.ts +14 -0
  56. package/src/driver/compiler.ts +25 -4
  57. package/src/driver/toolchain-download.ts +27 -0
  58. package/src/extensions/native.ts +270 -0
  59. package/src/extensions/registry.ts +21 -0
  60. package/src/index.ts +10 -0
@@ -0,0 +1,270 @@
1
+ /**
2
+ * Native (C++ / Rust) extensions.
3
+ *
4
+ * xbintsc can consume code that was compiled outside the TypeScript pipeline,
5
+ * as long as it exposes `extern "C"` entry points with the runtime calling
6
+ * convention:
7
+ *
8
+ * xt_value my_fn(int32_t argc, xt_value *argv);
9
+ *
10
+ * A C++ or Rust project is built into an object file or static archive, and a
11
+ * small JSON manifest describes how those symbols map onto global functions
12
+ * (`builtins`) and importable modules (`modules`). The driver links the
13
+ * artifacts verbatim and the code generator wires the bindings exactly like it
14
+ * does for the built-in `node` extension — the core compiler never needs to
15
+ * know the extension was written in C++ or Rust.
16
+ *
17
+ * ```jsonc
18
+ * {
19
+ * "name": "mathx",
20
+ * "description": "C++ math helpers",
21
+ * "objects": ["build/libmathx.a"],
22
+ * "linkerFlags": ["-lm"],
23
+ * "linkerFlagsByPlatform": { "linux": ["-lstdc++"], "darwin": ["-lc++"] },
24
+ * "builtins": { "fastAdd": { "symbol": "mathx_add" } },
25
+ * "modules": {
26
+ * "mathx": {
27
+ * "exports": {
28
+ * "add": { "symbol": "mathx_add" },
29
+ * "reverse": { "symbol": "mathx_reverse" }
30
+ * }
31
+ * }
32
+ * }
33
+ * }
34
+ * ```
35
+ *
36
+ * `objects` paths are resolved relative to the manifest file, so a manifest can
37
+ * live next to the project it describes.
38
+ */
39
+
40
+ import { existsSync, readFileSync } from "node:fs";
41
+ import { dirname, isAbsolute, resolve } from "node:path";
42
+ import type { Extension, ExtensionModule, ModuleExport, ModuleExports } from "./registry.js";
43
+
44
+ /** A global function an extension provides (callable without an import). */
45
+ export interface NativeBuiltin {
46
+ /** Exported C symbol, called as `xt_value symbol(int32_t argc, xt_value *argv)`. */
47
+ readonly symbol: string;
48
+ readonly returnVoid?: boolean;
49
+ }
50
+
51
+ /** One binding inside a `modules` entry; mirrors the core `ModuleExport`. */
52
+ export type NativeModuleExport = ModuleExport;
53
+
54
+ /** An importable module supplied by the native library. */
55
+ export interface NativeModule {
56
+ /** Named exports for `import { x } from "..."`. */
57
+ readonly exports?: Readonly<Record<string, NativeModuleExport>>;
58
+ /** Namespace name for `import * as ns` / `import ns from`. */
59
+ readonly namespace?: string;
60
+ }
61
+
62
+ /** The on-disk schema of a native extension manifest. */
63
+ export interface NativeManifest {
64
+ /** Unique extension name (used by `--ext`/diagnostics). */
65
+ readonly name: string;
66
+ readonly description?: string;
67
+ /**
68
+ * Object files (`.o`) or static archives (`.a`/`.lib`) to link. Resolved
69
+ * relative to the manifest unless absolute.
70
+ */
71
+ readonly objects?: readonly string[];
72
+ /** Linker flags appended verbatim, e.g. `["-lm"]`. */
73
+ readonly linkerFlags?: readonly string[];
74
+ /**
75
+ * Linker flags added only on the given platform (`darwin`, `linux`, `win32`),
76
+ * for C++ standard libraries or Rust's native dependencies that differ per OS.
77
+ */
78
+ readonly linkerFlagsByPlatform?: Readonly<Record<string, readonly string[]>>;
79
+ /** Global functions the extension binds. */
80
+ readonly builtins?: Readonly<Record<string, NativeBuiltin>>;
81
+ /** Modules importable as `import ... from "<specifier>"`. */
82
+ readonly modules?: Readonly<Record<string, NativeModule>>;
83
+ }
84
+
85
+ /** Raised for a malformed manifest or a missing build artifact. */
86
+ export class NativeExtensionError extends Error {
87
+ constructor(message: string) {
88
+ super(message);
89
+ this.name = "NativeExtensionError";
90
+ }
91
+ }
92
+
93
+ function isRecord(value: unknown): value is Record<string, unknown> {
94
+ return typeof value === "object" && value !== null && !Array.isArray(value);
95
+ }
96
+
97
+ function stringArray(value: unknown, field: string): readonly string[] {
98
+ if (value === undefined) return [];
99
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
100
+ throw new NativeExtensionError(`Native manifest field '${field}' must be an array of strings`);
101
+ }
102
+ return value as readonly string[];
103
+ }
104
+
105
+ function parseBuiltins(value: unknown): Readonly<Record<string, NativeBuiltin>> | undefined {
106
+ if (value === undefined) return undefined;
107
+ if (!isRecord(value)) throw new NativeExtensionError("Native manifest field 'builtins' must be an object");
108
+ const builtins: Record<string, NativeBuiltin> = {};
109
+ for (const [name, entry] of Object.entries(value)) {
110
+ if (!isRecord(entry) || typeof entry.symbol !== "string" || entry.symbol.length === 0) {
111
+ throw new NativeExtensionError(`Native manifest builtin '${name}' needs a non-empty 'symbol'`);
112
+ }
113
+ builtins[name] = {
114
+ symbol: entry.symbol,
115
+ ...(entry.returnVoid === true ? { returnVoid: true } : {}),
116
+ };
117
+ }
118
+ return builtins;
119
+ }
120
+
121
+ function parseExports(value: unknown, moduleName: string): ModuleExports | undefined {
122
+ if (value === undefined) return undefined;
123
+ if (!isRecord(value)) {
124
+ throw new NativeExtensionError(`Native manifest module '${moduleName}'.exports must be an object`);
125
+ }
126
+ const exports: Record<string, ModuleExport> = {};
127
+ for (const [name, entry] of Object.entries(value)) {
128
+ if (!isRecord(entry)) {
129
+ throw new NativeExtensionError(`Native manifest export '${moduleName}.${name}' must be an object`);
130
+ }
131
+ const symbol = entry.symbol;
132
+ const namespace = entry.namespace;
133
+ const method = entry.method;
134
+ if (symbol !== undefined && typeof symbol !== "string") {
135
+ throw new NativeExtensionError(`Native manifest export '${moduleName}.${name}'.symbol must be a string`);
136
+ }
137
+ if (namespace !== undefined && typeof namespace !== "string") {
138
+ throw new NativeExtensionError(`Native manifest export '${moduleName}.${name}'.namespace must be a string`);
139
+ }
140
+ if (method !== undefined && typeof method !== "string") {
141
+ throw new NativeExtensionError(`Native manifest export '${moduleName}.${name}'.method must be a string`);
142
+ }
143
+ if (symbol === undefined && namespace === undefined) {
144
+ throw new NativeExtensionError(
145
+ `Native manifest export '${moduleName}.${name}' needs a 'symbol' or a 'namespace'`,
146
+ );
147
+ }
148
+ exports[name] = {
149
+ ...(symbol !== undefined ? { symbol } : {}),
150
+ ...(namespace !== undefined ? { namespace } : {}),
151
+ ...(method !== undefined ? { method } : {}),
152
+ ...(entry.returnVoid === true ? { returnVoid: true } : {}),
153
+ ...(entry.isConstructor === true ? { isConstructor: true } : {}),
154
+ };
155
+ }
156
+ return exports;
157
+ }
158
+
159
+ function parseModules(value: unknown): Readonly<Record<string, ExtensionModule>> | undefined {
160
+ if (value === undefined) return undefined;
161
+ if (!isRecord(value)) throw new NativeExtensionError("Native manifest field 'modules' must be an object");
162
+ const modules: Record<string, ExtensionModule> = {};
163
+ for (const [specifier, entry] of Object.entries(value)) {
164
+ if (!isRecord(entry)) {
165
+ throw new NativeExtensionError(`Native manifest module '${specifier}' must be an object`);
166
+ }
167
+ if (entry.namespace !== undefined && typeof entry.namespace !== "string") {
168
+ throw new NativeExtensionError(`Native manifest module '${specifier}'.namespace must be a string`);
169
+ }
170
+ modules[specifier] = {
171
+ ...(entry.namespace !== undefined ? { namespace: entry.namespace } : {}),
172
+ ...(entry.exports !== undefined ? { exports: parseExports(entry.exports, specifier) } : {}),
173
+ };
174
+ }
175
+ return modules;
176
+ }
177
+
178
+ /** Validate parsed JSON and normalise it into a {@link NativeManifest}. */
179
+ export function parseNativeManifest(value: unknown, source = "<manifest>"): NativeManifest {
180
+ if (!isRecord(value)) throw new NativeExtensionError(`Native manifest ${source} must contain a JSON object`);
181
+ if (typeof value.name !== "string" || value.name.trim().length === 0) {
182
+ throw new NativeExtensionError(`Native manifest ${source} needs a non-empty 'name'`);
183
+ }
184
+ if (value.description !== undefined && typeof value.description !== "string") {
185
+ throw new NativeExtensionError(`Native manifest '${value.name}'.description must be a string`);
186
+ }
187
+
188
+ let linkerFlagsByPlatform: Record<string, readonly string[]> | undefined;
189
+ if (value.linkerFlagsByPlatform !== undefined) {
190
+ if (!isRecord(value.linkerFlagsByPlatform)) {
191
+ throw new NativeExtensionError("Native manifest field 'linkerFlagsByPlatform' must be an object");
192
+ }
193
+ linkerFlagsByPlatform = {};
194
+ for (const [platform, flags] of Object.entries(value.linkerFlagsByPlatform)) {
195
+ linkerFlagsByPlatform[platform] = stringArray(flags, `linkerFlagsByPlatform.${platform}`);
196
+ }
197
+ }
198
+
199
+ const builtins = parseBuiltins(value.builtins);
200
+ const modules = parseModules(value.modules);
201
+
202
+ return {
203
+ name: value.name,
204
+ ...(value.description !== undefined ? { description: value.description } : {}),
205
+ objects: stringArray(value.objects, "objects"),
206
+ linkerFlags: stringArray(value.linkerFlags, "linkerFlags"),
207
+ ...(linkerFlagsByPlatform ? { linkerFlagsByPlatform } : {}),
208
+ ...(builtins ? { builtins } : {}),
209
+ ...(modules ? { modules } : {}),
210
+ };
211
+ }
212
+
213
+ /** Read and validate a manifest from disk. */
214
+ export function loadNativeManifest(manifestPath: string): NativeManifest {
215
+ const absolute = resolve(manifestPath);
216
+ let text: string;
217
+ try {
218
+ text = readFileSync(absolute, "utf8");
219
+ } catch (error) {
220
+ throw new NativeExtensionError(`Unable to read native extension manifest '${absolute}': ${String(error)}`);
221
+ }
222
+ let parsed: unknown;
223
+ try {
224
+ parsed = JSON.parse(text);
225
+ } catch (error) {
226
+ throw new NativeExtensionError(`Native extension manifest '${absolute}' is not valid JSON: ${String(error)}`);
227
+ }
228
+ return parseNativeManifest(parsed, absolute);
229
+ }
230
+
231
+ function resolveArtifact(baseDir: string, path: string): string {
232
+ return isAbsolute(path) ? path : resolve(baseDir, path);
233
+ }
234
+
235
+ /**
236
+ * Turn a manifest into an {@link Extension}: resolve and verify every native
237
+ * object, then expose the manifest's builtins/modules to the code generator.
238
+ *
239
+ * The manifest is read eagerly so a typo surfaces at registration time rather
240
+ * than at link time.
241
+ */
242
+ export function nativeExtensionFromManifest(manifestPath: string): Extension {
243
+ const absolute = resolve(manifestPath);
244
+ const manifest = loadNativeManifest(absolute);
245
+ const baseDir = dirname(absolute);
246
+
247
+ const objects = (manifest.objects ?? []).map((object) => resolveArtifact(baseDir, object));
248
+ for (const object of objects) {
249
+ if (!existsSync(object)) {
250
+ throw new NativeExtensionError(
251
+ `Native extension '${manifest.name}' references missing object '${object}'.\n` +
252
+ `Build the C++/Rust library first (see the project next to ${absolute}).`,
253
+ );
254
+ }
255
+ }
256
+
257
+ const linkerFlags = () => [
258
+ ...(manifest.linkerFlags ?? []),
259
+ ...(manifest.linkerFlagsByPlatform?.[process.platform] ?? []),
260
+ ];
261
+
262
+ return {
263
+ name: manifest.name,
264
+ description: manifest.description ?? `Native extension from ${absolute}`,
265
+ nativeObjects: () => objects,
266
+ linkerFlags,
267
+ ...(manifest.builtins ? { builtins: () => manifest.builtins! } : {}),
268
+ ...(manifest.modules ? { modules: () => manifest.modules! } : {}),
269
+ };
270
+ }
@@ -52,6 +52,17 @@ export interface Extension {
52
52
  readonly description?: string;
53
53
  /** C/asm sources compiled and linked alongside the generated module. */
54
54
  runtimeSources?(): readonly string[];
55
+ /**
56
+ * Pre-built object files or static archives linked alongside the generated
57
+ * module. This is the hook for native extensions written in C++ or Rust:
58
+ * compile them to `extern "C"` objects (or a static library) that use the
59
+ * `xt_value` ABI, then hand the artifacts to the driver through an
60
+ * `Extension` such as the one built by `src/extensions/native.ts`.
61
+ *
62
+ * The paths must already exist; the driver passes them straight to the
63
+ * linker and never recompiles them.
64
+ */
65
+ nativeObjects?(): readonly string[];
55
66
  /** Extra linker flags (e.g. `["-lm"]`, `["-framework", "CoreFoundation"]`). */
56
67
  linkerFlags?(): readonly string[];
57
68
  /** Global identifiers that resolve to runtime symbols when called. */
@@ -123,6 +134,16 @@ export class ExtensionRegistry {
123
134
  return sources;
124
135
  }
125
136
 
137
+ /** Flatten every registered extension's pre-built native objects. */
138
+ nativeObjects(): readonly string[] {
139
+ const objects: string[] = [];
140
+ for (const extension of this.extensions.values()) {
141
+ const extra = extension.nativeObjects?.();
142
+ if (extra) objects.push(...extra);
143
+ }
144
+ return objects;
145
+ }
146
+
126
147
  linkerFlags(): readonly string[] {
127
148
  const flags: string[] = [];
128
149
  for (const extension of this.extensions.values()) {
package/src/index.ts CHANGED
@@ -32,4 +32,14 @@ export {
32
32
  export { ExtensionRegistry, createDefaultRegistry, coreExtension, type Extension, type ExtensionModule, type ModuleExport, type ModuleExports } from "./extensions/registry.js";
33
33
  export { nodeExtension } from "./extensions/node/index.js";
34
34
  export type { NodeModule } from "./extensions/node/module.js";
35
+ export {
36
+ NativeExtensionError,
37
+ loadNativeManifest,
38
+ nativeExtensionFromManifest,
39
+ parseNativeManifest,
40
+ type NativeManifest,
41
+ type NativeBuiltin,
42
+ type NativeModule,
43
+ type NativeModuleExport,
44
+ } from "./extensions/native.js";
35
45
  export * from "./driver/index.js";