@ubjs/wasm 0.31.0-5

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/README.md ADDED
@@ -0,0 +1,60 @@
1
+ # @ubjs/wasm
2
+
3
+ The WebAssembly player runtime for [`uniffi-bindgen-react-native`][bindgen]
4
+ generated bindings. Imported by generated TypeScript code; not intended for
5
+ direct use.
6
+
7
+ [bindgen]: https://github.com/jhugman/uniffi-bindgen-react-native
8
+
9
+ ## What it does
10
+
11
+ The player reads a table of FFI signatures the bindgen emits alongside your
12
+ bindings, and calls the `.wasm` through it. Nothing per-crate is generated in
13
+ C++ or JavaScript — one runtime drives every module.
14
+
15
+ ## Compatibility
16
+
17
+ Runs anywhere `WebAssembly` does: modern browsers, Node ≥18, Bun, and web
18
+ bundlers. The `exports` map picks the browser or node build through the
19
+ `browser` and `node` conditions.
20
+
21
+ Hermes has no `WebAssembly`, so this does not run in a standard React Native
22
+ app. Use the JSI flavor there. Metro is still supported as a *web* bundler
23
+ (Expo Web, React Native Web).
24
+
25
+ ## Install
26
+
27
+ You should not install this directly. Generated bindings import it, and list
28
+ `@ubjs/core` as a peer requirement.
29
+
30
+ ```bash
31
+ npm install @ubjs/wasm @ubjs/core
32
+ ```
33
+
34
+ ## Loading a module
35
+
36
+ Generated bindings export `uniffiInitAsync`, which takes the `.wasm` however
37
+ your environment names it — a URL, a path, a `Response`, or bytes. Naming the
38
+ asset is the one thing only the host knows, so there is no default.
39
+
40
+ ```ts
41
+ import { uniffiInitAsync } from './generated';
42
+
43
+ import wasm from './generated/my_crate.wasm'; // bundler
44
+ const wasm = new URL('./generated/my_crate.wasm', import.meta.url); // node
45
+
46
+ await uniffiInitAsync(wasm);
47
+ ```
48
+
49
+ Under Metro, `.wasm` goes through the asset registry rather than becoming a
50
+ URL; resolve it with `Asset.fromModule(...).uri`, or serve the file and pass
51
+ its URL.
52
+
53
+ ## Rust side
54
+
55
+ Your crate builds a `cdylib` and depends on the [`uniffi-runtime-wasm`][crate]
56
+ crate, which supplies the allocator and panic hook the player calls into.
57
+ `ubrn build wasm2` checks both, and `uniffi_core` needs its
58
+ `wasm-unstable-single-threaded` feature.
59
+
60
+ [crate]: https://crates.io/crates/uniffi-runtime-wasm
@@ -0,0 +1,14 @@
1
+ import { UniffiNativeModule, type ImportResolver, type WasmSource } from "../../core/src/module.js";
2
+ export { FfiType } from "../../core/src/ffi-type.js";
3
+ export { UniffiNativeModule };
4
+ export type { WasmSource };
5
+ /**
6
+ * `options.resolveModule` supplies the wasm's own module imports. A cdylib
7
+ * that reached wasm-bindgen through its dependencies imports `./<lib>_bg.js`,
8
+ * and the caller must hand that glue over — generated bindings import it
9
+ * statically, which keeps it in the bundler's graph. Nothing here loads a
10
+ * module at runtime, so a bundler sees no dynamic import to warn about.
11
+ */
12
+ export declare function openWasm(source: WasmSource | Promise<Response>, options?: {
13
+ resolveModule?: ImportResolver;
14
+ }): Promise<UniffiNativeModule>;
@@ -0,0 +1,26 @@
1
+ /*
2
+ * This Source Code Form is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/
5
+ */
6
+ import { UniffiNativeModule, } from "../../core/src/module.js";
7
+ export { FfiType } from "../../core/src/ffi-type.js";
8
+ export { UniffiNativeModule };
9
+ /**
10
+ * `options.resolveModule` supplies the wasm's own module imports. A cdylib
11
+ * that reached wasm-bindgen through its dependencies imports `./<lib>_bg.js`,
12
+ * and the caller must hand that glue over — generated bindings import it
13
+ * statically, which keeps it in the bundler's graph. Nothing here loads a
14
+ * module at runtime, so a bundler sees no dynamic import to warn about.
15
+ */
16
+ export async function openWasm(source, options) {
17
+ if (typeof source === "string" || source instanceof URL) {
18
+ const response = await fetch(source.toString());
19
+ return UniffiNativeModule.open(response, options);
20
+ }
21
+ // `fetch(...)` handed straight in, without an intervening `await`.
22
+ if (typeof source?.then === "function") {
23
+ return UniffiNativeModule.open(await source, options);
24
+ }
25
+ return UniffiNativeModule.open(source, options);
26
+ }
@@ -0,0 +1,45 @@
1
+ import type { Memory } from "./memory.js";
2
+ import type { Scratch } from "./scratch.js";
3
+ import { type StructLayout } from "./marshal.js";
4
+ import type { FfiTypeDesc } from "./ffi-type.js";
5
+ import type { CallbackDef } from "./callback.js";
6
+ export interface FunctionDef {
7
+ args: FfiTypeDesc[];
8
+ ret: FfiTypeDesc;
9
+ hasRustCallStatus: boolean;
10
+ }
11
+ export interface DispatchContext {
12
+ memory: Memory;
13
+ scratch: Scratch;
14
+ structs: Map<string, StructLayout>;
15
+ callbackDefs: Map<string, CallbackDef>;
16
+ alloc: (size: number, align: number) => number;
17
+ free: (ptr: number, size: number, align: number) => void;
18
+ installCallback: (fn: (...args: any[]) => any, def: CallbackDef) => number;
19
+ useJit: boolean;
20
+ }
21
+ /**
22
+ * Probe for `new Function` availability. Returns true if we can JIT-compile
23
+ * dispatchers; false under strict CSP. The probe is cheap (one Function
24
+ * construction) and the result is captured at register() time for the
25
+ * lifetime of the module.
26
+ */
27
+ export declare function canUseFunctionConstructor(): boolean;
28
+ export declare function getCapacityHint(view: Uint8Array): number | undefined;
29
+ /**
30
+ * Build a JIT-compiled dispatcher for a function whose arg/return types are
31
+ * all in the "simple" set (scalars + `RustBuffer` + `Void` return). Returns
32
+ * `undefined` for unsupported shapes (callback args, struct-by-value args,
33
+ * etc.) so the caller falls back to the interpreted dispatcher.
34
+ *
35
+ * Offsets, scalar/RustBuffer call shape, and the inline status check are
36
+ * baked into the body. The body refers to `mem`, `fn`, `alloc`, `ctx` and
37
+ * a handful of helpers as free variables; they are passed in as
38
+ * `new Function` constructor args so V8 can monomorphise the closure
39
+ * identically to hand-written source.
40
+ *
41
+ * The body bakes in one register-time scratch base, so it carries the same
42
+ * re-entrancy hazard as `buildInterpretedDispatcher`. See `Scratch.reserve`.
43
+ */
44
+ export declare function buildJitDispatcher(ctx: DispatchContext, exportFn: Function, def: FunctionDef, fnName: string): ((...args: any[]) => unknown) | undefined;
45
+ export declare function specializeFunction(ctx: DispatchContext, exportFn: Function, def: FunctionDef, fnName?: string): (...jsArgs: any[]) => any;
@@ -0,0 +1,476 @@
1
+ import { RUST_CALL_STATUS_SIZE, RUST_BUFFER_SIZE, RCS_ERROR_BUF_OFF, readRustBuffer, writeRustBufferPayload, writeRustCallStatusZero, } from "./marshal.js";
2
+ const SCALAR_SLOT = { scratchSize: 0, scratchAlign: 1 };
3
+ const RUST_BUFFER_SLOT = {
4
+ scratchSize: RUST_BUFFER_SIZE,
5
+ scratchAlign: 8,
6
+ };
7
+ /** Scratch a lowered arg needs. Only `RustBuffer` takes a slot; everything
8
+ * else — scalars, callback table indices, and the persistently-allocated
9
+ * `Reference(Struct)` — passes by value. */
10
+ function argSlot(t) {
11
+ return t.tag === "RustBuffer" ? RUST_BUFFER_SLOT : SCALAR_SLOT;
12
+ }
13
+ /** Scratch a return value needs. `RustBuffer` returns come back through an
14
+ * sret pointer; scalars and `Void` come back in the wasm return slot. */
15
+ function retSlot(t) {
16
+ return t.tag === "RustBuffer"
17
+ ? { hasSret: true, ...RUST_BUFFER_SLOT }
18
+ : { hasSret: false, ...SCALAR_SLOT };
19
+ }
20
+ const align = (off, a) => (off + (a - 1)) & ~(a - 1);
21
+ /**
22
+ * Probe for `new Function` availability. Returns true if we can JIT-compile
23
+ * dispatchers; false under strict CSP. The probe is cheap (one Function
24
+ * construction) and the result is captured at register() time for the
25
+ * lifetime of the module.
26
+ */
27
+ export function canUseFunctionConstructor() {
28
+ try {
29
+ // eslint-disable-next-line no-new-func
30
+ return new Function("return 42")() === 42;
31
+ }
32
+ catch {
33
+ return false;
34
+ }
35
+ }
36
+ function planArg(t) {
37
+ switch (t.tag) {
38
+ case "UInt8":
39
+ case "Int8":
40
+ case "UInt16":
41
+ case "Int16":
42
+ case "UInt32":
43
+ case "Int32":
44
+ case "VoidPointer":
45
+ case "MutReference":
46
+ return { ...argSlot(t), prepare: (_c, _b, v) => v | 0 };
47
+ case "UInt64":
48
+ case "Int64":
49
+ case "Handle":
50
+ return { ...argSlot(t), prepare: (_c, _b, v) => v }; // bigint passes through
51
+ case "Float32":
52
+ case "Float64":
53
+ return { ...argSlot(t), prepare: (_c, _b, v) => v };
54
+ case "RustBuffer":
55
+ return {
56
+ ...argSlot(t),
57
+ // Codegen lowers every `RustBuffer`-shaped arg via
58
+ // `converter.lower(value, rustbuffer_alloc)`, so the view arriving
59
+ // here already aliases wasm memory: its `byteOffset` is the
60
+ // `dataPtr`. All that remains is the (capacity, len, dataPtr) struct
61
+ // Rust reads as a `RustBuffer`. Rust drops it via
62
+ // `Vec::from_raw_parts`, so don't free `dataPtr` here.
63
+ prepare: (ctx, base, v) => {
64
+ writeRustBufferPayload(ctx.memory, ctx.alloc, base, v);
65
+ return base;
66
+ },
67
+ };
68
+ case "Callback": {
69
+ const name = t.name;
70
+ return {
71
+ ...argSlot(t),
72
+ prepare: (ctx, _base, fn) => {
73
+ const def = ctx.callbackDefs.get(name);
74
+ if (!def) {
75
+ throw new Error(`planArg: callback shape "${name}" not registered`);
76
+ }
77
+ return ctx.installCallback(fn, def);
78
+ },
79
+ };
80
+ }
81
+ case "Reference": {
82
+ // The only `Reference(...)` arg in the codegen today is
83
+ // `Reference(Struct(name))` — used for `init_callback_vtable_*` to pass
84
+ // a vtable struct in linear memory. The allocation is persistent: Rust
85
+ // retains the pointer for the cdylib lifetime, so it is deliberately
86
+ // not freed from the scratch path.
87
+ if (t.inner.tag !== "Struct") {
88
+ throw new Error(`planArg: Reference inner type ${t.inner.tag} not yet supported`);
89
+ }
90
+ const structName = t.inner.name;
91
+ return {
92
+ ...argSlot(t),
93
+ prepare: (ctx, _base, value) => {
94
+ const layout = ctx.structs.get(structName);
95
+ if (!layout) {
96
+ throw new Error(`planArg: struct "${structName}" not registered`);
97
+ }
98
+ const ptr = ctx.alloc(layout.size, 8);
99
+ for (const f of layout.fields) {
100
+ const fieldVal = value[f.name];
101
+ if (f.type.tag === "Callback") {
102
+ const def = ctx.callbackDefs.get(f.type.name);
103
+ if (!def) {
104
+ throw new Error(`planArg: callback shape "${f.type.name}" (in struct "${structName}") not registered`);
105
+ }
106
+ const slot = ctx.installCallback(fieldVal, def);
107
+ ctx.memory.writeU32(ptr + f.offset, slot);
108
+ }
109
+ else {
110
+ f.shape.write(ctx.memory, ptr + f.offset, fieldVal);
111
+ }
112
+ }
113
+ return ptr;
114
+ },
115
+ };
116
+ }
117
+ default:
118
+ throw new Error(`planArg: type ${t.tag} not yet supported`);
119
+ }
120
+ }
121
+ // Copy a wasm-side RustBuffer's payload into a fresh `Uint8Array` and free
122
+ // the wasm allocation. Used for RustCallStatus's errorBuf, whose bytes reach
123
+ // `liftString` / errorHandler after the allocation is gone and so must be
124
+ // JS-owned.
125
+ function copyAndFreeRustBuffer(ctx, rb) {
126
+ const len = Number(rb.len);
127
+ const cap = Number(rb.capacity);
128
+ const bytes = len > 0 ? ctx.memory.readBytes(rb.dataPtr, len) : new Uint8Array(0);
129
+ if (cap > 0 && rb.dataPtr !== 0) {
130
+ ctx.free(rb.dataPtr, cap, 1);
131
+ }
132
+ return bytes;
133
+ }
134
+ // Records a view's Rust-side `capacity`, which `rustbuffer_free` must pass
135
+ // back to satisfy the allocator's `Layout` contract.
136
+ //
137
+ // A handed-off view has `byteLength === len`, so converters see only the
138
+ // message bytes — but Rust may have allocated more. Views from elsewhere
139
+ // (`rustbuffer_alloc(n)`) carry no hint, and the runtime falls back to
140
+ // `byteLength`, which equals capacity for those.
141
+ const CAPACITY_HINT = Symbol("uniffi.rustbuffer.capacity");
142
+ function setCapacityHint(view, capacity) {
143
+ view[CAPACITY_HINT] = capacity;
144
+ }
145
+ export function getCapacityHint(view) {
146
+ return view[CAPACITY_HINT];
147
+ }
148
+ // Alias the RustBuffer's payload in wasm memory — no copy, no free. The one
149
+ // mandatory copy happens inside `lift()` instead.
150
+ //
151
+ // Two invariants the caller owns:
152
+ //
153
+ // * Ownership. The codegen call site wraps `lift(view)` in `try/finally`
154
+ // so `rustbuffer_free(view)` runs even when `lift` throws.
155
+ // * Detachment. Growing wasm memory invalidates the view, so `lift` must
156
+ // not trigger a grow before it finishes reading. Converter `read` only
157
+ // allocates on the JS heap, so this holds today.
158
+ function viewRustBufferHandoff(ctx, rb) {
159
+ const cap = Number(rb.capacity);
160
+ const len = Number(rb.len);
161
+ if (cap === 0 || rb.dataPtr === 0)
162
+ return new Uint8Array(0);
163
+ const view = new Uint8Array(ctx.memory.buffer(), rb.dataPtr, len);
164
+ if (cap !== len)
165
+ setCapacityHint(view, cap);
166
+ return view;
167
+ }
168
+ function planRet(t) {
169
+ switch (t.tag) {
170
+ case "Void":
171
+ return { ...retSlot(t), finish: () => undefined };
172
+ case "UInt8":
173
+ case "Int8":
174
+ case "UInt16":
175
+ case "Int16":
176
+ case "UInt32":
177
+ case "Int32":
178
+ case "Handle":
179
+ case "UInt64":
180
+ case "Int64":
181
+ case "Float32":
182
+ case "Float64":
183
+ return { ...retSlot(t), finish: (_c, _b, r) => r };
184
+ case "RustBuffer":
185
+ // Hand back a `Uint8Array` view aliasing wasm memory. Codegen wraps the
186
+ // converter's `lift(view)` in try/finally so `rustbuffer_free(view)`
187
+ // releases the allocation even when `lift` throws.
188
+ return {
189
+ ...retSlot(t),
190
+ finish: (ctx, sretBase) => viewRustBufferHandoff(ctx, readRustBuffer(ctx.memory, sretBase)),
191
+ };
192
+ default:
193
+ throw new Error(`planRet: type ${t.tag} not yet supported`);
194
+ }
195
+ }
196
+ /**
197
+ * Lay out one call's scratch — status, sret, then each arg needing a slot —
198
+ * and reserve the region. Takes `ScratchSlot`s rather than plans so both
199
+ * dispatchers can call it: the JIT path knows the sizes without building the
200
+ * `prepare`/`finish` closures it would never call.
201
+ */
202
+ function computeAndReserveLayout(ctx, def, argSlots, ret) {
203
+ let layoutSize = 0;
204
+ const statusOff = def.hasRustCallStatus
205
+ ? ((layoutSize = align(layoutSize, 8)), layoutSize)
206
+ : -1;
207
+ if (def.hasRustCallStatus)
208
+ layoutSize += RUST_CALL_STATUS_SIZE;
209
+ const sretOff = ret.hasSret
210
+ ? ((layoutSize = align(layoutSize, ret.scratchAlign)), layoutSize)
211
+ : -1;
212
+ if (ret.hasSret)
213
+ layoutSize += ret.scratchSize;
214
+ const argOffsets = argSlots.map((s) => {
215
+ if (s.scratchSize === 0)
216
+ return -1;
217
+ layoutSize = align(layoutSize, s.scratchAlign);
218
+ const off = layoutSize;
219
+ layoutSize += s.scratchSize;
220
+ return off;
221
+ });
222
+ const base = ctx.scratch.reserve(layoutSize);
223
+ return { layoutSize, statusOff, sretOff, argOffsets, base };
224
+ }
225
+ /**
226
+ * Interpreted dispatcher: reserve scratch once, then per call write each arg
227
+ * via its `prepare` closure, call `exportFn`, check the status inline, and
228
+ * return `retPlan.finish`.
229
+ *
230
+ * Every call shares the one register-time scratch reservation, so an export
231
+ * that re-enters itself synchronously corrupts the outer call. See
232
+ * `Scratch.reserve`.
233
+ */
234
+ function buildInterpretedDispatcher(ctx, exportFn, def) {
235
+ const argPlans = def.args.map((t) => planArg(t));
236
+ const retPlan = planRet(def.ret);
237
+ const { statusOff, sretOff, argOffsets, base } = computeAndReserveLayout(ctx, def, argPlans, retPlan);
238
+ return function dispatch(...jsArgs) {
239
+ // Last JS arg is the status object iff hasRustCallStatus.
240
+ const userArgs = def.hasRustCallStatus ? jsArgs.slice(0, -1) : jsArgs;
241
+ const statusObj = def.hasRustCallStatus ? jsArgs[jsArgs.length - 1] : null;
242
+ if (def.hasRustCallStatus)
243
+ writeRustCallStatusZero(ctx.memory, base + statusOff);
244
+ const wasmArgs = [];
245
+ if (retPlan.hasSret)
246
+ wasmArgs.push(base + sretOff);
247
+ for (let i = 0; i < argPlans.length; i++) {
248
+ const p = argPlans[i];
249
+ const argBase = argOffsets[i] >= 0 ? base + argOffsets[i] : 0;
250
+ wasmArgs.push(p.prepare(ctx, argBase, userArgs[i]));
251
+ }
252
+ if (def.hasRustCallStatus)
253
+ wasmArgs.push(base + statusOff);
254
+ const scalarRet = exportFn(...wasmArgs);
255
+ // Inline status check on the success path — no RustCallStatus object built.
256
+ if (def.hasRustCallStatus) {
257
+ const code = ctx.memory.readU8(base + statusOff);
258
+ statusObj.code = code;
259
+ if (code !== 0) {
260
+ // Lift errorBuf into a Uint8Array and free the wasm allocation, to
261
+ // match the `UniffiByteArray` contract `rust-call.ts` assumes when
262
+ // it forwards the buffer to liftString / errorHandler.
263
+ const errBufRb = readRustBuffer(ctx.memory, base + statusOff + RCS_ERROR_BUF_OFF);
264
+ statusObj.errorBuf = copyAndFreeRustBuffer(ctx, errBufRb);
265
+ // On the error path Rust hasn't written a valid value into the sret
266
+ // slot — `rustCallWithError` will throw via `uniffiCheckCallStatus`
267
+ // before anything looks at the return, so skip `retPlan.finish`.
268
+ return undefined;
269
+ }
270
+ }
271
+ return retPlan.finish(ctx, base + sretOff, scalarRet);
272
+ };
273
+ }
274
+ /**
275
+ * Tags that the JIT dispatcher knows how to emit inline as return types.
276
+ * Includes `Void` (return-only), scalars, and `RustBuffer`.
277
+ */
278
+ function isSimpleRetType(t) {
279
+ switch (t.tag) {
280
+ case "Void":
281
+ case "UInt8":
282
+ case "Int8":
283
+ case "UInt16":
284
+ case "Int16":
285
+ case "UInt32":
286
+ case "Int32":
287
+ case "UInt64":
288
+ case "Int64":
289
+ case "Float32":
290
+ case "Float64":
291
+ case "Handle":
292
+ case "RustBuffer":
293
+ return true;
294
+ default:
295
+ return false;
296
+ }
297
+ }
298
+ /**
299
+ * Tags that the JIT dispatcher knows how to emit inline as arg types.
300
+ * Restricted to scalars and `RustBuffer` — excludes `Void` (return-only).
301
+ * Anything outside this set returns `undefined` from `buildJitDispatcher`,
302
+ * causing `specializeFunction` to fall back to the interpreted path.
303
+ */
304
+ function isSimpleArgType(t) {
305
+ switch (t.tag) {
306
+ case "UInt8":
307
+ case "Int8":
308
+ case "UInt16":
309
+ case "Int16":
310
+ case "UInt32":
311
+ case "Int32":
312
+ case "UInt64":
313
+ case "Int64":
314
+ case "Float32":
315
+ case "Float64":
316
+ case "Handle":
317
+ case "RustBuffer":
318
+ return true;
319
+ default:
320
+ return false;
321
+ }
322
+ }
323
+ function isI32Tag(tag) {
324
+ return (tag === "UInt8" ||
325
+ tag === "Int8" ||
326
+ tag === "UInt16" ||
327
+ tag === "Int16" ||
328
+ tag === "UInt32" ||
329
+ tag === "Int32");
330
+ }
331
+ function isBigIntTag(tag) {
332
+ return tag === "UInt64" || tag === "Int64" || tag === "Handle";
333
+ }
334
+ function isFloatTag(tag) {
335
+ return tag === "Float32" || tag === "Float64";
336
+ }
337
+ function isPassByValueArg(tag) {
338
+ return isI32Tag(tag) || isBigIntTag(tag) || isFloatTag(tag);
339
+ }
340
+ function safeName(name) {
341
+ return name.replace(/[^A-Za-z0-9_]/g, "_") || "dispatch";
342
+ }
343
+ function buildReturnReader(retTag, sretBase) {
344
+ switch (retTag) {
345
+ case "Void":
346
+ return "return undefined;";
347
+ case "UInt8":
348
+ case "Int8":
349
+ case "UInt16":
350
+ case "Int16":
351
+ case "UInt32":
352
+ case "Int32":
353
+ case "UInt64":
354
+ case "Int64":
355
+ case "Handle":
356
+ case "Float32":
357
+ case "Float64":
358
+ return "return scalarRet;";
359
+ case "RustBuffer":
360
+ // As in `planRet`: the caller's try/finally frees the returned view.
361
+ return `return viewRustBufferHandoff(ctx, readRustBuffer(mem, ${sretBase}));`;
362
+ default:
363
+ // Unreachable: `isSimpleRetType` filters before this is called.
364
+ return "throw new Error('JIT: unsupported return type');";
365
+ }
366
+ }
367
+ /**
368
+ * Build a JIT-compiled dispatcher for a function whose arg/return types are
369
+ * all in the "simple" set (scalars + `RustBuffer` + `Void` return). Returns
370
+ * `undefined` for unsupported shapes (callback args, struct-by-value args,
371
+ * etc.) so the caller falls back to the interpreted dispatcher.
372
+ *
373
+ * Offsets, scalar/RustBuffer call shape, and the inline status check are
374
+ * baked into the body. The body refers to `mem`, `fn`, `alloc`, `ctx` and
375
+ * a handful of helpers as free variables; they are passed in as
376
+ * `new Function` constructor args so V8 can monomorphise the closure
377
+ * identically to hand-written source.
378
+ *
379
+ * The body bakes in one register-time scratch base, so it carries the same
380
+ * re-entrancy hazard as `buildInterpretedDispatcher`. See `Scratch.reserve`.
381
+ */
382
+ export function buildJitDispatcher(ctx, exportFn, def, fnName) {
383
+ // Bail out for unsupported shapes — fall back to interpreted.
384
+ for (const a of def.args) {
385
+ if (!isSimpleArgType(a))
386
+ return undefined;
387
+ }
388
+ if (!isSimpleRetType(def.ret))
389
+ return undefined;
390
+ const { statusOff, sretOff, argOffsets, base } = computeAndReserveLayout(ctx, def, def.args.map(argSlot), retSlot(def.ret));
391
+ // String-build the dispatcher body.
392
+ const hasStatus = def.hasRustCallStatus;
393
+ const userArgNames = def.args.map((_, i) => `a${i}`);
394
+ const paramNames = hasStatus
395
+ ? [...userArgNames, "statusObj"]
396
+ : [...userArgNames];
397
+ // Per-arg: scalars pass straight through; RustBuffer writes a 24-byte
398
+ // struct into the reserved scratch slot.
399
+ const writes = [];
400
+ for (let i = 0; i < def.args.length; i++) {
401
+ const tag = def.args[i].tag;
402
+ if (isPassByValueArg(tag)) {
403
+ // Nothing to write — value goes straight into the wasm call below.
404
+ }
405
+ else if (tag === "RustBuffer") {
406
+ const off = base + argOffsets[i];
407
+ writes.push(`writeRustBufferPayload(mem, alloc, ${off}, a${i});`);
408
+ }
409
+ else {
410
+ // isSimpleArgType filtered above; this is unreachable.
411
+ throw new Error(`unreachable: arg tag ${tag} passed isSimpleArgType`);
412
+ }
413
+ }
414
+ // Wasm-side arg order: [sret?, ...userArgs, status?].
415
+ const callArgs = [];
416
+ if (sretOff >= 0)
417
+ callArgs.push(`${base + sretOff}`);
418
+ for (let i = 0; i < def.args.length; i++) {
419
+ const tag = def.args[i].tag;
420
+ if (isI32Tag(tag)) {
421
+ // Match the interpreted path's `v | 0` coercion.
422
+ callArgs.push(`(a${i} | 0)`);
423
+ }
424
+ else if (isPassByValueArg(tag)) {
425
+ // bigint / float pass straight through.
426
+ callArgs.push(`a${i}`);
427
+ }
428
+ else {
429
+ // RustBuffer: the wasm fn receives the scratch pointer.
430
+ callArgs.push(`${base + argOffsets[i]}`);
431
+ }
432
+ }
433
+ if (hasStatus)
434
+ callArgs.push(`${base + statusOff}`);
435
+ const statusBase = base + statusOff;
436
+ const errBufBase = statusBase + RCS_ERROR_BUF_OFF;
437
+ const writeStatusZero = hasStatus
438
+ ? `writeRustCallStatusZero(mem, ${statusBase});`
439
+ : "";
440
+ // Mirrors `buildInterpretedDispatcher`: assign `statusObj.code` on both
441
+ // paths, and on error copy out errorBuf then return undefined — Rust
442
+ // leaves the sret slot invalid when the call fails.
443
+ const statusCheck = hasStatus
444
+ ? `
445
+ var code = mem.readU8(${statusBase});
446
+ statusObj.code = code;
447
+ if (code !== 0) {
448
+ statusObj.errorBuf = copyAndFreeRustBuffer(ctx, readRustBuffer(mem, ${errBufBase}));
449
+ return undefined;
450
+ }
451
+ `
452
+ : "";
453
+ const callExpr = `fn(${callArgs.join(", ")})`;
454
+ const readRet = buildReturnReader(def.ret.tag, base + sretOff);
455
+ const body = `
456
+ "use strict";
457
+ return function ${safeName(fnName)}(${paramNames.join(", ")}) {
458
+ ${writeStatusZero}
459
+ ${writes.join("\n ")}
460
+ var scalarRet = ${callExpr};
461
+ ${statusCheck}
462
+ ${readRet}
463
+ };
464
+ `;
465
+ // eslint-disable-next-line no-new-func
466
+ const factory = new Function("ctx", "mem", "fn", "alloc", "readRustBuffer", "viewRustBufferHandoff", "copyAndFreeRustBuffer", "writeRustBufferPayload", "writeRustCallStatusZero", body);
467
+ return factory(ctx, ctx.memory, exportFn, ctx.alloc, readRustBuffer, viewRustBufferHandoff, copyAndFreeRustBuffer, writeRustBufferPayload, writeRustCallStatusZero);
468
+ }
469
+ export function specializeFunction(ctx, exportFn, def, fnName = "dispatch") {
470
+ if (ctx.useJit) {
471
+ const jit = buildJitDispatcher(ctx, exportFn, def, fnName);
472
+ if (jit)
473
+ return jit;
474
+ }
475
+ return buildInterpretedDispatcher(ctx, exportFn, def);
476
+ }