@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 +60 -0
- package/dist/browser/src/index.d.ts +14 -0
- package/dist/browser/src/index.js +26 -0
- package/dist/core/src/call.d.ts +45 -0
- package/dist/core/src/call.js +476 -0
- package/dist/core/src/callback.d.ts +95 -0
- package/dist/core/src/callback.js +562 -0
- package/dist/core/src/ffi-type.d.ts +111 -0
- package/dist/core/src/ffi-type.js +22 -0
- package/dist/core/src/future.d.ts +22 -0
- package/dist/core/src/future.js +64 -0
- package/dist/core/src/index.d.ts +2 -0
- package/dist/core/src/index.js +7 -0
- package/dist/core/src/marshal.d.ts +84 -0
- package/dist/core/src/marshal.js +210 -0
- package/dist/core/src/memory.d.ts +26 -0
- package/dist/core/src/memory.js +75 -0
- package/dist/core/src/module.d.ts +48 -0
- package/dist/core/src/module.js +267 -0
- package/dist/core/src/scratch.d.ts +40 -0
- package/dist/core/src/scratch.js +81 -0
- package/dist/core/src/trampoline.d.ts +9 -0
- package/dist/core/src/trampoline.js +153 -0
- package/dist/node/src/index.d.ts +19 -0
- package/dist/node/src/index.js +35 -0
- package/package.json +47 -0
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import type { FfiTypeDesc } from "./ffi-type.js";
|
|
2
|
+
import type { Memory } from "./memory.js";
|
|
3
|
+
import { type StructLayout } from "./marshal.js";
|
|
4
|
+
export interface CallbackDef {
|
|
5
|
+
args: FfiTypeDesc[];
|
|
6
|
+
ret: FfiTypeDesc;
|
|
7
|
+
hasRustCallStatus: boolean;
|
|
8
|
+
outReturn?: boolean;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Per-instance dispatch table. `module.ts` owns one of these and routes the
|
|
12
|
+
* `__ubrn_dispatch` import through `dispatch`.
|
|
13
|
+
*/
|
|
14
|
+
export declare class CallbackTable {
|
|
15
|
+
private memory;
|
|
16
|
+
private hostExports;
|
|
17
|
+
/** Async compilation is not implemented; `false` is reserved for it. */
|
|
18
|
+
private compileSync;
|
|
19
|
+
private shapes;
|
|
20
|
+
private shapesByShapeId;
|
|
21
|
+
/**
|
|
22
|
+
* Shapes that bypass the registry-by-handle path. The `RustFutureContinu-
|
|
23
|
+
* ationCallback` shape lives here: its first argument is a u64 cookie, not
|
|
24
|
+
* a UniFFI registry handle, so the per-shape callback owns its own routing
|
|
25
|
+
* (e.g. the FutureRegistry's cookie -> resolver map).
|
|
26
|
+
*/
|
|
27
|
+
private continuationShapes;
|
|
28
|
+
/** Optional registration context: callback shape defs + compiled struct
|
|
29
|
+
* layouts. Set by `module.ts` after `registerSync()` so `makeDispatchRoute`
|
|
30
|
+
* can resolve `Callback`-typed args (function-table indices) into JS
|
|
31
|
+
* callables that re-lower their args and dispatch through the indirect
|
|
32
|
+
* function table. */
|
|
33
|
+
private registrationContext?;
|
|
34
|
+
constructor(memory: Memory, hostExports: WebAssembly.Exports,
|
|
35
|
+
/** Async compilation is not implemented; `false` is reserved for it. */
|
|
36
|
+
compileSync?: boolean);
|
|
37
|
+
setRegistrationContext(ctx: {
|
|
38
|
+
callbackDefs: Map<string, CallbackDef>;
|
|
39
|
+
structs: Map<string, StructLayout>;
|
|
40
|
+
}): void;
|
|
41
|
+
/**
|
|
42
|
+
* Implements `env.__ubrn_dispatch`. Trampolines prepend their shape id and
|
|
43
|
+
* forward everything else verbatim.
|
|
44
|
+
*
|
|
45
|
+
* On the registry path the host's first argument is the handle, per the
|
|
46
|
+
* UniFFI vtable convention; it is stripped before calling the closure.
|
|
47
|
+
*
|
|
48
|
+
* For shapes registered via `registerContinuationShape` (e.g. the future
|
|
49
|
+
* continuation callback) we forward all args verbatim — `args[0]` is a
|
|
50
|
+
* cookie, not a handle, and the caller owns the lookup.
|
|
51
|
+
*/
|
|
52
|
+
dispatch: (shapeId: number, ...args: any[]) => any;
|
|
53
|
+
/**
|
|
54
|
+
* Mark `shapeId` as a "continuation" shape — when the trampoline fires for
|
|
55
|
+
* that shape we route directly to `fn(...args)` rather than going through
|
|
56
|
+
* the registry-by-handle lookup. Used by `FutureRegistry`.
|
|
57
|
+
*/
|
|
58
|
+
registerContinuationShape(shapeId: number, fn: (...args: any[]) => any): void;
|
|
59
|
+
private fnSlotCache;
|
|
60
|
+
installCallbackFunction(fn: (...args: any[]) => any, def: CallbackDef): number;
|
|
61
|
+
private makeDispatchRoute;
|
|
62
|
+
/**
|
|
63
|
+
* Define (or look up, if already defined) the trampoline for a callback
|
|
64
|
+
* shape. Returns the shape id, which is the index callers should pass to
|
|
65
|
+
* `register`/`installAt`.
|
|
66
|
+
*/
|
|
67
|
+
defineShape(_name: string, def: CallbackDef): number;
|
|
68
|
+
/** Register a JS closure for `def`'s shape. Returns the handle. */
|
|
69
|
+
register(name: string, fn: (...args: any[]) => any, def: CallbackDef): number;
|
|
70
|
+
/** Drop a previously registered callback. */
|
|
71
|
+
unregister(handle: number, def: CallbackDef): void;
|
|
72
|
+
/** Number of live registrations for `def`'s shape. Used by tests and by
|
|
73
|
+
* the generated `free` vtable hook to verify callbacks are released. */
|
|
74
|
+
size(def: CallbackDef): number;
|
|
75
|
+
/**
|
|
76
|
+
* Install a shape's trampoline into the host's indirect function table at
|
|
77
|
+
* `tableIndex`. The host wasm calls into the trampoline via
|
|
78
|
+
* `call_indirect`, so this is how a JS callback becomes reachable from
|
|
79
|
+
* Rust.
|
|
80
|
+
*
|
|
81
|
+
* Note: many callbacks of the same *shape* share one trampoline, but each
|
|
82
|
+
* needs its own table slot because the host passes a fixed table index per
|
|
83
|
+
* Rust-side callback object.
|
|
84
|
+
*/
|
|
85
|
+
installAt(tableIndex: number, shapeId: number): void;
|
|
86
|
+
private shapeIdFor;
|
|
87
|
+
private signatureKey;
|
|
88
|
+
/** Encode the trampoline's wasm-level signature and emit the wasm bytes
|
|
89
|
+
* for it via the JS-side encoder in `trampoline.ts`. The wasm-level
|
|
90
|
+
* params are `def.args` plus implicit i32 pointer args UniFFI tacks on
|
|
91
|
+
* when `outReturn` / `hasRustCallStatus` are set; for `outReturn` the
|
|
92
|
+
* return travels via the pointer, so the trampoline's wasm return is
|
|
93
|
+
* void regardless of `def.ret`. */
|
|
94
|
+
private compileTrampoline;
|
|
95
|
+
}
|
|
@@ -0,0 +1,562 @@
|
|
|
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
|
+
// JS-side dispatch table and per-shape trampoline cache for the Wasm2 player.
|
|
7
|
+
//
|
|
8
|
+
// Rust can only call back into JS through `call_indirect`, so every callback
|
|
9
|
+
// needs a wasm function in the host's `__indirect_function_table`. Three
|
|
10
|
+
// pieces make that work:
|
|
11
|
+
//
|
|
12
|
+
// * A *shape* is one signature, say "(i32, i32) -> i32". Each gets one
|
|
13
|
+
// trampoline, emitted by `trampoline.ts` and instantiated as its own
|
|
14
|
+
// module: it imports `env.__ubrn_dispatch` and exports "trampoline".
|
|
15
|
+
// * Many closures share their shape's trampoline. `register` hands each a
|
|
16
|
+
// *handle*, unique within the shape, which the host passes as the first
|
|
17
|
+
// argument.
|
|
18
|
+
// * `dispatch(shapeId, handle, ...args)` recovers the closure and calls it.
|
|
19
|
+
import { RUST_BUFFER_SIZE, readRustBuffer, writeRustBufferPayload, writeRustCallStatusZero, } from "./marshal.js";
|
|
20
|
+
import { emitTrampoline as emitTrampolineModule } from "./trampoline.js";
|
|
21
|
+
const RCS_CODE_OFF = 0;
|
|
22
|
+
const RCS_ERROR_BUF_OFF = 8;
|
|
23
|
+
/** Lift one callback arg into the form the codegen closure expects: the
|
|
24
|
+
* receive-side mirror of `planArg` in `call.ts`.
|
|
25
|
+
*
|
|
26
|
+
* Scalars pass through. A `RustBuffer` becomes a `Uint8Array` and its wasm
|
|
27
|
+
* allocation is freed, Rust having handed ownership over. A `Callback` is a
|
|
28
|
+
* table index, wrapped into a JS callable. */
|
|
29
|
+
function liftCallbackArg(ctx, t, raw) {
|
|
30
|
+
if (t.tag === "RustBuffer") {
|
|
31
|
+
const ptr = raw;
|
|
32
|
+
const rb = readRustBuffer(ctx.memory, ptr);
|
|
33
|
+
const len = Number(rb.len);
|
|
34
|
+
const cap = Number(rb.capacity);
|
|
35
|
+
const bytes = len > 0 ? ctx.memory.readBytes(rb.dataPtr, len) : new Uint8Array(0);
|
|
36
|
+
if (cap > 0 && rb.dataPtr !== 0) {
|
|
37
|
+
ctx.free(rb.dataPtr, cap, 1);
|
|
38
|
+
}
|
|
39
|
+
return bytes;
|
|
40
|
+
}
|
|
41
|
+
if (t.tag === "Callback") {
|
|
42
|
+
return wrapWasmCallback(ctx, t.name, raw);
|
|
43
|
+
}
|
|
44
|
+
return raw;
|
|
45
|
+
}
|
|
46
|
+
/** Wrap a function-table index into a JS callable that lowers its arguments
|
|
47
|
+
* per `def.args` and dispatches through `__indirect_function_table`, the way
|
|
48
|
+
* `call_indirect` would. */
|
|
49
|
+
function wrapWasmCallback(ctx, name, slotIdx) {
|
|
50
|
+
const callbackDefs = ctx.callbackDefs;
|
|
51
|
+
const structs = ctx.structs;
|
|
52
|
+
const table = ctx.table;
|
|
53
|
+
if (!callbackDefs || !structs || !table) {
|
|
54
|
+
throw new Error("wrapWasmCallback: registration context not installed; call setRegistrationContext()");
|
|
55
|
+
}
|
|
56
|
+
const def = callbackDefs.get(name);
|
|
57
|
+
if (!def) {
|
|
58
|
+
throw new Error(`wrapWasmCallback: callback shape "${name}" not registered`);
|
|
59
|
+
}
|
|
60
|
+
const target = table.get(slotIdx);
|
|
61
|
+
if (typeof target !== "function") {
|
|
62
|
+
throw new Error(`wrapWasmCallback: __indirect_function_table[${slotIdx}] is not a function`);
|
|
63
|
+
}
|
|
64
|
+
// No completion callback lifted this way sets either flag. Bail rather
|
|
65
|
+
// than silently produce wrong wasm args if one ever does.
|
|
66
|
+
if (def.outReturn || def.hasRustCallStatus) {
|
|
67
|
+
throw new Error(`wrapWasmCallback: callback shape "${name}" with outReturn/hasRustCallStatus not yet supported`);
|
|
68
|
+
}
|
|
69
|
+
const argTypes = def.args;
|
|
70
|
+
const memory = ctx.memory;
|
|
71
|
+
const alloc = ctx.alloc;
|
|
72
|
+
const free = ctx.free;
|
|
73
|
+
return (...userArgs) => {
|
|
74
|
+
// Freed after the call. Inner allocations, such as RustBuffer payloads,
|
|
75
|
+
// pass to Rust and are not.
|
|
76
|
+
const outerAllocs = [];
|
|
77
|
+
const wasmArgs = [];
|
|
78
|
+
try {
|
|
79
|
+
for (let i = 0; i < argTypes.length; i++) {
|
|
80
|
+
const t = argTypes[i];
|
|
81
|
+
const v = userArgs[i];
|
|
82
|
+
wasmArgs.push(lowerCallbackArg(memory, alloc, structs, t, v, outerAllocs));
|
|
83
|
+
}
|
|
84
|
+
return target(...wasmArgs);
|
|
85
|
+
}
|
|
86
|
+
finally {
|
|
87
|
+
for (const a of outerAllocs)
|
|
88
|
+
free(a.ptr, a.size, a.align);
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
function lowerCallbackArg(memory, alloc, structs, t, v, outerAllocs) {
|
|
93
|
+
switch (t.tag) {
|
|
94
|
+
case "UInt8":
|
|
95
|
+
case "Int8":
|
|
96
|
+
case "UInt16":
|
|
97
|
+
case "Int16":
|
|
98
|
+
case "UInt32":
|
|
99
|
+
case "Int32":
|
|
100
|
+
case "VoidPointer":
|
|
101
|
+
case "Callback":
|
|
102
|
+
case "Reference":
|
|
103
|
+
case "MutReference":
|
|
104
|
+
return v | 0;
|
|
105
|
+
case "UInt64":
|
|
106
|
+
case "Int64":
|
|
107
|
+
case "Handle":
|
|
108
|
+
return typeof v === "bigint" ? v : BigInt(v);
|
|
109
|
+
case "Float32":
|
|
110
|
+
case "Float64":
|
|
111
|
+
return v;
|
|
112
|
+
case "RustBuffer": {
|
|
113
|
+
// Bytes are handed to Rust, so don't free them here.
|
|
114
|
+
const rbPtr = alloc(RUST_BUFFER_SIZE, 8);
|
|
115
|
+
outerAllocs.push({ ptr: rbPtr, size: RUST_BUFFER_SIZE, align: 8 });
|
|
116
|
+
writeRustBufferPayload(memory, alloc, rbPtr, v);
|
|
117
|
+
return rbPtr;
|
|
118
|
+
}
|
|
119
|
+
case "Struct": {
|
|
120
|
+
const layout = structs.get(t.name);
|
|
121
|
+
if (!layout) {
|
|
122
|
+
throw new Error(`lowerCallbackArg: struct "${t.name}" not registered`);
|
|
123
|
+
}
|
|
124
|
+
const ptr = alloc(layout.size, 8);
|
|
125
|
+
outerAllocs.push({ ptr, size: layout.size, align: 8 });
|
|
126
|
+
for (const f of layout.fields) {
|
|
127
|
+
const fieldVal = v[f.name];
|
|
128
|
+
switch (f.type.tag) {
|
|
129
|
+
case "RustCallStatus":
|
|
130
|
+
writeStatusFromResult(memory, alloc, ptr + f.offset, fieldVal);
|
|
131
|
+
break;
|
|
132
|
+
case "RustBuffer":
|
|
133
|
+
writeRustBufferPayload(memory, alloc, ptr + f.offset, fieldVal);
|
|
134
|
+
break;
|
|
135
|
+
default:
|
|
136
|
+
f.shape.write(memory, ptr + f.offset, fieldVal);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return ptr;
|
|
140
|
+
}
|
|
141
|
+
default:
|
|
142
|
+
throw new Error(`lowerCallbackArg: type ${t.tag} not yet supported`);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
/** Write a lowered return value to the pointer Rust handed us: `planRet` in
|
|
146
|
+
* `call.ts`, in the lowering direction. */
|
|
147
|
+
function writeReturnValue(memory, alloc, ptr, ret, value,
|
|
148
|
+
/** Optional registration context, required when `ret.tag === "Struct"`
|
|
149
|
+
* (or when a struct field is `Callback`-typed). The dispatcher passes
|
|
150
|
+
* this through from `makeDispatchRoute`. */
|
|
151
|
+
ctx) {
|
|
152
|
+
switch (ret.tag) {
|
|
153
|
+
case "Void":
|
|
154
|
+
return;
|
|
155
|
+
case "UInt8":
|
|
156
|
+
case "Int8":
|
|
157
|
+
memory.writeU8(ptr, value | 0);
|
|
158
|
+
return;
|
|
159
|
+
case "UInt16":
|
|
160
|
+
case "Int16":
|
|
161
|
+
case "UInt32":
|
|
162
|
+
case "Int32":
|
|
163
|
+
case "VoidPointer":
|
|
164
|
+
case "Callback":
|
|
165
|
+
case "Reference":
|
|
166
|
+
case "MutReference":
|
|
167
|
+
memory.writeU32(ptr, value | 0);
|
|
168
|
+
return;
|
|
169
|
+
case "UInt64":
|
|
170
|
+
case "Int64":
|
|
171
|
+
case "Handle":
|
|
172
|
+
memory.writeU64(ptr, typeof value === "bigint" ? value : BigInt(value));
|
|
173
|
+
return;
|
|
174
|
+
case "Float32":
|
|
175
|
+
memory.writeF32(ptr, value);
|
|
176
|
+
return;
|
|
177
|
+
case "Float64":
|
|
178
|
+
memory.writeF64(ptr, value);
|
|
179
|
+
return;
|
|
180
|
+
case "RustBuffer":
|
|
181
|
+
// `value` is a `Uint8Array` (UniffiByteArray) — round-trip through
|
|
182
|
+
// wasm memory the same way `planArg.RustBuffer` does on the lower
|
|
183
|
+
// path, so Rust can reclaim it via `Vec::from_raw_parts`.
|
|
184
|
+
writeRustBufferPayload(memory, alloc, ptr, value);
|
|
185
|
+
return;
|
|
186
|
+
case "Struct": {
|
|
187
|
+
if (!ctx) {
|
|
188
|
+
throw new Error(`writeReturnValue: Struct return ("${ret.name}") requires a registration context`);
|
|
189
|
+
}
|
|
190
|
+
const layout = ctx.structs.get(ret.name);
|
|
191
|
+
if (!layout) {
|
|
192
|
+
throw new Error(`writeReturnValue: struct "${ret.name}" not registered`);
|
|
193
|
+
}
|
|
194
|
+
// Walk the struct fields in declaration order, writing each at its
|
|
195
|
+
// computed offset. `Callback`-typed fields need the JS function
|
|
196
|
+
// installed as a wasm callback (so Rust receives a function-table
|
|
197
|
+
// index it can `call_indirect` on). `RustBuffer` fields ship their
|
|
198
|
+
// payload bytes through wasm memory and transfer ownership to Rust.
|
|
199
|
+
// Other field types are handled by the precomputed `f.shape.write`.
|
|
200
|
+
for (const f of layout.fields) {
|
|
201
|
+
const fieldVal = value[f.name];
|
|
202
|
+
switch (f.type.tag) {
|
|
203
|
+
case "Callback": {
|
|
204
|
+
const def = ctx.callbackDefs.get(f.type.name);
|
|
205
|
+
if (!def) {
|
|
206
|
+
throw new Error(`writeReturnValue: callback shape "${f.type.name}" not registered (in struct "${ret.name}")`);
|
|
207
|
+
}
|
|
208
|
+
const slot = ctx.installCallback(fieldVal, def);
|
|
209
|
+
memory.writeU32(ptr + f.offset, slot);
|
|
210
|
+
break;
|
|
211
|
+
}
|
|
212
|
+
case "RustBuffer":
|
|
213
|
+
writeRustBufferPayload(memory, alloc, ptr + f.offset, fieldVal);
|
|
214
|
+
break;
|
|
215
|
+
default:
|
|
216
|
+
f.shape.write(memory, ptr + f.offset, fieldVal);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
default:
|
|
222
|
+
throw new Error(`writeReturnValue: ret type ${ret.tag} not supported`);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
/** Write a `UniffiRustCallStatus` (32 bytes: i8 code + RustBuffer) to wasm
|
|
226
|
+
* memory. Empty error → success path. */
|
|
227
|
+
function writeStatusFromResult(memory, alloc, ptr, result) {
|
|
228
|
+
const code = (result?.code ?? 0) | 0;
|
|
229
|
+
if (code === 0) {
|
|
230
|
+
writeRustCallStatusZero(memory, ptr);
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
memory.writeU8(ptr + RCS_CODE_OFF, code);
|
|
234
|
+
const errorBuf = result?.errorBuf ?? EMPTY_BYTES;
|
|
235
|
+
writeRustBufferPayload(memory, alloc, ptr + RCS_ERROR_BUF_OFF, errorBuf);
|
|
236
|
+
}
|
|
237
|
+
const EMPTY_BYTES = new Uint8Array(0);
|
|
238
|
+
const TAG_I32 = 0;
|
|
239
|
+
const TAG_I64 = 1;
|
|
240
|
+
const TAG_F32 = 2;
|
|
241
|
+
const TAG_F64 = 3;
|
|
242
|
+
function tagFor(t) {
|
|
243
|
+
switch (t.tag) {
|
|
244
|
+
case "UInt64":
|
|
245
|
+
case "Int64":
|
|
246
|
+
// UniFFI handles are u64 on every platform, including wasm32. Lowering
|
|
247
|
+
// them as i32 here would emit a trampoline whose `call_indirect`
|
|
248
|
+
// signature didn't match Rust's `extern "C" fn(handle: u64, ...)` —
|
|
249
|
+
// the wasm runtime then throws "null function or function signature
|
|
250
|
+
// mismatch" at the first poll.
|
|
251
|
+
case "Handle":
|
|
252
|
+
return TAG_I64;
|
|
253
|
+
case "Float32":
|
|
254
|
+
return TAG_F32;
|
|
255
|
+
case "Float64":
|
|
256
|
+
return TAG_F64;
|
|
257
|
+
default:
|
|
258
|
+
// All pointer-sized and small-integer FFI types lower to i32 in the
|
|
259
|
+
// wasm ABI. (Void is invalid here — only used as a return type and
|
|
260
|
+
// handled separately by `signatureKey`/`buildDescriptor`.)
|
|
261
|
+
return TAG_I32;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* Per-instance dispatch table. `module.ts` owns one of these and routes the
|
|
266
|
+
* `__ubrn_dispatch` import through `dispatch`.
|
|
267
|
+
*/
|
|
268
|
+
export class CallbackTable {
|
|
269
|
+
memory;
|
|
270
|
+
hostExports;
|
|
271
|
+
compileSync;
|
|
272
|
+
shapes = new Map();
|
|
273
|
+
shapesByShapeId = [];
|
|
274
|
+
/**
|
|
275
|
+
* Shapes that bypass the registry-by-handle path. The `RustFutureContinu-
|
|
276
|
+
* ationCallback` shape lives here: its first argument is a u64 cookie, not
|
|
277
|
+
* a UniFFI registry handle, so the per-shape callback owns its own routing
|
|
278
|
+
* (e.g. the FutureRegistry's cookie -> resolver map).
|
|
279
|
+
*/
|
|
280
|
+
continuationShapes = new Map();
|
|
281
|
+
/** Optional registration context: callback shape defs + compiled struct
|
|
282
|
+
* layouts. Set by `module.ts` after `registerSync()` so `makeDispatchRoute`
|
|
283
|
+
* can resolve `Callback`-typed args (function-table indices) into JS
|
|
284
|
+
* callables that re-lower their args and dispatch through the indirect
|
|
285
|
+
* function table. */
|
|
286
|
+
registrationContext;
|
|
287
|
+
constructor(memory, hostExports,
|
|
288
|
+
/** Async compilation is not implemented; `false` is reserved for it. */
|
|
289
|
+
compileSync = true) {
|
|
290
|
+
this.memory = memory;
|
|
291
|
+
this.hostExports = hostExports;
|
|
292
|
+
this.compileSync = compileSync;
|
|
293
|
+
}
|
|
294
|
+
setRegistrationContext(ctx) {
|
|
295
|
+
this.registrationContext = ctx;
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* Implements `env.__ubrn_dispatch`. Trampolines prepend their shape id and
|
|
299
|
+
* forward everything else verbatim.
|
|
300
|
+
*
|
|
301
|
+
* On the registry path the host's first argument is the handle, per the
|
|
302
|
+
* UniFFI vtable convention; it is stripped before calling the closure.
|
|
303
|
+
*
|
|
304
|
+
* For shapes registered via `registerContinuationShape` (e.g. the future
|
|
305
|
+
* continuation callback) we forward all args verbatim — `args[0]` is a
|
|
306
|
+
* cookie, not a handle, and the caller owns the lookup.
|
|
307
|
+
*/
|
|
308
|
+
dispatch = (shapeId, ...args) => {
|
|
309
|
+
const continuationFn = this.continuationShapes.get(shapeId);
|
|
310
|
+
if (continuationFn) {
|
|
311
|
+
return continuationFn(...args);
|
|
312
|
+
}
|
|
313
|
+
const cache = this.shapesByShapeId[shapeId];
|
|
314
|
+
if (!cache) {
|
|
315
|
+
throw new Error(`__ubrn_dispatch: unknown shape ${shapeId}`);
|
|
316
|
+
}
|
|
317
|
+
// The trampoline forwards the handle in whatever wasm type the shape
|
|
318
|
+
// declares — a `Handle`/u64 arrives as a bigint, everything else as a
|
|
319
|
+
// number. `registry` is keyed by the number `register()` handed out, so
|
|
320
|
+
// normalise before looking up.
|
|
321
|
+
const handle = Number(args[0]);
|
|
322
|
+
const cb = cache.registry.get(handle);
|
|
323
|
+
if (!cb) {
|
|
324
|
+
throw new Error(`__ubrn_dispatch: unknown handle ${handle} for shape ${shapeId}`);
|
|
325
|
+
}
|
|
326
|
+
return cb(...args.slice(1));
|
|
327
|
+
};
|
|
328
|
+
/**
|
|
329
|
+
* Mark `shapeId` as a "continuation" shape — when the trampoline fires for
|
|
330
|
+
* that shape we route directly to `fn(...args)` rather than going through
|
|
331
|
+
* the registry-by-handle lookup. Used by `FutureRegistry`.
|
|
332
|
+
*/
|
|
333
|
+
registerContinuationShape(shapeId, fn) {
|
|
334
|
+
this.continuationShapes.set(shapeId, fn);
|
|
335
|
+
}
|
|
336
|
+
// Slots for closures installed directly rather than registered against a
|
|
337
|
+
// shape: `planArg`'s `Callback(name)` args and `Callback`-typed vtable
|
|
338
|
+
// fields. Each distinct (closure, signature) pair takes its own shape and
|
|
339
|
+
// table slot. That stays bounded because codegen builds each callback
|
|
340
|
+
// interface's vtable once at module scope and carries instance identity in
|
|
341
|
+
// the handle argument, so an interface costs N + 2 (clone, free) shapes
|
|
342
|
+
// however many instances exist.
|
|
343
|
+
//
|
|
344
|
+
// Keyed by signature as well as identity: one function installed for two
|
|
345
|
+
// signatures needs two slots, or Rust's `call_indirect` traps.
|
|
346
|
+
fnSlotCache = new WeakMap();
|
|
347
|
+
installCallbackFunction(fn, def) {
|
|
348
|
+
const sigKey = this.signatureKey(def);
|
|
349
|
+
let bySig = this.fnSlotCache.get(fn);
|
|
350
|
+
const cached = bySig?.get(sigKey);
|
|
351
|
+
if (cached !== undefined)
|
|
352
|
+
return cached;
|
|
353
|
+
const shapeId = this.shapesByShapeId.length;
|
|
354
|
+
const wasmBytes = this.compileTrampoline(shapeId, def);
|
|
355
|
+
const trampolineModule = new WebAssembly.Module(wasmBytes);
|
|
356
|
+
const instance = new WebAssembly.Instance(trampolineModule, {
|
|
357
|
+
env: { __ubrn_dispatch: this.dispatch },
|
|
358
|
+
});
|
|
359
|
+
const trampoline = instance.exports.trampoline;
|
|
360
|
+
if (typeof trampoline !== "function") {
|
|
361
|
+
throw new Error("emitted trampoline module did not export a 'trampoline' function");
|
|
362
|
+
}
|
|
363
|
+
const cache = {
|
|
364
|
+
signature: sigKey,
|
|
365
|
+
shapeId,
|
|
366
|
+
trampoline,
|
|
367
|
+
registry: new Map(),
|
|
368
|
+
nextHandle: 1,
|
|
369
|
+
};
|
|
370
|
+
this.shapesByShapeId.push(cache);
|
|
371
|
+
// Vtable methods on the codegen side return a `UniffiResult`; their
|
|
372
|
+
// wasm-level signature however returns void and takes trailing
|
|
373
|
+
// `out_ret` / `out_status` pointer args. Wrap the user closure so the
|
|
374
|
+
// dispatcher unwraps the result and writes it back through those
|
|
375
|
+
// pointers. Free/clone (no `outReturn`/`hasRustCallStatus`) and the
|
|
376
|
+
// future continuation route through unchanged.
|
|
377
|
+
const route = this.makeDispatchRoute(fn, def);
|
|
378
|
+
// Routed through the continuation path so all wasm args (including the
|
|
379
|
+
// u64 instance handle in vtable methods) are forwarded verbatim — the JS
|
|
380
|
+
// closure does its own handle-to-instance lift.
|
|
381
|
+
this.continuationShapes.set(shapeId, route);
|
|
382
|
+
const table = this.hostExports.__indirect_function_table;
|
|
383
|
+
if (!table) {
|
|
384
|
+
throw new Error("installCallbackFunction: host wasm does not export __indirect_function_table");
|
|
385
|
+
}
|
|
386
|
+
const slot = table.length;
|
|
387
|
+
table.grow(1);
|
|
388
|
+
table.set(slot, trampoline);
|
|
389
|
+
if (!bySig) {
|
|
390
|
+
bySig = new Map();
|
|
391
|
+
this.fnSlotCache.set(fn, bySig);
|
|
392
|
+
}
|
|
393
|
+
bySig.set(sigKey, slot);
|
|
394
|
+
return slot;
|
|
395
|
+
}
|
|
396
|
+
makeDispatchRoute(fn, def) {
|
|
397
|
+
const userArgCount = def.args.length;
|
|
398
|
+
const memory = this.memory;
|
|
399
|
+
const alloc = this.hostExports.__ubrn_alloc;
|
|
400
|
+
const free = this.hostExports.__ubrn_free;
|
|
401
|
+
const argTypes = def.args;
|
|
402
|
+
// Aggregate-typed args (RustBuffer) and function-pointer args
|
|
403
|
+
// (`Callback`) need a wasm-side lift before being handed to the user
|
|
404
|
+
// closure: the wasm ABI passes those as i32 pointers / table indices,
|
|
405
|
+
// but the codegen closure expects the lifted JS representation
|
|
406
|
+
// (`Uint8Array` / a callable wrapper).
|
|
407
|
+
const needsArgLift = argTypes.some((t) => t.tag === "RustBuffer" || t.tag === "Callback");
|
|
408
|
+
const ret = def.ret;
|
|
409
|
+
const outReturn = def.outReturn;
|
|
410
|
+
const hasStatus = def.hasRustCallStatus;
|
|
411
|
+
if (!outReturn && !hasStatus && !needsArgLift) {
|
|
412
|
+
// Direct passthrough — free/clone, the future continuation, etc.
|
|
413
|
+
return fn;
|
|
414
|
+
}
|
|
415
|
+
const installCallback = (cbFn, cbDef) => this.installCallbackFunction(cbFn, cbDef);
|
|
416
|
+
const writeRetCtx = this.registrationContext
|
|
417
|
+
? {
|
|
418
|
+
structs: this.registrationContext.structs,
|
|
419
|
+
callbackDefs: this.registrationContext.callbackDefs,
|
|
420
|
+
installCallback,
|
|
421
|
+
}
|
|
422
|
+
: undefined;
|
|
423
|
+
const liftCtx = {
|
|
424
|
+
memory,
|
|
425
|
+
alloc,
|
|
426
|
+
free,
|
|
427
|
+
table: this.hostExports.__indirect_function_table,
|
|
428
|
+
callbackDefs: this.registrationContext?.callbackDefs,
|
|
429
|
+
structs: this.registrationContext?.structs,
|
|
430
|
+
};
|
|
431
|
+
// `hasStatus` also decides where the FFI return value lives: sync vtable
|
|
432
|
+
// methods wrap it in a `UniffiResult` (`result.pointee`), async ones
|
|
433
|
+
// return it directly.
|
|
434
|
+
return (...wasmArgs) => {
|
|
435
|
+
let idx = userArgCount;
|
|
436
|
+
const outRetPtr = outReturn ? wasmArgs[idx++] : -1;
|
|
437
|
+
const outStatusPtr = hasStatus ? wasmArgs[idx++] : -1;
|
|
438
|
+
const userArgs = needsArgLift
|
|
439
|
+
? argTypes.map((t, i) => liftCallbackArg(liftCtx, t, wasmArgs[i]))
|
|
440
|
+
: wasmArgs.slice(0, userArgCount);
|
|
441
|
+
const result = fn(...userArgs);
|
|
442
|
+
const code = hasStatus ? (result?.code ?? 0) | 0 : 0;
|
|
443
|
+
if (outRetPtr >= 0 && code === 0) {
|
|
444
|
+
const retValue = hasStatus ? result?.pointee : result;
|
|
445
|
+
writeReturnValue(memory, alloc, outRetPtr, ret, retValue, writeRetCtx);
|
|
446
|
+
}
|
|
447
|
+
if (outStatusPtr >= 0) {
|
|
448
|
+
writeStatusFromResult(memory, alloc, outStatusPtr, result);
|
|
449
|
+
}
|
|
450
|
+
};
|
|
451
|
+
}
|
|
452
|
+
/**
|
|
453
|
+
* Define (or look up, if already defined) the trampoline for a callback
|
|
454
|
+
* shape. Returns the shape id, which is the index callers should pass to
|
|
455
|
+
* `register`/`installAt`.
|
|
456
|
+
*/
|
|
457
|
+
defineShape(_name, def) {
|
|
458
|
+
const key = this.signatureKey(def);
|
|
459
|
+
const existing = this.shapes.get(key);
|
|
460
|
+
if (existing) {
|
|
461
|
+
return existing.shapeId;
|
|
462
|
+
}
|
|
463
|
+
const shapeId = this.shapesByShapeId.length;
|
|
464
|
+
const wasmBytes = this.compileTrampoline(shapeId, def);
|
|
465
|
+
if (!this.compileSync) {
|
|
466
|
+
throw new Error("Async trampoline compilation not yet supported; pass compileSync=true");
|
|
467
|
+
}
|
|
468
|
+
const trampolineModule = new WebAssembly.Module(wasmBytes);
|
|
469
|
+
const instance = new WebAssembly.Instance(trampolineModule, {
|
|
470
|
+
env: { __ubrn_dispatch: this.dispatch },
|
|
471
|
+
});
|
|
472
|
+
const trampoline = instance.exports.trampoline;
|
|
473
|
+
if (typeof trampoline !== "function") {
|
|
474
|
+
throw new Error("emitted trampoline module did not export a 'trampoline' function");
|
|
475
|
+
}
|
|
476
|
+
const cache = {
|
|
477
|
+
signature: key,
|
|
478
|
+
shapeId,
|
|
479
|
+
trampoline,
|
|
480
|
+
registry: new Map(),
|
|
481
|
+
// Handles start at 1 so a caller can reliably distinguish "no callback"
|
|
482
|
+
// (0) from "registered". The host's `call_indirect` will use whatever
|
|
483
|
+
// handle the dispatcher gives it.
|
|
484
|
+
nextHandle: 1,
|
|
485
|
+
};
|
|
486
|
+
this.shapes.set(key, cache);
|
|
487
|
+
this.shapesByShapeId.push(cache);
|
|
488
|
+
return shapeId;
|
|
489
|
+
}
|
|
490
|
+
/** Register a JS closure for `def`'s shape. Returns the handle. */
|
|
491
|
+
register(name, fn, def) {
|
|
492
|
+
const shapeId = this.defineShape(name, def);
|
|
493
|
+
const cache = this.shapesByShapeId[shapeId];
|
|
494
|
+
const handle = cache.nextHandle++;
|
|
495
|
+
cache.registry.set(handle, fn);
|
|
496
|
+
return handle;
|
|
497
|
+
}
|
|
498
|
+
/** Drop a previously registered callback. */
|
|
499
|
+
unregister(handle, def) {
|
|
500
|
+
const shapeId = this.shapeIdFor(def);
|
|
501
|
+
const cache = this.shapesByShapeId[shapeId];
|
|
502
|
+
cache.registry.delete(handle);
|
|
503
|
+
}
|
|
504
|
+
/** Number of live registrations for `def`'s shape. Used by tests and by
|
|
505
|
+
* the generated `free` vtable hook to verify callbacks are released. */
|
|
506
|
+
size(def) {
|
|
507
|
+
const shapeId = this.shapeIdFor(def);
|
|
508
|
+
return this.shapesByShapeId[shapeId].registry.size;
|
|
509
|
+
}
|
|
510
|
+
/**
|
|
511
|
+
* Install a shape's trampoline into the host's indirect function table at
|
|
512
|
+
* `tableIndex`. The host wasm calls into the trampoline via
|
|
513
|
+
* `call_indirect`, so this is how a JS callback becomes reachable from
|
|
514
|
+
* Rust.
|
|
515
|
+
*
|
|
516
|
+
* Note: many callbacks of the same *shape* share one trampoline, but each
|
|
517
|
+
* needs its own table slot because the host passes a fixed table index per
|
|
518
|
+
* Rust-side callback object.
|
|
519
|
+
*/
|
|
520
|
+
installAt(tableIndex, shapeId) {
|
|
521
|
+
const cache = this.shapesByShapeId[shapeId];
|
|
522
|
+
if (!cache) {
|
|
523
|
+
throw new Error(`installAt: shape ${shapeId} not defined`);
|
|
524
|
+
}
|
|
525
|
+
const table = this.hostExports.__indirect_function_table;
|
|
526
|
+
if (!table) {
|
|
527
|
+
throw new Error("installAt: host wasm does not export __indirect_function_table");
|
|
528
|
+
}
|
|
529
|
+
if (tableIndex >= table.length) {
|
|
530
|
+
table.grow(tableIndex - table.length + 1);
|
|
531
|
+
}
|
|
532
|
+
table.set(tableIndex, cache.trampoline);
|
|
533
|
+
}
|
|
534
|
+
shapeIdFor(def) {
|
|
535
|
+
const key = this.signatureKey(def);
|
|
536
|
+
const cache = this.shapes.get(key);
|
|
537
|
+
if (!cache) {
|
|
538
|
+
throw new Error("shape not defined; call defineShape first");
|
|
539
|
+
}
|
|
540
|
+
return cache.shapeId;
|
|
541
|
+
}
|
|
542
|
+
signatureKey(def) {
|
|
543
|
+
const tags = def.args.map((a) => tagFor(a));
|
|
544
|
+
const ret = def.ret.tag === "Void" ? "" : `:${tagFor(def.ret)}`;
|
|
545
|
+
return `${tags.join(",")}${ret}`;
|
|
546
|
+
}
|
|
547
|
+
/** Encode the trampoline's wasm-level signature and emit the wasm bytes
|
|
548
|
+
* for it via the JS-side encoder in `trampoline.ts`. The wasm-level
|
|
549
|
+
* params are `def.args` plus implicit i32 pointer args UniFFI tacks on
|
|
550
|
+
* when `outReturn` / `hasRustCallStatus` are set; for `outReturn` the
|
|
551
|
+
* return travels via the pointer, so the trampoline's wasm return is
|
|
552
|
+
* void regardless of `def.ret`. */
|
|
553
|
+
compileTrampoline(shapeId, def) {
|
|
554
|
+
const paramTags = def.args.map((a) => tagFor(a));
|
|
555
|
+
if (def.outReturn)
|
|
556
|
+
paramTags.push(TAG_I32); // out_ret pointer
|
|
557
|
+
if (def.hasRustCallStatus)
|
|
558
|
+
paramTags.push(TAG_I32); // out_status pointer
|
|
559
|
+
const returnTag = !def.outReturn && def.ret.tag !== "Void" ? tagFor(def.ret) : undefined;
|
|
560
|
+
return emitTrampolineModule(shapeId, paramTags, returnTag);
|
|
561
|
+
}
|
|
562
|
+
}
|