1 from bindingstypes import ConvInfo
4 def first_to_lower(string: str) -> str:
6 return first.lower() + string[1:]
14 def __init__(self, DEBUG: bool, target: Target, outdir: str, **kwargs):
16 self.struct_file_suffixes = {}
17 self.function_ptr_counter = 0
18 self.function_ptrs = {}
19 self.c_type_map = dict(
20 uint8_t = ['number', 'number', 'Uint8Array'],
21 uint16_t = ['number', 'number', 'Uint16Array'],
22 uint32_t = ['number', 'number', 'Uint32Array'],
23 uint64_t = ['bigint', 'bigint', 'BigUint64Array'],
25 self.java_type_map = dict(
28 self.java_hu_type_map = dict(
32 self.to_hu_conv_templates = dict(
33 ptr = 'const {var_name}_hu_conv: {human_type} = new {human_type}(null, {var_name});',
34 default = 'const {var_name}_hu_conv: {human_type} = new {human_type}(null, {var_name});',
37 self.bindings_header = """
38 import * as version from './version.mjs';
40 const imports: any = {};
43 var js_objs: Array<WeakRef<object>> = [];
44 var js_invoke: Function;
45 var getRandomValues: Function;
47 imports.wasi_snapshot_preview1 = {
48 "fd_write": (fd: number, iovec_array_ptr: number, iovec_array_len: number) => {
49 // This should generally only be used to print panic messages
50 console.log("FD_WRITE to " + fd + " in " + iovec_array_len + " chunks.");
51 const ptr_len_view = new Uint32Array(wasm.memory.buffer, iovec_array_ptr, iovec_array_len * 2);
52 for (var i = 0; i < iovec_array_len; i++) {
53 const bytes_view = new Uint8Array(wasm.memory.buffer, ptr_len_view[i*2], ptr_len_view[i*2+1]);
54 console.log(String.fromCharCode(...bytes_view));
58 "fd_close": (_fd: number) => {
59 // This is not generally called, but may be referenced in debug builds
60 console.log("wasi_snapshot_preview1:fd_close");
61 return 58; // Not Supported
63 "fd_seek": (_fd: number, _offset: bigint, _whence: number, _new_offset: number) => {
64 // This is not generally called, but may be referenced in debug builds
65 console.log("wasi_snapshot_preview1:fd_seek");
66 return 58; // Not Supported
68 "random_get": (buf_ptr: number, buf_len: number) => {
69 const buf = new Uint8Array(wasm.memory.buffer, buf_ptr, buf_len);
73 "environ_sizes_get": (environ_var_count_ptr: number, environ_len_ptr: number) => {
74 // This is called before fd_write to format + print panic messages
75 console.log("wasi_snapshot_preview1:environ_sizes_get");
76 const out_count_view = new Uint32Array(wasm.memory.buffer, environ_var_count_ptr, 1);
77 out_count_view[0] = 0;
78 const out_len_view = new Uint32Array(wasm.memory.buffer, environ_len_ptr, 1);
82 "environ_get": (environ_ptr: number, environ_buf_ptr: number) => {
83 // This is called before fd_write to format + print panic messages
84 console.log("wasi_snapshot_preview1:environ_get");
85 return 58; // Note supported - we said there were 0 environment entries!
88 console.log("wasi_snapshot_preview1:proc_exit");
93 let isWasmInitialized: boolean = false;
95 async function finishInitializeWasm(wasmInstance: WebAssembly.Instance) {
96 if (typeof crypto === "undefined") {
97 var crypto_import = (await import('crypto')).webcrypto;
98 getRandomValues = crypto_import.getRandomValues.bind(crypto_import);
100 getRandomValues = crypto.getRandomValues.bind(crypto);
103 wasm = wasmInstance.exports;
104 if (!wasm.test_bigint_pass_deadbeef0badf00d(BigInt("0xdeadbeef0badf00d"))) {
105 throw new Error(\"Currently need BigInt-as-u64 support, try ----experimental-wasm-bigint");
108 if (decodeString(wasm.TS_get_lib_version_string()) !== version.get_ldk_java_bindings_version())
109 throw new Error(\"Compiled LDK library and LDK class failes do not match\");
110 // Fetching the LDK versions from C also checks that the header and binaries match
111 const c_bindings_ver: number = wasm.TS_get_ldk_c_bindings_version();
112 const ldk_ver: number = wasm.TS_get_ldk_version();
113 if (c_bindings_ver == 0)
114 throw new Error(\"LDK version did not match the header we built against\");
116 throw new Error(\"LDK C bindings version did not match the header we built against\");
117 const c_bindings_version: string = decodeString(c_bindings_ver)
118 const ldk_version: string = decodeString(ldk_ver);
119 console.log(\"Loaded LDK-Java Bindings with LDK \" + ldk_version + \" and LDK-C-Bindings \" + c_bindings_version);
121 isWasmInitialized = true;
125 export async function initializeWasmFromUint8Array(wasmBinary: Uint8Array) {
126 imports.env["js_invoke_function"] = js_invoke;
127 const { instance: wasmInstance } = await WebAssembly.instantiate(wasmBinary, imports);
128 await finishInitializeWasm(wasmInstance);
132 export async function initializeWasmFetch(uri: string) {
133 const stream = fetch(uri);
134 imports.env["js_invoke_function"] = js_invoke;
135 const { instance: wasmInstance } = await WebAssembly.instantiateStreaming(stream, imports);
136 await finishInitializeWasm(wasmInstance);
139 self.bindings_header += """
142 const nextMultipleOfFour = (value: number) => {
143 return Math.ceil(value / 4) * 4;
147 export function encodeUint8Array (inputArray: Uint8Array): number {
148 const cArrayPointer = wasm.TS_malloc(inputArray.length + 4);
149 const arrayLengthView = new Uint32Array(wasm.memory.buffer, cArrayPointer, 1);
150 arrayLengthView[0] = inputArray.length;
151 const arrayMemoryView = new Uint8Array(wasm.memory.buffer, cArrayPointer + 4, inputArray.length);
152 arrayMemoryView.set(inputArray);
153 return cArrayPointer;
156 export function encodeUint32Array (inputArray: Uint32Array|Array<number>): number {
157 const cArrayPointer = wasm.TS_malloc((inputArray.length + 1) * 4);
158 const arrayMemoryView = new Uint32Array(wasm.memory.buffer, cArrayPointer, inputArray.length);
159 arrayMemoryView.set(inputArray, 1);
160 arrayMemoryView[0] = inputArray.length;
161 return cArrayPointer;
164 export function encodeUint64Array (inputArray: BigUint64Array|Array<bigint>): number {
165 const cArrayPointer = wasm.TS_malloc(inputArray.length * 8 + 1);
166 const arrayLengthView = new Uint32Array(wasm.memory.buffer, cArrayPointer, 1);
167 arrayLengthView[0] = inputArray.length;
168 const arrayMemoryView = new BigUint64Array(wasm.memory.buffer, cArrayPointer + 4, inputArray.length);
169 arrayMemoryView.set(inputArray);
170 return cArrayPointer;
174 export function check_arr_len(arr: Uint8Array, len: number): Uint8Array {
175 if (arr.length != len) { throw new Error("Expected array of length " + len + "got " + arr.length); }
180 export function getArrayLength(arrayPointer: number): number {
181 const arraySizeViewer = new Uint32Array(wasm.memory.buffer, arrayPointer, 1);
182 return arraySizeViewer[0];
185 export function decodeUint8Array (arrayPointer: number, free = true): Uint8Array {
186 const arraySize = getArrayLength(arrayPointer);
187 const actualArrayViewer = new Uint8Array(wasm.memory.buffer, arrayPointer + 4, arraySize);
188 // Clone the contents, TODO: In the future we should wrap the Viewer in a class that
189 // will free the underlying memory when it becomes unreachable instead of copying here.
190 // Note that doing so may have edge-case interactions with memory resizing (invalidating the buffer).
191 const actualArray = actualArrayViewer.slice(0, arraySize);
193 wasm.TS_free(arrayPointer);
197 const decodeUint32Array = (arrayPointer: number, free = true) => {
198 const arraySize = getArrayLength(arrayPointer);
199 const actualArrayViewer = new Uint32Array(
200 wasm.memory.buffer, // value
201 arrayPointer + 4, // offset (ignoring length bytes)
202 arraySize // uint32 count
204 // Clone the contents, TODO: In the future we should wrap the Viewer in a class that
205 // will free the underlying memory when it becomes unreachable instead of copying here.
206 const actualArray = actualArrayViewer.slice(0, arraySize);
208 wasm.TS_free(arrayPointer);
214 export function freeWasmMemory(pointer: number) { wasm.TS_free(pointer); }
217 export function getU32ArrayElem(arrayPointer: number, idx: number): number {
218 const actualArrayViewer = new Uint32Array(wasm.memory.buffer, arrayPointer + 4, idx + 1);
219 return actualArrayViewer[idx];
223 export function encodeString(str: string): number {
224 const charArray = new TextEncoder().encode(str);
225 return encodeUint8Array(charArray);
229 export function decodeString(stringPointer: number, free = true): string {
230 const arraySize = getArrayLength(stringPointer);
231 const memoryView = new Uint8Array(wasm.memory.buffer, stringPointer + 4, arraySize);
232 const result = new TextDecoder("utf-8").decode(memoryView);
235 wasm.TS_free(stringPointer);
242 self.bindings_header += """
244 export function getRemainingAllocationCount(): number {
245 return wasm.TS_allocs_remaining();
248 export function debugPrintRemainingAllocs() {
249 wasm.TS_print_leaks();
253 self.bindings_header += "\n/* @internal */ export function getRemainingAllocationCount(): number { return 0; }\n"
254 self.bindings_header += "/* @internal */ export function debugPrintRemainingAllocs() { }\n"
256 with open(outdir + "/index.mts", 'a') as index:
257 index.write("""import { initializeWasmFetch, initializeWasmFromUint8Array } from './bindings.mjs';
258 /** Initializes the WASM backend by calling `fetch()` on the given URI - Browser only */
259 export async function initializeWasmWebFetch(uri: string) {
260 await initializeWasmFetch(uri);
262 /** Initializes the WASM backend given a Uint8Array of the .wasm binary file - Browser or Node.JS */
263 export async function initializeWasmFromBinary(bin: Uint8Array) {
264 await initializeWasmFromUint8Array(bin);
269 self.bindings_version_file = """export function get_ldk_java_bindings_version(): String {
270 return "<git_version_ldk_garbagecollected>";
273 self.bindings_footer = ""
275 self.common_base = """
276 function freer(f: () => void) { f() }
277 const finalizer = new FinalizationRegistry(freer);
278 function get_freeer(ptr: number, free_fn: (ptr: number) => void) {
284 export default class CommonBase {
285 protected ptr: number;
286 protected ptrs_to: object[] = [];
287 protected constructor(ptr: number, free_fn: (ptr: number) => void) {
289 if (Number.isFinite(ptr) && ptr != 0){
290 finalizer.register(this, get_freeer(ptr, free_fn));
293 // In Java, protected means "any subclass can access fields on any other subclass'"
294 // In TypeScript, protected means "any subclass can access parent fields on instances of itself"
295 // To work around this, we add accessors for other instances' protected fields here.
296 protected static add_ref_from(holder: CommonBase, referent: object) {
297 holder.ptrs_to.push(referent);
299 protected static get_ptr_of(o: CommonBase) {
302 protected static set_null_skip_free(o: CommonBase) {
304 finalizer.unregister(o);
309 self.txout_defn = """export class TxOut extends CommonBase {
310 /** The script_pubkey in this output */
311 public script_pubkey: Uint8Array;
312 /** The value, in satoshis, of this output */
313 public value: bigint;
316 public constructor(_dummy: object, ptr: number) {
317 super(ptr, bindings.TxOut_free);
318 this.script_pubkey = bindings.decodeUint8Array(bindings.TxOut_get_script_pubkey(ptr));
319 this.value = bindings.TxOut_get_value(ptr);
321 public constructor_new(value: bigint, script_pubkey: Uint8Array): TxOut {
322 return new TxOut(null, bindings.TxOut_new(bindings.encodeUint8Array(script_pubkey), value));
325 self.obj_defined(["TxOut"], "structs")
327 self.c_file_pfx = """#include "js-wasm.h"
328 #include <stdatomic.h>
329 #include <lightning.h>
331 // These should be provided...somehow...
332 void *memset(void *s, int c, size_t n);
333 void *memcpy(void *dest, const void *src, size_t n);
334 int memcmp(const void *s1, const void *s2, size_t n);
336 extern void __attribute__((noreturn)) abort(void);
337 static inline void assert(bool expression) {
338 if (!expression) { abort(); }
341 uint32_t __attribute__((export_name("test_bigint_pass_deadbeef0badf00d"))) test_bigint_pass_deadbeef0badf00d(uint64_t val) {
342 return val == 0xdeadbeef0badf00dULL;
348 self.c_file_pfx += """
349 void *malloc(size_t size);
350 void free(void *ptr);
352 #define MALLOC(a, _) malloc(a)
353 #define do_MALLOC(a, _b, _c) malloc(a)
354 #define FREE(p) if ((unsigned long)(p) > 4096) { free(p); }
355 #define DO_ASSERT(a) (void)(a)
357 #define CHECK_ACCESS(p)
358 #define CHECK_INNER_FIELD_ACCESS_OR_NULL(v)
361 self.c_file_pfx += """
362 extern int snprintf(char *str, size_t size, const char *format, ...);
363 typedef int32_t ssize_t;
364 ssize_t write(int fd, const void *buf, size_t count);
365 #define DEBUG_PRINT(...) do { \\
366 char debug_str[1024]; \\
367 int s_len = snprintf(debug_str, 1023, __VA_ARGS__); \\
368 write(2, debug_str, s_len); \\
371 // Always run a, then assert it is true:
372 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
373 // Assert a is true or do nothing
374 #define CHECK(a) DO_ASSERT(a)
376 // Running a leak check across all the allocations and frees of the JDK is a mess,
377 // so instead we implement our own naive leak checker here, relying on the -wrap
378 // linker option to wrap malloc/calloc/realloc/free, tracking everyhing allocated
379 // and free'd in Rust or C across the generated bindings shared library.
382 typedef struct allocation {
383 struct allocation* next;
385 const char* struct_name;
388 static allocation* allocation_ll = NULL;
389 static allocation* freed_ll = NULL;
391 extern void* __real_malloc(size_t len);
392 extern void* __real_calloc(size_t nmemb, size_t len);
393 extern void* __real_aligned_alloc(size_t alignment, size_t size);
394 static void new_allocation(void* res, const char* struct_name, int lineno) {
395 allocation* new_alloc = __real_malloc(sizeof(allocation));
396 new_alloc->ptr = res;
397 new_alloc->struct_name = struct_name;
398 new_alloc->next = allocation_ll;
399 new_alloc->lineno = lineno;
400 allocation_ll = new_alloc;
402 static void* do_MALLOC(size_t len, const char* struct_name, int lineno) {
403 void* res = __real_malloc(len);
404 new_allocation(res, struct_name, lineno);
407 #define MALLOC(len, struct_name) do_MALLOC(len, struct_name, __LINE__)
409 void __real_free(void* ptr);
410 static void alloc_freed(void* ptr, int lineno) {
411 allocation* p = NULL;
412 allocation* it = allocation_ll;
413 while (it->ptr != ptr) {
414 p = it; it = it->next;
418 while (it && it->ptr != ptr) { p = it; it = it->next; }
420 DEBUG_PRINT("Tried to free unknown pointer %p at line %d.\\n", ptr, lineno);
422 DEBUG_PRINT("Tried to free unknown pointer %p at line %d.\\n Possibly double-free from %s, allocated on line %d.", ptr, lineno, it->struct_name, it->lineno);
427 if (p) { p->next = it->next; } else { allocation_ll = it->next; }
428 DO_ASSERT(it->ptr == ptr);
432 static void do_FREE(void* ptr, int lineno) {
433 if ((unsigned long)ptr <= 4096) return; // Rust loves to create pointers to the NULL page for dummys
434 alloc_freed(ptr, lineno);
437 #define FREE(ptr) do_FREE(ptr, __LINE__)
439 static void CHECK_ACCESS(const void* ptr) {
440 allocation* it = allocation_ll;
441 while (it->ptr != ptr) {
444 return; // addrsan should catch malloc-unknown and print more info than we have
448 #define CHECK_INNER_FIELD_ACCESS_OR_NULL(v) \\
449 if (v.is_owned && v.inner != NULL) { \\
450 const void *p = __unmangle_inner_ptr(v.inner); \\
456 void* __wrap_malloc(size_t len) {
457 void* res = __real_malloc(len);
458 new_allocation(res, "malloc call", 0);
461 void* __wrap_calloc(size_t nmemb, size_t len) {
462 void* res = __real_calloc(nmemb, len);
463 new_allocation(res, "calloc call", 0);
466 void* __wrap_aligned_alloc(size_t alignment, size_t size) {
467 void* res = __real_aligned_alloc(alignment, size);
468 new_allocation(res, "aligned_alloc call", 0);
471 void __wrap_free(void* ptr) {
472 if (ptr == NULL) return;
477 void* __real_realloc(void* ptr, size_t newlen);
478 void* __wrap_realloc(void* ptr, size_t len) {
479 if (ptr != NULL) alloc_freed(ptr, 0);
480 void* res = __real_realloc(ptr, len);
481 new_allocation(res, "realloc call", 0);
484 void __wrap_reallocarray(void* ptr, size_t new_sz) {
485 // Rust doesn't seem to use reallocarray currently
489 uint32_t __attribute__((export_name("TS_allocs_remaining"))) allocs_remaining() {
491 for (allocation* a = allocation_ll; a != NULL; a = a->next) {
496 void __attribute__((export_name("TS_print_leaks"))) print_leaks() {
497 for (allocation* a = allocation_ll; a != NULL; a = a->next) {
498 DEBUG_PRINT("%s %p remains. Allocated on line %d\\n", a->struct_name, a->ptr, a->lineno);
502 self.c_file_pfx = self.c_file_pfx + """
503 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
504 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
505 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
506 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
508 _Static_assert(sizeof(void*) == 4, "Pointers mut be 32 bits");
510 #define DECL_ARR_TYPE(ty, name) \\
511 struct name##array { \\
515 typedef struct name##array * name##Array; \\
516 static inline name##Array init_##name##Array(size_t arr_len, int lineno) { \\
517 name##Array arr = (name##Array)do_MALLOC(arr_len * sizeof(ty) + sizeof(uint32_t), #name" array init", lineno); \\
518 arr->arr_len = arr_len; \\
522 DECL_ARR_TYPE(int64_t, int64_t);
523 DECL_ARR_TYPE(int8_t, int8_t);
524 DECL_ARR_TYPE(uint32_t, uint32_t);
525 DECL_ARR_TYPE(void*, ptr);
526 DECL_ARR_TYPE(char, char);
527 typedef charArray jstring;
529 static inline jstring str_ref_to_ts(const char* chars, size_t len) {
530 charArray arr = init_charArray(len, __LINE__);
531 memcpy(arr->elems, chars, len);
534 static inline LDKStr str_ref_to_owned_c(const jstring str) {
535 char* newchars = MALLOC(str->arr_len + 1, "String chars");
536 memcpy(newchars, str->elems, str->arr_len);
537 newchars[str->arr_len] = 0;
541 .chars_is_owned = true
546 typedef bool jboolean;
548 uint32_t __attribute__((export_name("TS_malloc"))) TS_malloc(uint32_t size) {
549 return (uint32_t)MALLOC(size, "JS-Called malloc");
551 void __attribute__((export_name("TS_free"))) TS_free(uint32_t ptr) {
555 jstring __attribute__((export_name("TS_get_ldk_c_bindings_version"))) TS_get_ldk_c_bindings_version() {
556 const char *res = check_get_ldk_bindings_version();
557 if (res == NULL) return NULL;
558 return str_ref_to_ts(res, strlen(res));
560 jstring __attribute__((export_name("TS_get_ldk_version"))) get_ldk_version() {
561 const char *res = check_get_ldk_version();
562 if (res == NULL) return NULL;
563 return str_ref_to_ts(res, strlen(res));
568 self.c_version_file = """jstring __attribute__((export_name("TS_get_lib_version_string"))) TS_get_lib_version_string() {
569 return str_ref_to_ts("<git_version_ldk_garbagecollected>", strlen("<git_version_ldk_garbagecollected>"));
572 self.hu_struct_file_prefix = """
573 import CommonBase from './CommonBase.mjs';
574 import * as bindings from '../bindings.mjs'
577 self.util_fn_pfx = self.hu_struct_file_prefix + "\nexport class UtilMethods extends CommonBase {\n"
578 self.util_fn_sfx = "}"
579 self.c_fn_ty_pfx = ""
580 self.file_ext = ".mts"
581 self.ptr_c_ty = "uint32_t"
582 self.ptr_native_ty = "number"
583 self.result_c_ty = "uint32_t"
584 self.ptr_arr = "ptrArray"
585 self.is_arr_some_check = ("", " != 0")
586 self.get_native_arr_len_call = ("", "->arr_len")
588 def release_native_arr_ptr_call(self, ty_info, arr_var, arr_ptr_var):
590 def create_native_arr_call(self, arr_len, ty_info):
591 if ty_info.c_ty == "ptrArray":
592 assert ty_info.subty is not None and ty_info.subty.c_ty.endswith("Array")
593 return "init_" + ty_info.c_ty + "(" + arr_len + ", __LINE__)"
594 def set_native_arr_contents(self, arr_name, arr_len, ty_info):
595 if ty_info.c_ty == "int8_tArray":
596 return ("memcpy(" + arr_name + "->elems, ", ", " + arr_len + ")")
599 def get_native_arr_contents(self, arr_name, dest_name, arr_len, ty_info, copy):
600 if ty_info.c_ty == "int8_tArray":
602 return "memcpy(" + dest_name + ", " + arr_name + "->elems, " + arr_len + "); FREE(" + arr_name + ")"
603 if ty_info.c_ty == "ptrArray":
604 return "(void*) " + arr_name + "->elems /* XXX " + arr_name + " leaks */"
607 return arr_name + "->elems /* XXX " + arr_name + " leaks */"
608 def get_native_arr_elem(self, arr_name, idxc, ty_info):
609 assert False # Only called if above is None
610 def get_native_arr_ptr_call(self, ty_info):
611 if ty_info.subty is not None:
612 return "(" + ty_info.subty.c_ty + "*)(((uint8_t*)", ") + 4)"
613 return "(" + ty_info.c_ty + "*)(((uint8_t*)", ") + 4)"
614 def get_native_arr_entry_call(self, ty_info, arr_name, idxc, entry_access):
616 def cleanup_native_arr_ref_contents(self, arr_name, dest_name, arr_len, ty_info):
617 if ty_info.c_ty == "int8_tArray":
622 def map_hu_array_elems(self, arr_name, conv_name, arr_ty, elem_ty):
623 assert elem_ty.c_ty == "uint32_t" or elem_ty.c_ty.endswith("Array")
624 return arr_name + " != null ? " + arr_name + ".map(" + conv_name + " => " + elem_ty.from_hu_conv[0] + ") : null"
626 def str_ref_to_native_call(self, var_name, str_len):
627 return "str_ref_to_ts(" + var_name + ", " + str_len + ")"
628 def str_ref_to_c_call(self, var_name):
629 return "str_ref_to_owned_c(" + var_name + ")"
630 def str_to_hu_conv(self, var_name):
631 return "const " + var_name + "_conv: string = bindings.decodeString(" + var_name + ");"
632 def str_from_hu_conv(self, var_name):
633 return ("bindings.encodeString(" + var_name + ")", "")
635 def c_fn_name_define_pfx(self, fn_name, have_args):
636 return " __attribute__((export_name(\"TS_" + fn_name + "\"))) TS_" + fn_name + "("
641 def get_java_arr_len(self, arr_name):
642 return "bindings.getArrayLength(" + arr_name + ")"
643 def get_java_arr_elem(self, elem_ty, arr_name, idx):
644 if elem_ty.c_ty == "uint32_t" or elem_ty.c_ty == "uintptr_t" or elem_ty.c_ty.endswith("Array"):
645 return "bindings.getU32ArrayElem(" + arr_name + ", " + idx + ")"
648 def constr_hu_array(self, ty_info, arr_len):
649 return "new Array(" + arr_len + ").fill(null)"
650 def cleanup_converted_native_array(self, ty_info, arr_name):
651 return "bindings.freeWasmMemory(" + arr_name + ")"
653 def primitive_arr_from_hu(self, mapped_ty, fixed_len, arr_name):
655 if fixed_len is not None:
656 assert mapped_ty.c_ty == "int8_t"
657 inner = "bindings.check_arr_len(" + arr_name + ", " + fixed_len + ")"
658 if mapped_ty.c_ty.endswith("Array"):
659 return ("bindings.encodeUint32Array(" + inner + ")", "")
660 elif mapped_ty.c_ty == "uint8_t" or mapped_ty.c_ty == "int8_t":
661 return ("bindings.encodeUint8Array(" + inner + ")", "")
662 elif mapped_ty.c_ty == "uint32_t":
663 return ("bindings.encodeUint32Array(" + inner + ")", "")
664 elif mapped_ty.c_ty == "int64_t":
665 return ("bindings.encodeUint64Array(" + inner + ")", "")
667 print(mapped_ty.c_ty)
670 def primitive_arr_to_hu(self, mapped_ty, fixed_len, arr_name, conv_name):
671 assert mapped_ty.c_ty == "uint8_t" or mapped_ty.c_ty == "int8_t"
672 return "const " + conv_name + ": Uint8Array = bindings.decodeUint8Array(" + arr_name + ");"
674 def var_decl_statement(self, ty_string, var_name, statement):
675 return "const " + var_name + ": " + ty_string + " = " + statement
677 def java_arr_ty_str(self, elem_ty_str):
680 def for_n_in_range(self, n, minimum, maximum):
681 return "for (var " + n + " = " + minimum + "; " + n + " < " + maximum + "; " + n + "++) {"
682 def for_n_in_arr(self, n, arr_name, arr_elem_ty):
683 return (arr_name + ".forEach((" + n + ": " + arr_elem_ty.java_hu_ty + ") => { ", " })")
685 def get_ptr(self, var):
686 return "CommonBase.get_ptr_of(" + var + ")"
687 def set_null_skip_free(self, var):
688 return "CommonBase.set_null_skip_free(" + var + ");"
690 def add_ref(self, holder, referent):
691 return "CommonBase.add_ref_from(" + holder + ", " + referent + ")"
693 def obj_defined(self, struct_names, folder):
694 with open(self.outdir + "/index.mts", 'a') as index:
695 index.write(f"export * from './{folder}/{struct_names[0]}.mjs';\n")
696 with open(self.outdir + "/imports.mts.part", 'a') as imports:
697 imports.write(f"import {{ {', '.join(struct_names)} }} from '../{folder}/{struct_names[0]}.mjs';\n")
699 def native_c_unitary_enum_map(self, struct_name, variants, enum_doc_comment):
700 out_c = "static inline LDK" + struct_name + " LDK" + struct_name + "_from_js(int32_t ord) {\n"
701 out_c = out_c + "\tswitch (ord) {\n"
704 out_typescript_enum_fields = ""
706 for var, var_docs in variants:
707 out_c = out_c + "\t\tcase %d: return %s;\n" % (ord_v, var)
709 if var_docs is not None:
710 var_docs_repld = var_docs.replace("\n", "\n\t")
711 out_typescript_enum_fields += f"/**\n\t * {var_docs_repld}\n\t */\n"
712 out_typescript_enum_fields += f"\t{var},\n\t"
713 out_c = out_c + "\t}\n"
714 out_c = out_c + "\tabort();\n"
715 out_c = out_c + "}\n"
717 out_c = out_c + "static inline int32_t LDK" + struct_name + "_to_js(LDK" + struct_name + " val) {\n"
718 out_c = out_c + "\tswitch (val) {\n"
720 for var, _ in variants:
721 out_c = out_c + "\t\tcase " + var + ": return %d;\n" % ord_v
723 out_c = out_c + "\t\tdefault: abort();\n"
724 out_c = out_c + "\t}\n"
725 out_c = out_c + "}\n"
727 out_typescript = f"""
729 export enum {struct_name} {{
730 {out_typescript_enum_fields}
733 out_typescript_enum = f"export {{ {struct_name} }} from \"../bindings.mjs\";"
734 self.obj_defined([struct_name], "enums")
735 return (out_c, out_typescript_enum, out_typescript)
737 def c_unitary_enum_to_native_call(self, ty_info):
738 return (ty_info.rust_obj + "_to_js(", ")")
739 def native_unitary_enum_to_c_call(self, ty_info):
740 return (ty_info.rust_obj + "_from_js(", ")")
742 def native_c_map_trait(self, struct_name, field_var_conversions, flattened_field_var_conversions, field_function_lines, trait_doc_comment):
743 out_typescript_bindings = ""
744 super_instantiator = ""
745 bindings_instantiator = ""
746 pointer_to_adder = ""
747 impl_constructor_arguments = ""
748 for var in flattened_field_var_conversions:
749 if isinstance(var, ConvInfo):
750 impl_constructor_arguments += f", {var.arg_name}: {var.java_hu_ty}"
751 super_instantiator += first_to_lower(var.arg_name) + ", "
752 if var.from_hu_conv is not None:
753 bindings_instantiator += ", " + var.from_hu_conv[0]
754 if var.from_hu_conv[1] != "":
755 pointer_to_adder += "\t\t\t" + var.from_hu_conv[1] + ";\n"
757 bindings_instantiator += ", " + first_to_lower(var.arg_name)
759 bindings_instantiator += ", " + first_to_lower(var[1]) + ".bindings_instance"
760 super_instantiator += first_to_lower(var[1]) + "_impl, "
761 pointer_to_adder += "\t\timpl_holder.held.ptrs_to.push(" + first_to_lower(var[1]) + ");\n"
762 impl_constructor_arguments += f", {first_to_lower(var[1])}_impl: {var[0].replace('LDK', '')}Interface"
764 super_constructor_statements = ""
765 trait_constructor_arguments = ""
766 for var in field_var_conversions:
767 if isinstance(var, ConvInfo):
768 trait_constructor_arguments += ", " + var.arg_name
770 super_constructor_statements += "\t\tconst " + first_to_lower(var[1]) + " = " + var[1] + ".new_impl(" + super_instantiator + ");\n"
771 trait_constructor_arguments += ", " + first_to_lower(var[1]) + ".bindings_instance"
772 for suparg in var[2]:
773 if isinstance(suparg, ConvInfo):
774 trait_constructor_arguments += ", " + suparg.arg_name
776 trait_constructor_arguments += ", " + suparg[1]
778 # BUILD INTERFACE METHODS
779 out_java_interface = ""
780 out_interface_implementation_overrides = ""
782 for fn_line in field_function_lines:
783 java_method_descriptor = ""
784 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
785 out_java_interface += "\t/**" + fn_line.docs.replace("\n", "\n\t * ") + "\n\t */\n"
786 out_java_interface += "\t" + fn_line.fn_name + "("
787 out_interface_implementation_overrides += f"\t\t\t{fn_line.fn_name} ("
789 for idx, arg_conv_info in enumerate(fn_line.args_ty):
791 out_java_interface += ", "
792 out_interface_implementation_overrides += ", "
793 out_java_interface += f"{arg_conv_info.arg_name}: {arg_conv_info.java_hu_ty}"
794 out_interface_implementation_overrides += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
795 java_method_descriptor += arg_conv_info.java_fn_ty_arg
796 out_java_interface += f"): {fn_line.ret_ty_info.java_hu_ty};\n"
797 java_method_descriptor += ")" + fn_line.ret_ty_info.java_fn_ty_arg
798 java_methods.append((fn_line.fn_name, java_method_descriptor))
800 out_interface_implementation_overrides += f"): {fn_line.ret_ty_info.java_ty} {{\n"
802 for arg_info in fn_line.args_ty:
803 if arg_info.to_hu_conv is not None:
804 out_interface_implementation_overrides += "\t\t\t\t" + arg_info.to_hu_conv.replace("\n", "\n\t\t\t\t") + "\n"
806 if fn_line.ret_ty_info.java_ty != "void":
807 out_interface_implementation_overrides += "\t\t\t\tconst ret: " + fn_line.ret_ty_info.java_hu_ty + " = arg." + fn_line.fn_name + "("
809 out_interface_implementation_overrides += f"\t\t\t\targ." + fn_line.fn_name + "("
811 for idx, arg_info in enumerate(fn_line.args_ty):
813 out_interface_implementation_overrides += ", "
814 if arg_info.to_hu_conv_name is not None:
815 out_interface_implementation_overrides += arg_info.to_hu_conv_name
817 out_interface_implementation_overrides += arg_info.arg_name
819 out_interface_implementation_overrides += ");\n"
820 if fn_line.ret_ty_info.java_ty != "void":
821 if fn_line.ret_ty_info.from_hu_conv is not None:
822 out_interface_implementation_overrides += "\t\t\t\t" + f"const result: {fn_line.ret_ty_info.java_ty} = " + fn_line.ret_ty_info.from_hu_conv[0].replace("\n", "\n\t\t\t\t") + ";\n"
823 if fn_line.ret_ty_info.from_hu_conv[1] != "":
824 out_interface_implementation_overrides += "\t\t\t\t" + fn_line.ret_ty_info.from_hu_conv[1].replace("this", "impl_holder.held").replace("\n", "\n\t\t\t\t") + ";\n"
825 #if fn_line.ret_ty_info.rust_obj in result_types:
826 # XXX: We need to handle this in conversion logic so that its cross-language!
827 # Avoid double-free by breaking the result - we should learn to clone these and then we can be safe instead
828 # out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\tret.ptr = 0;\n"
829 out_interface_implementation_overrides += "\t\t\t\treturn result;\n"
831 out_interface_implementation_overrides += "\t\t\t\treturn ret;\n"
832 out_interface_implementation_overrides += f"\t\t\t}},\n"
834 formatted_trait_docs = trait_doc_comment.replace("\n", "\n * ")
835 out_typescript_human = f"""
836 {self.hu_struct_file_prefix}
838 /** An implementation of {struct_name.replace("LDK","")} */
839 export interface {struct_name.replace("LDK", "")}Interface {{
840 {out_java_interface}}}
842 class {struct_name}Holder {{
843 held: {struct_name.replace("LDK", "")};
847 * {formatted_trait_docs}
849 export class {struct_name.replace("LDK","")} extends CommonBase {{
851 public bindings_instance?: bindings.{struct_name};
854 constructor(_dummy: object, ptr: number) {{
855 super(ptr, bindings.{struct_name.replace("LDK","")}_free);
856 this.bindings_instance = null;
859 /** Creates a new instance of {struct_name.replace("LDK","")} from a given implementation */
860 public static new_impl(arg: {struct_name.replace("LDK", "")}Interface{impl_constructor_arguments}): {struct_name.replace("LDK", "")} {{
861 const impl_holder: {struct_name}Holder = new {struct_name}Holder();
862 let structImplementation = {{
863 {out_interface_implementation_overrides} }} as bindings.{struct_name};
864 {super_constructor_statements} const ptr: number = bindings.{struct_name}_new(structImplementation{bindings_instantiator});
866 impl_holder.held = new {struct_name.replace("LDK", "")}(null, ptr);
867 impl_holder.held.bindings_instance = structImplementation;
868 {pointer_to_adder} return impl_holder.held;
872 self.obj_defined([struct_name.replace("LDK", ""), struct_name.replace("LDK", "") + "Interface"], "structs")
874 out_typescript_bindings += "/* @internal */\nexport interface " + struct_name + " {\n"
876 for fn_line in field_function_lines:
877 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
878 out_typescript_bindings += f"\t{fn_line.fn_name} ("
880 for idx, arg_conv_info in enumerate(fn_line.args_ty):
882 out_typescript_bindings = out_typescript_bindings + ", "
883 out_typescript_bindings += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
885 out_typescript_bindings += f"): {fn_line.ret_ty_info.java_ty};\n"
887 out_typescript_bindings += "}\n\n"
889 out_typescript_bindings += f"/* @internal */\nexport function {struct_name}_new(impl: {struct_name}"
890 for var in flattened_field_var_conversions:
891 if isinstance(var, ConvInfo):
892 out_typescript_bindings += f", {var.arg_name}: {var.java_ty}"
894 out_typescript_bindings += f", {var[1]}: {var[0]}"
896 out_typescript_bindings += f"""): number {{
897 if(!isWasmInitialized) {{
898 throw new Error("initializeWasm() must be awaited first!");
900 var new_obj_idx = js_objs.length;
901 for (var i = 0; i < js_objs.length; i++) {{
902 if (js_objs[i] == null || js_objs[i] == undefined) {{ new_obj_idx = i; break; }}
904 js_objs[i] = new WeakRef(impl);
905 return wasm.TS_{struct_name}_new(i);
909 # Now that we've written out our java code (and created java_meths), generate C
910 out_c = "typedef struct " + struct_name + "_JCalls {\n"
911 out_c += "\tatomic_size_t refcnt;\n"
912 out_c += "\tuint32_t instance_ptr;\n"
913 for var in flattened_field_var_conversions:
914 if isinstance(var, ConvInfo):
915 # We're a regular ol' field
919 out_c = out_c + "\t" + var[0] + "_JCalls* " + var[1] + ";\n"
920 out_c = out_c + "} " + struct_name + "_JCalls;\n"
922 for fn_line in field_function_lines:
923 if fn_line.fn_name == "free":
924 out_c = out_c + "static void " + struct_name + "_JCalls_free(void* this_arg) {\n"
925 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
926 out_c = out_c + "\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n"
927 out_c = out_c + "\t\tFREE(j_calls);\n"
928 out_c = out_c + "\t}\n}\n"
930 for idx, fn_line in enumerate(field_function_lines):
931 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
932 assert fn_line.ret_ty_info.ty_info.get_full_rust_ty()[1] == ""
933 out_c = out_c + fn_line.ret_ty_info.ty_info.get_full_rust_ty()[0] + " " + fn_line.fn_name + "_" + struct_name + "_jcall("
934 if fn_line.self_is_const:
935 out_c = out_c + "const void* this_arg"
937 out_c = out_c + "void* this_arg"
939 for idx, arg in enumerate(fn_line.args_ty):
940 out_c = out_c + ", " + arg.ty_info.get_full_rust_ty()[0] + " " + arg.arg_name + arg.ty_info.get_full_rust_ty()[1]
942 out_c = out_c + ") {\n"
943 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
945 for arg_info in fn_line.args_ty:
946 if arg_info.ret_conv is not None:
947 out_c = out_c + "\t" + arg_info.ret_conv[0].replace('\n', '\n\t')
948 out_c = out_c + arg_info.arg_name
949 out_c = out_c + arg_info.ret_conv[1].replace('\n', '\n\t') + "\n"
951 if fn_line.ret_ty_info.c_ty.endswith("Array"):
952 out_c += "\t" + fn_line.ret_ty_info.c_ty + " ret = (" + fn_line.ret_ty_info.c_ty + ")"
953 out_c += "js_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
954 elif fn_line.ret_ty_info.java_ty == "void":
955 out_c = out_c + "\tjs_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
956 elif fn_line.ret_ty_info.java_hu_ty == "string":
957 out_c = out_c + "\tjstring ret = (jstring)js_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
958 elif not fn_line.ret_ty_info.passed_as_ptr:
959 out_c = out_c + "\treturn js_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
961 out_c = out_c + "\tuint32_t ret = js_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
963 self.function_ptrs[self.function_ptr_counter] = (struct_name, fn_line.fn_name)
964 self.function_ptr_counter += 1
966 for idx, arg_info in enumerate(fn_line.args_ty):
967 if arg_info.ret_conv is not None:
968 out_c = out_c + ", (uint32_t)" + arg_info.ret_conv_name
970 out_c = out_c + ", (uint32_t)" + arg_info.arg_name
971 out_c = out_c + ");\n"
972 if fn_line.ret_ty_info.arg_conv is not None:
973 out_c = out_c + "\t" + fn_line.ret_ty_info.arg_conv.replace("\n", "\n\t") + "\n\treturn " + fn_line.ret_ty_info.arg_conv_name + ";\n"
975 out_c = out_c + "}\n"
977 # Write out a clone function whether we need one or not, as we use them in moving to rust
978 out_c = out_c + "static void " + struct_name + "_JCalls_cloned(" + struct_name + "* new_obj) {\n"
979 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) new_obj->this_arg;\n"
980 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n"
981 for var in field_var_conversions:
982 if not isinstance(var, ConvInfo):
983 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->" + var[1] + "->refcnt, 1, memory_order_release);\n"
984 out_c = out_c + "}\n"
986 out_c = out_c + "static inline " + struct_name + " " + struct_name + "_init (JSValue o"
987 for var in flattened_field_var_conversions:
988 if isinstance(var, ConvInfo):
989 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
991 out_c = out_c + ", JSValue " + var[1]
992 out_c = out_c + ") {\n"
994 out_c = out_c + "\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n"
995 out_c = out_c + "\tatomic_init(&calls->refcnt, 1);\n"
996 out_c = out_c + "\tcalls->instance_ptr = o;\n"
998 for (fn_name, java_meth_descr) in java_meths:
999 if fn_name != "free" and fn_name != "cloned":
1000 out_c = out_c + "\tcalls->" + fn_name + "_meth = (*env)->GetMethodID(env, c, \"" + fn_name + "\", \"" + java_meth_descr + "\");\n"
1001 out_c = out_c + "\tCHECK(calls->" + fn_name + "_meth != NULL);\n"
1003 for var in flattened_field_var_conversions:
1004 if isinstance(var, ConvInfo) and var.arg_conv is not None:
1005 out_c = out_c + "\n\t" + var.arg_conv.replace("\n", "\n\t") +"\n"
1006 out_c = out_c + "\n\t" + struct_name + " ret = {\n"
1007 out_c = out_c + "\t\t.this_arg = (void*) calls,\n"
1008 for fn_line in field_function_lines:
1009 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
1010 out_c = out_c + "\t\t." + fn_line.fn_name + " = " + fn_line.fn_name + "_" + struct_name + "_jcall,\n"
1011 elif fn_line.fn_name == "free":
1012 out_c = out_c + "\t\t.free = " + struct_name + "_JCalls_free,\n"
1014 out_c = out_c + "\t\t.cloned = " + struct_name + "_JCalls_cloned,\n"
1015 for var in field_var_conversions:
1016 if isinstance(var, ConvInfo):
1017 if var.arg_conv_name is not None:
1018 out_c = out_c + "\t\t." + var.arg_name + " = " + var.arg_conv_name + ",\n"
1019 out_c = out_c + "\t\t.set_" + var.arg_name + " = NULL,\n"
1021 out_c = out_c + "\t\t." + var.var_name + " = " + var.var_name + ",\n"
1022 out_c = out_c + "\t\t.set_" + var.var_name + " = NULL,\n"
1024 out_c += "\t\t." + var[1] + " = " + var[0] + "_init(" + var[1]
1025 for suparg in var[2]:
1026 if isinstance(suparg, ConvInfo):
1027 out_c += ", " + suparg.arg_name
1029 out_c += ", " + suparg[1]
1031 out_c = out_c + "\t};\n"
1032 for var in flattened_field_var_conversions:
1033 if not isinstance(var, ConvInfo):
1034 out_c = out_c + "\tcalls->" + var[1] + " = ret." + var[1] + ".this_arg;\n"
1035 out_c = out_c + "\treturn ret;\n"
1036 out_c = out_c + "}\n"
1038 out_c = out_c + self.c_fn_ty_pfx + "long " + self.c_fn_name_define_pfx(struct_name + "_new", True) + "JSValue o"
1039 for var in flattened_field_var_conversions:
1040 if isinstance(var, ConvInfo):
1041 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
1043 out_c = out_c + ", JSValue " + var[1]
1044 out_c = out_c + ") {\n"
1045 out_c = out_c + "\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n"
1046 out_c = out_c + "\t*res_ptr = " + struct_name + "_init(o"
1047 for var in flattened_field_var_conversions:
1048 if isinstance(var, ConvInfo):
1049 out_c = out_c + ", " + var.arg_name
1051 out_c = out_c + ", " + var[1]
1052 out_c = out_c + ");\n"
1053 out_c = out_c + "\treturn (long)res_ptr;\n"
1054 out_c = out_c + "}\n"
1056 return (out_typescript_bindings, out_typescript_human, out_c)
1058 def trait_struct_inc_refcnt(self, ty_info):
1061 def map_complex_enum(self, struct_name, variant_list, camel_to_snake, enum_doc_comment):
1062 bindings_type = struct_name.replace("LDK", "")
1063 java_hu_type = struct_name.replace("LDK", "").replace("COption", "Option")
1069 out_java_enum += (self.hu_struct_file_prefix)
1071 java_hu_class = "/**\n * " + enum_doc_comment.replace("\n", "\n * ") + "\n */\n"
1072 java_hu_class += "export class " + java_hu_type + " extends CommonBase {\n"
1073 java_hu_class += "\tprotected constructor(_dummy: object, ptr: number) { super(ptr, bindings." + bindings_type + "_free); }\n"
1074 java_hu_class += "\t/* @internal */\n"
1075 java_hu_class += f"\tpublic static constr_from_ptr(ptr: number): {java_hu_type} {{\n"
1076 java_hu_class += f"\t\tconst raw_ty: number = bindings." + struct_name + "_ty_from_ptr(ptr);\n"
1077 out_c += self.c_fn_ty_pfx + "uint32_t" + self.c_fn_name_define_pfx(struct_name + "_ty_from_ptr", True) + self.ptr_c_ty + " ptr) {\n"
1078 out_c += "\t" + struct_name + " *obj = (" + struct_name + "*)(ptr & ~1);\n"
1079 out_c += "\tswitch(obj->tag) {\n"
1080 java_hu_class += "\t\tswitch (raw_ty) {\n"
1081 java_hu_subclasses = ""
1083 out_java += "/* @internal */\nexport class " + struct_name + " {\n"
1084 out_java += "\tprotected constructor() {}\n"
1086 for var in variant_list:
1087 java_hu_subclasses += "/** A " + java_hu_type + " of type " + var.var_name + " */\n"
1088 java_hu_subclasses += "export class " + java_hu_type + "_" + var.var_name + " extends " + java_hu_type + " {\n"
1089 java_hu_class += f"\t\t\tcase {var_idx}: "
1090 java_hu_class += "return new " + java_hu_type + "_" + var.var_name + "(ptr);\n"
1091 out_c += f"\t\tcase {struct_name}_{var.var_name}: return {var_idx};\n"
1093 for idx, (field_ty, field_docs) in enumerate(var.fields):
1094 if field_docs is not None:
1095 java_hu_subclasses += "\t/**\n\t * " + field_docs.replace("\n", "\n\t * ") + "\n\t */\n"
1096 java_hu_subclasses += "\tpublic " + field_ty.arg_name + f": {field_ty.java_hu_ty};\n"
1097 if field_ty.to_hu_conv is not None:
1098 hu_conv_body += f"\t\tconst {field_ty.arg_name}: {field_ty.java_ty} = bindings.{struct_name}_{var.var_name}_get_{field_ty.arg_name}(ptr);\n"
1099 hu_conv_body += f"\t\t" + field_ty.to_hu_conv.replace("\n", "\n\t\t\t") + "\n"
1100 hu_conv_body += f"\t\tthis." + field_ty.arg_name + " = " + field_ty.to_hu_conv_name + ";\n"
1102 hu_conv_body += f"\t\tthis.{field_ty.arg_name} = bindings.{struct_name}_{var.var_name}_get_{field_ty.arg_name}(ptr);\n"
1103 java_hu_subclasses += "\t/* @internal */\n"
1104 java_hu_subclasses += "\tpublic constructor(ptr: number) {\n\t\tsuper(null, ptr);\n"
1105 java_hu_subclasses = java_hu_subclasses + hu_conv_body
1106 java_hu_subclasses = java_hu_subclasses + "\t}\n}\n"
1109 java_hu_class += "\t\t\tdefault:\n\t\t\t\tthrow new Error('oops, this should be unreachable'); // Unreachable without extending the (internal) bindings interface\n\t\t}\n\t}\n\n"
1110 out_java += self.fn_call_body(struct_name + "_ty_from_ptr", "uint32_t", "number", "ptr: number", "ptr")
1111 out_c += ("\t\tdefault: abort();\n")
1112 out_c += ("\t}\n}\n")
1114 for var in variant_list:
1115 for idx, (field_map, _) in enumerate(var.fields):
1116 fn_name = f"{struct_name}_{var.var_name}_get_{field_map.arg_name}"
1117 out_c += self.c_fn_ty_pfx + field_map.c_ty + self.c_fn_name_define_pfx(fn_name, True) + self.ptr_c_ty + " ptr) {\n"
1118 out_c += "\t" + struct_name + " *obj = (" + struct_name + "*)(ptr & ~1);\n"
1119 out_c += f"\tassert(obj->tag == {struct_name}_{var.var_name});\n"
1120 if field_map.ret_conv is not None:
1121 out_c += ("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t"))
1122 if var.tuple_variant:
1123 out_c += "obj->" + camel_to_snake(var.var_name)
1125 out_c += "obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name
1126 out_c += (field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
1127 out_c += "\treturn " + field_map.ret_conv_name + ";\n"
1129 if var.tuple_variant:
1130 out_c += "\treturn " + "obj->" + camel_to_snake(var.var_name) + ";\n"
1132 out_c += "\treturn " + "obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name + ";\n"
1134 out_java += self.fn_call_body(fn_name, field_map.c_ty, field_map.java_ty, "ptr: number", "ptr")
1135 out_java_enum += java_hu_class
1136 self.struct_file_suffixes[java_hu_type] = java_hu_subclasses
1137 self.obj_defined([java_hu_type], "structs")
1138 return (out_java, out_java_enum, out_c)
1140 def map_opaque_struct(self, struct_name, struct_doc_comment):
1141 implementations = ""
1144 hu_name = struct_name.replace("LDKC2Tuple", "TwoTuple").replace("LDKC3Tuple", "ThreeTuple").replace("LDK", "")
1145 out_opaque_struct_human = f"{self.hu_struct_file_prefix}"
1146 if struct_name.startswith("LDKLocked"):
1147 out_opaque_struct_human += "/** XXX: DO NOT USE THIS - it remains locked until the GC runs (if that ever happens */"
1148 formatted_doc_comment = struct_doc_comment.replace("\n", "\n * ")
1149 out_opaque_struct_human += f"""
1151 * {formatted_doc_comment}
1153 export class {hu_name} extends CommonBase {implementations}{{
1155 public constructor(_dummy: object, ptr: number) {{
1156 super(ptr, bindings.{struct_name.replace("LDK","")}_free);
1160 self.obj_defined([hu_name], "structs")
1161 return out_opaque_struct_human
1163 def map_tuple(self, struct_name):
1164 return self.map_opaque_struct(struct_name, "A Tuple")
1166 def map_result(self, struct_name, res_map, err_map):
1167 human_ty = struct_name.replace("LDKCResult", "Result")
1169 suffixes = f"export class {human_ty}_OK extends {human_ty} {{\n"
1170 if res_map.java_hu_ty != "void":
1171 suffixes += "\tpublic res: " + res_map.java_hu_ty + ";\n"
1174 public constructor(_dummy: object, ptr: number) {{
1177 if res_map.java_hu_ty == "void":
1179 elif res_map.to_hu_conv is not None:
1180 suffixes += "\t\tconst res: " + res_map.java_ty + " = bindings." + struct_name.replace("LDK", "") + "_get_ok(ptr);\n"
1181 suffixes += "\t\t" + res_map.to_hu_conv.replace("\n", "\n\t\t")
1182 suffixes += "\n\t\tthis.res = " + res_map.to_hu_conv_name + ";\n"
1184 suffixes += "\t\tthis.res = bindings." + struct_name.replace("LDK", "") + "_get_ok(ptr);\n"
1185 suffixes += "\t}\n}\n"
1187 suffixes += f"export class {human_ty}_Err extends {human_ty} {{\n"
1188 if err_map.java_hu_ty != "void":
1189 suffixes += "\tpublic err: " + err_map.java_hu_ty + ";\n"
1192 public constructor(_dummy: object, ptr: number) {{
1195 if err_map.java_hu_ty == "void":
1197 elif err_map.to_hu_conv is not None:
1198 suffixes += "\t\tconst err: " + err_map.java_ty + " = bindings." + struct_name.replace("LDK", "") + "_get_err(ptr);\n"
1199 suffixes += "\t\t" + err_map.to_hu_conv.replace("\n", "\n\t\t")
1200 suffixes += "\n\t\tthis.err = " + err_map.to_hu_conv_name + ";\n"
1202 suffixes += "\t\tthis.err = bindings." + struct_name.replace("LDK", "") + "_get_err(ptr);\n"
1203 suffixes += "\t}\n}"
1205 self.struct_file_suffixes[human_ty] = suffixes
1206 self.obj_defined([human_ty], "structs")
1208 return f"""{self.hu_struct_file_prefix}
1210 export class {human_ty} extends CommonBase {{
1211 protected constructor(_dummy: object, ptr: number) {{
1212 super(ptr, bindings.{struct_name.replace("LDK","")}_free);
1215 public static constr_from_ptr(ptr: number): {human_ty} {{
1216 if (bindings.{struct_name.replace("LDK", "")}_is_ok(ptr)) {{
1217 return new {human_ty}_OK(null, ptr);
1219 return new {human_ty}_Err(null, ptr);
1224 def fn_call_body(self, method_name, return_c_ty, return_java_ty, method_argument_string, native_call_argument_string):
1225 has_return_value = return_c_ty != 'void'
1226 return_statement = 'return nativeResponseValue;'
1227 if not has_return_value:
1228 return_statement = '// debug statements here'
1230 return f"""/* @internal */
1231 export function {method_name}({method_argument_string}): {return_java_ty} {{
1232 if(!isWasmInitialized) {{
1233 throw new Error("initializeWasm() must be awaited first!");
1235 const nativeResponseValue = wasm.TS_{method_name}({native_call_argument_string});
1239 def map_function(self, argument_types, c_call_string, method_name, meth_n, return_type_info, struct_meth, default_constructor_args, takes_self, takes_self_as_ref, args_known, type_mapping_generator, doc_comment):
1242 out_java_struct = None
1245 out_c += (self.c_fn_ty_pfx)
1246 out_c += (return_type_info.c_ty)
1247 out_java += (return_type_info.java_ty)
1248 if return_type_info.ret_conv is not None:
1249 ret_conv_pfx, ret_conv_sfx = return_type_info.ret_conv
1250 out_java += (" " + method_name + "(")
1251 out_c += (" " + self.c_fn_name_define_pfx(method_name, True))
1253 method_argument_string = ""
1254 native_call_argument_string = ""
1255 for idx, arg_conv_info in enumerate(argument_types):
1257 method_argument_string += (", ")
1258 native_call_argument_string += ', '
1260 if arg_conv_info.c_ty != "void":
1261 out_c += (arg_conv_info.c_ty + " " + arg_conv_info.arg_name)
1262 method_argument_string += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
1263 native_call_argument_string += arg_conv_info.arg_name
1264 out_java = self.fn_call_body(method_name, return_type_info.c_ty, return_type_info.java_ty, method_argument_string, native_call_argument_string)
1266 out_java_struct = ""
1267 if doc_comment is not None:
1268 out_java_struct = "\t/**\n\t * " + doc_comment.replace("\n", "\n\t * ") + "\n\t */\n"
1271 out_java_struct += ("\t// Skipped " + method_name + "\n")
1274 out_java_struct += (
1275 "\tpublic static constructor_" + meth_n + "(")
1277 out_java_struct += ("\tpublic " + meth_n + "(")
1278 for idx, arg in enumerate(argument_types):
1280 if not takes_self or idx > 1:
1281 out_java_struct += (", ")
1284 if arg.java_ty != "void":
1285 if arg.arg_name in default_constructor_args:
1286 for explode_idx, explode_arg in enumerate(default_constructor_args[arg.arg_name]):
1287 if explode_idx != 0:
1288 out_java_struct += (", ")
1289 out_java_struct += arg.arg_name + "_" + explode_arg.arg_name + ": " + explode_arg.java_hu_ty
1291 out_java_struct += arg.arg_name + ": " + arg.java_hu_ty
1294 if out_java_struct is not None:
1295 out_java_struct += "): " + return_type_info.java_hu_ty + " {\n"
1296 for info in argument_types:
1297 if info.arg_conv is not None:
1298 out_c += ("\t" + info.arg_conv.replace('\n', "\n\t") + "\n")
1299 if return_type_info.ret_conv is not None:
1300 out_c += ("\t" + ret_conv_pfx.replace('\n', '\n\t'))
1301 elif return_type_info.c_ty != "void":
1302 out_c += ("\t" + return_type_info.c_ty + " ret_val = ")
1305 if c_call_string is None:
1306 out_c += (method_name + "(")
1308 out_c += (c_call_string)
1309 for idx, info in enumerate(argument_types):
1310 if info.arg_conv_name is not None:
1313 elif c_call_string is not None:
1315 out_c += (info.arg_conv_name)
1317 if return_type_info.ret_conv is not None:
1318 out_c += (ret_conv_sfx.replace('\n', '\n\t'))
1321 for info in argument_types:
1322 if info.arg_conv_cleanup is not None:
1323 out_c += ("\n\t" + info.arg_conv_cleanup.replace("\n", "\n\t"))
1324 if return_type_info.ret_conv is not None:
1325 out_c += ("\n\treturn " + return_type_info.ret_conv_name + ";")
1326 elif return_type_info.c_ty != "void":
1327 out_c += ("\n\treturn ret_val;")
1328 out_c += ("\n}\n\n")
1331 out_java_struct += ("\t\t")
1332 if return_type_info.java_ty != "void":
1333 out_java_struct += "const ret: " + return_type_info.java_ty + " = "
1334 out_java_struct += ("bindings." + method_name + "(")
1335 for idx, info in enumerate(argument_types):
1337 out_java_struct += (", ")
1338 if idx == 0 and takes_self:
1339 out_java_struct += ("this.ptr")
1340 elif info.arg_name in default_constructor_args:
1341 out_java_struct += ("bindings." + info.java_hu_ty + "_new(")
1342 for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
1343 if explode_idx != 0:
1344 out_java_struct += (", ")
1345 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1346 if explode_arg.from_hu_conv is not None:
1347 out_java_struct += (
1348 explode_arg.from_hu_conv[0].replace(explode_arg.arg_name, expl_arg_name))
1350 out_java_struct += (expl_arg_name)
1351 out_java_struct += (")")
1352 elif info.from_hu_conv is not None:
1353 out_java_struct += (info.from_hu_conv[0])
1355 out_java_struct += (info.arg_name)
1356 out_java_struct += (");\n")
1357 if return_type_info.to_hu_conv is not None:
1359 out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t").replace("this",
1360 return_type_info.to_hu_conv_name) + "\n")
1362 out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t") + "\n")
1364 for idx, info in enumerate(argument_types):
1365 if idx == 0 and takes_self:
1367 elif info.arg_name in default_constructor_args:
1368 for explode_arg in default_constructor_args[info.arg_name]:
1369 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1370 if explode_arg.from_hu_conv is not None and return_type_info.to_hu_conv_name:
1371 out_java_struct += ("\t\t" + explode_arg.from_hu_conv[1].replace(explode_arg.arg_name,
1372 expl_arg_name).replace(
1373 "this", return_type_info.to_hu_conv_name) + ";\n")
1374 elif info.from_hu_conv is not None and info.from_hu_conv[1] != "":
1375 if not takes_self and return_type_info.to_hu_conv_name is not None:
1376 out_java_struct += (
1377 "\t\t" + info.from_hu_conv[1].replace("this", return_type_info.to_hu_conv_name).replace("\n", "\n\t\t") + ";\n")
1379 out_java_struct += ("\t\t" + info.from_hu_conv[1].replace("\n", "\n\t\t") + ";\n")
1381 if return_type_info.to_hu_conv_name is not None:
1382 out_java_struct += ("\t\treturn " + return_type_info.to_hu_conv_name + ";\n")
1383 elif return_type_info.java_ty != "void" and return_type_info.rust_obj != "LDK" + struct_meth:
1384 out_java_struct += ("\t\treturn ret;\n")
1385 out_java_struct += ("\t}\n\n")
1387 return (out_java, out_c, out_java_struct)
1390 for struct in self.struct_file_suffixes:
1391 with open(self.outdir + "/structs/" + struct + self.file_ext, "a") as src:
1392 src.write(self.struct_file_suffixes[struct])
1394 with open(self.outdir + "/bindings.mts", "a") as bindings:
1397 js_invoke = function(obj_ptr: number, fn_id: number, arg1: number, arg2: number, arg3: number, arg4: number, arg5: number, arg6: number, arg7: number, arg8: number, arg9: number, arg10: number) {
1398 const weak: WeakRef<object> = js_objs[obj_ptr];
1399 if (weak == null || weak == undefined) {
1400 console.error("Got function call on unknown/free'd JS object!");
1401 throw new Error("Got function call on unknown/free'd JS object!");
1403 const obj: object = weak.deref();
1404 if (obj == null || obj == undefined) {
1405 console.error("Got function call on GC'd JS object!");
1406 throw new Error("Got function call on GC'd JS object!");
1410 bindings.write("\tswitch (fn_id) {\n")
1411 for f in self.function_ptrs:
1412 bindings.write(f"\t\tcase {str(f)}: fn = Object.getOwnPropertyDescriptor(obj, \"{self.function_ptrs[f][1]}\"); break;\n")
1414 bindings.write("""\t\tdefault:
1415 console.error("Got unknown function call from C!");
1416 throw new Error("Got unknown function call from C!");
1418 if (fn == null || fn == undefined) {
1419 console.error("Got function call on incorrect JS object!");
1420 throw new Error("Got function call on incorrect JS object!");
1422 return fn.value.bind(obj)(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10);