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';
39 import { UInt5 } from './structs/CommonBase.mjs';
41 const imports: any = {};
44 var js_objs: Array<WeakRef<object>> = [];
45 var js_invoke: Function;
46 var getRandomValues: Function;
48 imports.wasi_snapshot_preview1 = {
49 "fd_write": (fd: number, iovec_array_ptr: number, iovec_array_len: number) => {
50 // This should generally only be used to print panic messages
51 console.log("FD_WRITE to " + fd + " in " + iovec_array_len + " chunks.");
52 const ptr_len_view = new Uint32Array(wasm.memory.buffer, iovec_array_ptr, iovec_array_len * 2);
53 for (var i = 0; i < iovec_array_len; i++) {
54 const bytes_view = new Uint8Array(wasm.memory.buffer, ptr_len_view[i*2], ptr_len_view[i*2+1]);
55 console.log(String.fromCharCode(...bytes_view));
59 "fd_close": (_fd: number) => {
60 // This is not generally called, but may be referenced in debug builds
61 console.log("wasi_snapshot_preview1:fd_close");
62 return 58; // Not Supported
64 "fd_seek": (_fd: number, _offset: bigint, _whence: number, _new_offset: number) => {
65 // This is not generally called, but may be referenced in debug builds
66 console.log("wasi_snapshot_preview1:fd_seek");
67 return 58; // Not Supported
69 "random_get": (buf_ptr: number, buf_len: number) => {
70 const buf = new Uint8Array(wasm.memory.buffer, buf_ptr, buf_len);
74 "environ_sizes_get": (environ_var_count_ptr: number, environ_len_ptr: number) => {
75 // This is called before fd_write to format + print panic messages
76 console.log("wasi_snapshot_preview1:environ_sizes_get");
77 const out_count_view = new Uint32Array(wasm.memory.buffer, environ_var_count_ptr, 1);
78 out_count_view[0] = 0;
79 const out_len_view = new Uint32Array(wasm.memory.buffer, environ_len_ptr, 1);
83 "environ_get": (environ_ptr: number, environ_buf_ptr: number) => {
84 // This is called before fd_write to format + print panic messages
85 console.log("wasi_snapshot_preview1:environ_get");
86 return 58; // Note supported - we said there were 0 environment entries!
89 console.log("wasi_snapshot_preview1:proc_exit");
94 let isWasmInitialized: boolean = false;
96 async function finishInitializeWasm(wasmInstance: WebAssembly.Instance) {
97 if (typeof crypto === "undefined") {
98 var crypto_import = (await import('crypto')).webcrypto;
99 getRandomValues = crypto_import.getRandomValues.bind(crypto_import);
101 getRandomValues = crypto.getRandomValues.bind(crypto);
104 wasm = wasmInstance.exports;
105 if (!wasm.test_bigint_pass_deadbeef0badf00d(BigInt("0xdeadbeef0badf00d"))) {
106 throw new Error(\"Currently need BigInt-as-u64 support, try ----experimental-wasm-bigint");
109 if (decodeString(wasm.TS_get_lib_version_string()) !== version.get_ldk_java_bindings_version())
110 throw new Error(\"Compiled LDK library and LDK class failes do not match\");
111 // Fetching the LDK versions from C also checks that the header and binaries match
112 const c_bindings_ver: number = wasm.TS_get_ldk_c_bindings_version();
113 const ldk_ver: number = wasm.TS_get_ldk_version();
114 if (c_bindings_ver == 0)
115 throw new Error(\"LDK version did not match the header we built against\");
117 throw new Error(\"LDK C bindings version did not match the header we built against\");
118 const c_bindings_version: string = decodeString(c_bindings_ver)
119 const ldk_version: string = decodeString(ldk_ver);
120 console.log(\"Loaded LDK-Java Bindings with LDK \" + ldk_version + \" and LDK-C-Bindings \" + c_bindings_version);
122 isWasmInitialized = true;
126 export async function initializeWasmFromUint8Array(wasmBinary: Uint8Array) {
127 imports.env["js_invoke_function"] = js_invoke;
128 const { instance: wasmInstance } = await WebAssembly.instantiate(wasmBinary, imports);
129 await finishInitializeWasm(wasmInstance);
133 export async function initializeWasmFetch(uri: string) {
134 const stream = fetch(uri);
135 imports.env["js_invoke_function"] = js_invoke;
136 const { instance: wasmInstance } = await WebAssembly.instantiateStreaming(stream, imports);
137 await finishInitializeWasm(wasmInstance);
140 self.bindings_header += """
144 export function uint5ArrToBytes(inputArray: Array<UInt5>): Uint8Array {
145 const arr = new Uint8Array(inputArray.length);
146 for (var i = 0; i < inputArray.length; i++) {
147 arr[i] = inputArray[i].getVal();
153 export function encodeUint8Array (inputArray: Uint8Array): number {
154 const cArrayPointer = wasm.TS_malloc(inputArray.length + 4);
155 const arrayLengthView = new Uint32Array(wasm.memory.buffer, cArrayPointer, 1);
156 arrayLengthView[0] = inputArray.length;
157 const arrayMemoryView = new Uint8Array(wasm.memory.buffer, cArrayPointer + 4, inputArray.length);
158 arrayMemoryView.set(inputArray);
159 return cArrayPointer;
162 export function encodeUint32Array (inputArray: Uint32Array|Array<number>): number {
163 const cArrayPointer = wasm.TS_malloc((inputArray.length + 1) * 4);
164 const arrayMemoryView = new Uint32Array(wasm.memory.buffer, cArrayPointer, inputArray.length);
165 arrayMemoryView.set(inputArray, 1);
166 arrayMemoryView[0] = inputArray.length;
167 return cArrayPointer;
170 export function encodeUint64Array (inputArray: BigUint64Array|Array<bigint>): number {
171 const cArrayPointer = wasm.TS_malloc(inputArray.length * 8 + 1);
172 const arrayLengthView = new Uint32Array(wasm.memory.buffer, cArrayPointer, 1);
173 arrayLengthView[0] = inputArray.length;
174 const arrayMemoryView = new BigUint64Array(wasm.memory.buffer, cArrayPointer + 4, inputArray.length);
175 arrayMemoryView.set(inputArray);
176 return cArrayPointer;
180 export function check_arr_len(arr: Uint8Array, len: number): Uint8Array {
181 if (arr.length != len) { throw new Error("Expected array of length " + len + "got " + arr.length); }
186 export function getArrayLength(arrayPointer: number): number {
187 const arraySizeViewer = new Uint32Array(wasm.memory.buffer, arrayPointer, 1);
188 return arraySizeViewer[0];
191 export function decodeUint8Array (arrayPointer: number, free = true): Uint8Array {
192 const arraySize = getArrayLength(arrayPointer);
193 const actualArrayViewer = new Uint8Array(wasm.memory.buffer, arrayPointer + 4, arraySize);
194 // Clone the contents, TODO: In the future we should wrap the Viewer in a class that
195 // will free the underlying memory when it becomes unreachable instead of copying here.
196 // Note that doing so may have edge-case interactions with memory resizing (invalidating the buffer).
197 const actualArray = actualArrayViewer.slice(0, arraySize);
199 wasm.TS_free(arrayPointer);
203 const decodeUint32Array = (arrayPointer: number, free = true) => {
204 const arraySize = getArrayLength(arrayPointer);
205 const actualArrayViewer = new Uint32Array(
206 wasm.memory.buffer, // value
207 arrayPointer + 4, // offset (ignoring length bytes)
208 arraySize // uint32 count
210 // Clone the contents, TODO: In the future we should wrap the Viewer in a class that
211 // will free the underlying memory when it becomes unreachable instead of copying here.
212 const actualArray = actualArrayViewer.slice(0, arraySize);
214 wasm.TS_free(arrayPointer);
220 export function freeWasmMemory(pointer: number) { wasm.TS_free(pointer); }
223 export function getU32ArrayElem(arrayPointer: number, idx: number): number {
224 const actualArrayViewer = new Uint32Array(wasm.memory.buffer, arrayPointer + 4, idx + 1);
225 return actualArrayViewer[idx];
229 export function getU8ArrayElem(arrayPointer: number, idx: number): number {
230 const actualArrayViewer = new Uint8Array(wasm.memory.buffer, arrayPointer + 4, idx + 1);
231 return actualArrayViewer[idx];
236 export function encodeString(str: string): number {
237 const charArray = new TextEncoder().encode(str);
238 return encodeUint8Array(charArray);
242 export function decodeString(stringPointer: number, free = true): string {
243 const arraySize = getArrayLength(stringPointer);
244 const memoryView = new Uint8Array(wasm.memory.buffer, stringPointer + 4, arraySize);
245 const result = new TextDecoder("utf-8").decode(memoryView);
248 wasm.TS_free(stringPointer);
255 self.bindings_header += """
257 export function getRemainingAllocationCount(): number {
258 return wasm.TS_allocs_remaining();
261 export function debugPrintRemainingAllocs() {
262 wasm.TS_print_leaks();
266 self.bindings_header += "\n/* @internal */ export function getRemainingAllocationCount(): number { return 0; }\n"
267 self.bindings_header += "/* @internal */ export function debugPrintRemainingAllocs() { }\n"
269 with open(outdir + "/index.mts", 'a') as index:
270 index.write("""import { initializeWasmFetch, initializeWasmFromUint8Array } from './bindings.mjs';
271 /** Initializes the WASM backend by calling `fetch()` on the given URI - Browser only */
272 export async function initializeWasmWebFetch(uri: string) {
273 await initializeWasmFetch(uri);
275 /** Initializes the WASM backend given a Uint8Array of the .wasm binary file - Browser or Node.JS */
276 export async function initializeWasmFromBinary(bin: Uint8Array) {
277 await initializeWasmFromUint8Array(bin);
282 self.bindings_version_file = """export function get_ldk_java_bindings_version(): String {
283 return "<git_version_ldk_garbagecollected>";
286 self.bindings_footer = ""
288 self.common_base = """
289 function freer(f: () => void) { f() }
290 const finalizer = new FinalizationRegistry(freer);
291 function get_freeer(ptr: number, free_fn: (ptr: number) => void) {
297 export class CommonBase {
298 protected ptr: number;
299 protected ptrs_to: object[] = [];
300 protected constructor(ptr: number, free_fn: (ptr: number) => void) {
302 if (Number.isFinite(ptr) && ptr != 0){
303 finalizer.register(this, get_freeer(ptr, free_fn));
306 // In Java, protected means "any subclass can access fields on any other subclass'"
307 // In TypeScript, protected means "any subclass can access parent fields on instances of itself"
308 // To work around this, we add accessors for other instances' protected fields here.
309 protected static add_ref_from(holder: CommonBase, referent: object) {
310 holder.ptrs_to.push(referent);
312 protected static get_ptr_of(o: CommonBase) {
315 protected static set_null_skip_free(o: CommonBase) {
317 finalizer.unregister(o);
322 public constructor(private val: number) {
323 if (val > 32 || val < 0) throw new Error("UInt5 value is out of range");
325 public getVal(): number {
331 self.txout_defn = """export class TxOut extends CommonBase {
332 /** The script_pubkey in this output */
333 public script_pubkey: Uint8Array;
334 /** The value, in satoshis, of this output */
335 public value: bigint;
338 public constructor(_dummy: object, ptr: number) {
339 super(ptr, bindings.TxOut_free);
340 this.script_pubkey = bindings.decodeUint8Array(bindings.TxOut_get_script_pubkey(ptr));
341 this.value = bindings.TxOut_get_value(ptr);
343 public constructor_new(value: bigint, script_pubkey: Uint8Array): TxOut {
344 return new TxOut(null, bindings.TxOut_new(bindings.encodeUint8Array(script_pubkey), value));
347 self.obj_defined(["TxOut"], "structs")
349 self.c_file_pfx = """#include "js-wasm.h"
350 #include <stdatomic.h>
351 #include <lightning.h>
353 // These should be provided...somehow...
354 void *memset(void *s, int c, size_t n);
355 void *memcpy(void *dest, const void *src, size_t n);
356 int memcmp(const void *s1, const void *s2, size_t n);
358 extern void __attribute__((noreturn)) abort(void);
359 static inline void assert(bool expression) {
360 if (!expression) { abort(); }
363 uint32_t __attribute__((export_name("test_bigint_pass_deadbeef0badf00d"))) test_bigint_pass_deadbeef0badf00d(uint64_t val) {
364 return val == 0xdeadbeef0badf00dULL;
370 self.c_file_pfx += """
371 void *malloc(size_t size);
372 void free(void *ptr);
374 #define MALLOC(a, _) malloc(a)
375 #define do_MALLOC(a, _b, _c) malloc(a)
376 #define FREE(p) if ((unsigned long)(p) > 4096) { free(p); }
377 #define DO_ASSERT(a) (void)(a)
379 #define CHECK_ACCESS(p)
380 #define CHECK_INNER_FIELD_ACCESS_OR_NULL(v)
383 self.c_file_pfx += """
384 extern int snprintf(char *str, size_t size, const char *format, ...);
385 typedef int32_t ssize_t;
386 ssize_t write(int fd, const void *buf, size_t count);
387 #define DEBUG_PRINT(...) do { \\
388 char debug_str[1024]; \\
389 int s_len = snprintf(debug_str, 1023, __VA_ARGS__); \\
390 write(2, debug_str, s_len); \\
393 // Always run a, then assert it is true:
394 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
395 // Assert a is true or do nothing
396 #define CHECK(a) DO_ASSERT(a)
398 // Running a leak check across all the allocations and frees of the JDK is a mess,
399 // so instead we implement our own naive leak checker here, relying on the -wrap
400 // linker option to wrap malloc/calloc/realloc/free, tracking everyhing allocated
401 // and free'd in Rust or C across the generated bindings shared library.
404 typedef struct allocation {
405 struct allocation* next;
407 const char* struct_name;
410 static allocation* allocation_ll = NULL;
411 static allocation* freed_ll = NULL;
413 extern void* __real_malloc(size_t len);
414 extern void* __real_calloc(size_t nmemb, size_t len);
415 extern void* __real_aligned_alloc(size_t alignment, size_t size);
416 static void new_allocation(void* res, const char* struct_name, int lineno) {
417 allocation* new_alloc = __real_malloc(sizeof(allocation));
418 new_alloc->ptr = res;
419 new_alloc->struct_name = struct_name;
420 new_alloc->next = allocation_ll;
421 new_alloc->lineno = lineno;
422 allocation_ll = new_alloc;
424 static void* do_MALLOC(size_t len, const char* struct_name, int lineno) {
425 void* res = __real_malloc(len);
426 new_allocation(res, struct_name, lineno);
429 #define MALLOC(len, struct_name) do_MALLOC(len, struct_name, __LINE__)
431 void __real_free(void* ptr);
432 static void alloc_freed(void* ptr, int lineno) {
433 allocation* p = NULL;
434 allocation* it = allocation_ll;
435 while (it->ptr != ptr) {
436 p = it; it = it->next;
440 while (it && it->ptr != ptr) { p = it; it = it->next; }
442 DEBUG_PRINT("Tried to free unknown pointer %p at line %d.\\n", ptr, lineno);
444 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);
449 if (p) { p->next = it->next; } else { allocation_ll = it->next; }
450 DO_ASSERT(it->ptr == ptr);
454 static void do_FREE(void* ptr, int lineno) {
455 if ((unsigned long)ptr <= 4096) return; // Rust loves to create pointers to the NULL page for dummys
456 alloc_freed(ptr, lineno);
459 #define FREE(ptr) do_FREE(ptr, __LINE__)
461 static void CHECK_ACCESS(const void* ptr) {
462 allocation* it = allocation_ll;
463 while (it->ptr != ptr) {
466 return; // addrsan should catch malloc-unknown and print more info than we have
470 #define CHECK_INNER_FIELD_ACCESS_OR_NULL(v) \\
471 if (v.is_owned && v.inner != NULL) { \\
472 const void *p = __unmangle_inner_ptr(v.inner); \\
478 void* __wrap_malloc(size_t len) {
479 void* res = __real_malloc(len);
480 new_allocation(res, "malloc call", 0);
483 void* __wrap_calloc(size_t nmemb, size_t len) {
484 void* res = __real_calloc(nmemb, len);
485 new_allocation(res, "calloc call", 0);
488 void* __wrap_aligned_alloc(size_t alignment, size_t size) {
489 void* res = __real_aligned_alloc(alignment, size);
490 new_allocation(res, "aligned_alloc call", 0);
493 void __wrap_free(void* ptr) {
494 if (ptr == NULL) return;
499 void* __real_realloc(void* ptr, size_t newlen);
500 void* __wrap_realloc(void* ptr, size_t len) {
501 if (ptr != NULL) alloc_freed(ptr, 0);
502 void* res = __real_realloc(ptr, len);
503 new_allocation(res, "realloc call", 0);
506 void __wrap_reallocarray(void* ptr, size_t new_sz) {
507 // Rust doesn't seem to use reallocarray currently
511 uint32_t __attribute__((export_name("TS_allocs_remaining"))) allocs_remaining() {
513 for (allocation* a = allocation_ll; a != NULL; a = a->next) {
518 void __attribute__((export_name("TS_print_leaks"))) print_leaks() {
519 for (allocation* a = allocation_ll; a != NULL; a = a->next) {
520 DEBUG_PRINT("%s %p remains. Allocated on line %d\\n", a->struct_name, a->ptr, a->lineno);
524 self.c_file_pfx = self.c_file_pfx + """
525 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
526 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
527 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
528 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
530 _Static_assert(sizeof(void*) == 4, "Pointers mut be 32 bits");
532 #define DECL_ARR_TYPE(ty, name) \\
533 struct name##array { \\
537 typedef struct name##array * name##Array; \\
538 static inline name##Array init_##name##Array(size_t arr_len, int lineno) { \\
539 name##Array arr = (name##Array)do_MALLOC(arr_len * sizeof(ty) + sizeof(uint32_t), #name" array init", lineno); \\
540 arr->arr_len = arr_len; \\
544 DECL_ARR_TYPE(int64_t, int64_t);
545 DECL_ARR_TYPE(int8_t, int8_t);
546 DECL_ARR_TYPE(uint32_t, uint32_t);
547 DECL_ARR_TYPE(void*, ptr);
548 DECL_ARR_TYPE(char, char);
549 typedef charArray jstring;
551 static inline jstring str_ref_to_ts(const char* chars, size_t len) {
552 charArray arr = init_charArray(len, __LINE__);
553 memcpy(arr->elems, chars, len);
556 static inline LDKStr str_ref_to_owned_c(const jstring str) {
557 char* newchars = MALLOC(str->arr_len + 1, "String chars");
558 memcpy(newchars, str->elems, str->arr_len);
559 newchars[str->arr_len] = 0;
563 .chars_is_owned = true
568 typedef bool jboolean;
570 uint32_t __attribute__((export_name("TS_malloc"))) TS_malloc(uint32_t size) {
571 return (uint32_t)MALLOC(size, "JS-Called malloc");
573 void __attribute__((export_name("TS_free"))) TS_free(uint32_t ptr) {
577 jstring __attribute__((export_name("TS_get_ldk_c_bindings_version"))) TS_get_ldk_c_bindings_version() {
578 const char *res = check_get_ldk_bindings_version();
579 if (res == NULL) return NULL;
580 return str_ref_to_ts(res, strlen(res));
582 jstring __attribute__((export_name("TS_get_ldk_version"))) get_ldk_version() {
583 const char *res = check_get_ldk_version();
584 if (res == NULL) return NULL;
585 return str_ref_to_ts(res, strlen(res));
590 self.c_version_file = """jstring __attribute__((export_name("TS_get_lib_version_string"))) TS_get_lib_version_string() {
591 return str_ref_to_ts("<git_version_ldk_garbagecollected>", strlen("<git_version_ldk_garbagecollected>"));
594 self.hu_struct_file_prefix = """
595 import { CommonBase, UInt5 } from './CommonBase.mjs';
596 import * as bindings from '../bindings.mjs'
599 self.util_fn_pfx = self.hu_struct_file_prefix + "\nexport class UtilMethods extends CommonBase {\n"
600 self.util_fn_sfx = "}"
601 self.c_fn_ty_pfx = ""
602 self.file_ext = ".mts"
603 self.ptr_c_ty = "uint32_t"
604 self.ptr_native_ty = "number"
605 self.result_c_ty = "uint32_t"
606 self.ptr_arr = "ptrArray"
607 self.is_arr_some_check = ("", " != 0")
608 self.get_native_arr_len_call = ("", "->arr_len")
610 def release_native_arr_ptr_call(self, ty_info, arr_var, arr_ptr_var):
612 def create_native_arr_call(self, arr_len, ty_info):
613 if ty_info.c_ty == "ptrArray":
614 assert ty_info.rust_obj == "LDKCVec_u5Z" or (ty_info.subty is not None and ty_info.subty.c_ty.endswith("Array"))
615 return "init_" + ty_info.c_ty + "(" + arr_len + ", __LINE__)"
616 def set_native_arr_contents(self, arr_name, arr_len, ty_info):
617 if ty_info.c_ty == "int8_tArray":
618 return ("memcpy(" + arr_name + "->elems, ", ", " + arr_len + ")")
621 def get_native_arr_contents(self, arr_name, dest_name, arr_len, ty_info, copy):
622 if ty_info.c_ty == "int8_tArray":
624 return "memcpy(" + dest_name + ", " + arr_name + "->elems, " + arr_len + "); FREE(" + arr_name + ")"
625 if ty_info.c_ty == "ptrArray":
626 return "(void*) " + arr_name + "->elems /* XXX " + arr_name + " leaks */"
629 return arr_name + "->elems /* XXX " + arr_name + " leaks */"
630 def get_native_arr_elem(self, arr_name, idxc, ty_info):
631 assert False # Only called if above is None
632 def get_native_arr_ptr_call(self, ty_info):
633 if ty_info.subty is not None:
634 return "(" + ty_info.subty.c_ty + "*)(((uint8_t*)", ") + 4)"
635 return "(" + ty_info.c_ty + "*)(((uint8_t*)", ") + 4)"
636 def get_native_arr_entry_call(self, ty_info, arr_name, idxc, entry_access):
638 def cleanup_native_arr_ref_contents(self, arr_name, dest_name, arr_len, ty_info):
639 if ty_info.c_ty == "int8_tArray":
644 def map_hu_array_elems(self, arr_name, conv_name, arr_ty, elem_ty):
645 if elem_ty.rust_obj == "LDKu5":
646 return arr_name + " != null ? bindings.uint5ArrToBytes(" + arr_name + ") : null"
647 assert elem_ty.c_ty == "uint32_t" or elem_ty.c_ty.endswith("Array")
648 return arr_name + " != null ? " + arr_name + ".map(" + conv_name + " => " + elem_ty.from_hu_conv[0] + ") : null"
650 def str_ref_to_native_call(self, var_name, str_len):
651 return "str_ref_to_ts(" + var_name + ", " + str_len + ")"
652 def str_ref_to_c_call(self, var_name):
653 return "str_ref_to_owned_c(" + var_name + ")"
654 def str_to_hu_conv(self, var_name):
655 return "const " + var_name + "_conv: string = bindings.decodeString(" + var_name + ");"
656 def str_from_hu_conv(self, var_name):
657 return ("bindings.encodeString(" + var_name + ")", "")
659 def c_fn_name_define_pfx(self, fn_name, have_args):
660 return " __attribute__((export_name(\"TS_" + fn_name + "\"))) TS_" + fn_name + "("
665 def get_java_arr_len(self, arr_name):
666 return "bindings.getArrayLength(" + arr_name + ")"
667 def get_java_arr_elem(self, elem_ty, arr_name, idx):
668 if elem_ty.c_ty == "uint32_t" or elem_ty.c_ty == "uintptr_t" or elem_ty.c_ty.endswith("Array"):
669 return "bindings.getU32ArrayElem(" + arr_name + ", " + idx + ")"
670 elif elem_ty.rust_obj == "LDKu5":
671 return "bindings.getU8ArrayElem(" + arr_name + ", " + idx + ")"
674 def constr_hu_array(self, ty_info, arr_len):
675 return "new Array(" + arr_len + ").fill(null)"
676 def cleanup_converted_native_array(self, ty_info, arr_name):
677 return "bindings.freeWasmMemory(" + arr_name + ")"
679 def primitive_arr_from_hu(self, mapped_ty, fixed_len, arr_name):
681 if fixed_len is not None:
682 assert mapped_ty.c_ty == "int8_t"
683 inner = "bindings.check_arr_len(" + arr_name + ", " + fixed_len + ")"
684 if mapped_ty.c_ty.endswith("Array"):
685 return ("bindings.encodeUint32Array(" + inner + ")", "")
686 elif mapped_ty.c_ty == "uint8_t" or mapped_ty.c_ty == "int8_t":
687 return ("bindings.encodeUint8Array(" + inner + ")", "")
688 elif mapped_ty.c_ty == "uint32_t":
689 return ("bindings.encodeUint32Array(" + inner + ")", "")
690 elif mapped_ty.c_ty == "int64_t":
691 return ("bindings.encodeUint64Array(" + inner + ")", "")
693 print(mapped_ty.c_ty)
696 def primitive_arr_to_hu(self, mapped_ty, fixed_len, arr_name, conv_name):
697 assert mapped_ty.c_ty == "uint8_t" or mapped_ty.c_ty == "int8_t"
698 return "const " + conv_name + ": Uint8Array = bindings.decodeUint8Array(" + arr_name + ");"
700 def var_decl_statement(self, ty_string, var_name, statement):
701 return "const " + var_name + ": " + ty_string + " = " + statement
703 def java_arr_ty_str(self, elem_ty_str):
706 def for_n_in_range(self, n, minimum, maximum):
707 return "for (var " + n + " = " + minimum + "; " + n + " < " + maximum + "; " + n + "++) {"
708 def for_n_in_arr(self, n, arr_name, arr_elem_ty):
709 return (arr_name + ".forEach((" + n + ": " + arr_elem_ty.java_hu_ty + ") => { ", " })")
711 def get_ptr(self, var):
712 return "CommonBase.get_ptr_of(" + var + ")"
713 def set_null_skip_free(self, var):
714 return "CommonBase.set_null_skip_free(" + var + ");"
716 def add_ref(self, holder, referent):
717 return "CommonBase.add_ref_from(" + holder + ", " + referent + ")"
719 def obj_defined(self, struct_names, folder):
720 with open(self.outdir + "/index.mts", 'a') as index:
721 index.write(f"export * from './{folder}/{struct_names[0]}.mjs';\n")
722 with open(self.outdir + "/imports.mts.part", 'a') as imports:
723 imports.write(f"import {{ {', '.join(struct_names)} }} from '../{folder}/{struct_names[0]}.mjs';\n")
725 def native_c_unitary_enum_map(self, struct_name, variants, enum_doc_comment):
726 out_c = "static inline LDK" + struct_name + " LDK" + struct_name + "_from_js(int32_t ord) {\n"
727 out_c = out_c + "\tswitch (ord) {\n"
730 out_typescript_enum_fields = ""
732 for var, var_docs in variants:
733 out_c = out_c + "\t\tcase %d: return %s;\n" % (ord_v, var)
735 if var_docs is not None:
736 var_docs_repld = var_docs.replace("\n", "\n\t")
737 out_typescript_enum_fields += f"/**\n\t * {var_docs_repld}\n\t */\n"
738 out_typescript_enum_fields += f"\t{var},\n\t"
739 out_c = out_c + "\t}\n"
740 out_c = out_c + "\tabort();\n"
741 out_c = out_c + "}\n"
743 out_c = out_c + "static inline int32_t LDK" + struct_name + "_to_js(LDK" + struct_name + " val) {\n"
744 out_c = out_c + "\tswitch (val) {\n"
746 for var, _ in variants:
747 out_c = out_c + "\t\tcase " + var + ": return %d;\n" % ord_v
749 out_c = out_c + "\t\tdefault: abort();\n"
750 out_c = out_c + "\t}\n"
751 out_c = out_c + "}\n"
753 out_typescript = f"""
755 export enum {struct_name} {{
756 {out_typescript_enum_fields}
759 out_typescript_enum = f"export {{ {struct_name} }} from \"../bindings.mjs\";"
760 self.obj_defined([struct_name], "enums")
761 return (out_c, out_typescript_enum, out_typescript)
763 def c_unitary_enum_to_native_call(self, ty_info):
764 return (ty_info.rust_obj + "_to_js(", ")")
765 def native_unitary_enum_to_c_call(self, ty_info):
766 return (ty_info.rust_obj + "_from_js(", ")")
768 def native_c_map_trait(self, struct_name, field_var_conversions, flattened_field_var_conversions, field_function_lines, trait_doc_comment):
769 out_typescript_bindings = ""
770 super_instantiator = ""
771 bindings_instantiator = ""
772 pointer_to_adder = ""
773 impl_constructor_arguments = ""
774 for var in flattened_field_var_conversions:
775 if isinstance(var, ConvInfo):
776 impl_constructor_arguments += f", {var.arg_name}: {var.java_hu_ty}"
777 super_instantiator += first_to_lower(var.arg_name) + ", "
778 if var.from_hu_conv is not None:
779 bindings_instantiator += ", " + var.from_hu_conv[0]
780 if var.from_hu_conv[1] != "":
781 pointer_to_adder += "\t\t\t" + var.from_hu_conv[1] + ";\n"
783 bindings_instantiator += ", " + first_to_lower(var.arg_name)
785 bindings_instantiator += ", " + first_to_lower(var[1]) + ".bindings_instance"
786 super_instantiator += first_to_lower(var[1]) + "_impl, "
787 pointer_to_adder += "\t\timpl_holder.held.ptrs_to.push(" + first_to_lower(var[1]) + ");\n"
788 impl_constructor_arguments += f", {first_to_lower(var[1])}_impl: {var[0].replace('LDK', '')}Interface"
790 super_constructor_statements = ""
791 trait_constructor_arguments = ""
792 for var in field_var_conversions:
793 if isinstance(var, ConvInfo):
794 trait_constructor_arguments += ", " + var.arg_name
796 super_constructor_statements += "\t\tconst " + first_to_lower(var[1]) + " = " + var[1] + ".new_impl(" + super_instantiator + ");\n"
797 trait_constructor_arguments += ", " + first_to_lower(var[1]) + ".bindings_instance"
798 for suparg in var[2]:
799 if isinstance(suparg, ConvInfo):
800 trait_constructor_arguments += ", " + suparg.arg_name
802 trait_constructor_arguments += ", " + suparg[1]
804 # BUILD INTERFACE METHODS
805 out_java_interface = ""
806 out_interface_implementation_overrides = ""
808 for fn_line in field_function_lines:
809 java_method_descriptor = ""
810 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
811 out_java_interface += "\t/**" + fn_line.docs.replace("\n", "\n\t * ") + "\n\t */\n"
812 out_java_interface += "\t" + fn_line.fn_name + "("
813 out_interface_implementation_overrides += f"\t\t\t{fn_line.fn_name} ("
815 for idx, arg_conv_info in enumerate(fn_line.args_ty):
817 out_java_interface += ", "
818 out_interface_implementation_overrides += ", "
819 out_java_interface += f"{arg_conv_info.arg_name}: {arg_conv_info.java_hu_ty}"
820 out_interface_implementation_overrides += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
821 java_method_descriptor += arg_conv_info.java_fn_ty_arg
822 out_java_interface += f"): {fn_line.ret_ty_info.java_hu_ty};\n"
823 java_method_descriptor += ")" + fn_line.ret_ty_info.java_fn_ty_arg
824 java_methods.append((fn_line.fn_name, java_method_descriptor))
826 out_interface_implementation_overrides += f"): {fn_line.ret_ty_info.java_ty} {{\n"
828 for arg_info in fn_line.args_ty:
829 if arg_info.to_hu_conv is not None:
830 out_interface_implementation_overrides += "\t\t\t\t" + arg_info.to_hu_conv.replace("\n", "\n\t\t\t\t") + "\n"
832 if fn_line.ret_ty_info.java_ty != "void":
833 out_interface_implementation_overrides += "\t\t\t\tconst ret: " + fn_line.ret_ty_info.java_hu_ty + " = arg." + fn_line.fn_name + "("
835 out_interface_implementation_overrides += f"\t\t\t\targ." + fn_line.fn_name + "("
837 for idx, arg_info in enumerate(fn_line.args_ty):
839 out_interface_implementation_overrides += ", "
840 if arg_info.to_hu_conv_name is not None:
841 out_interface_implementation_overrides += arg_info.to_hu_conv_name
843 out_interface_implementation_overrides += arg_info.arg_name
845 out_interface_implementation_overrides += ");\n"
846 if fn_line.ret_ty_info.java_ty != "void":
847 if fn_line.ret_ty_info.from_hu_conv is not None:
848 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"
849 if fn_line.ret_ty_info.from_hu_conv[1] != "":
850 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"
851 #if fn_line.ret_ty_info.rust_obj in result_types:
852 # XXX: We need to handle this in conversion logic so that its cross-language!
853 # Avoid double-free by breaking the result - we should learn to clone these and then we can be safe instead
854 # out_interface_implementation_overrides = out_interface_implementation_overrides + "\t\t\t\tret.ptr = 0;\n"
855 out_interface_implementation_overrides += "\t\t\t\treturn result;\n"
857 out_interface_implementation_overrides += "\t\t\t\treturn ret;\n"
858 out_interface_implementation_overrides += f"\t\t\t}},\n"
860 formatted_trait_docs = trait_doc_comment.replace("\n", "\n * ")
861 out_typescript_human = f"""
862 {self.hu_struct_file_prefix}
864 /** An implementation of {struct_name.replace("LDK","")} */
865 export interface {struct_name.replace("LDK", "")}Interface {{
866 {out_java_interface}}}
868 class {struct_name}Holder {{
869 held: {struct_name.replace("LDK", "")};
873 * {formatted_trait_docs}
875 export class {struct_name.replace("LDK","")} extends CommonBase {{
877 public bindings_instance?: bindings.{struct_name};
880 constructor(_dummy: object, ptr: number) {{
881 super(ptr, bindings.{struct_name.replace("LDK","")}_free);
882 this.bindings_instance = null;
885 /** Creates a new instance of {struct_name.replace("LDK","")} from a given implementation */
886 public static new_impl(arg: {struct_name.replace("LDK", "")}Interface{impl_constructor_arguments}): {struct_name.replace("LDK", "")} {{
887 const impl_holder: {struct_name}Holder = new {struct_name}Holder();
888 let structImplementation = {{
889 {out_interface_implementation_overrides} }} as bindings.{struct_name};
890 {super_constructor_statements} const ptr: number = bindings.{struct_name}_new(structImplementation{bindings_instantiator});
892 impl_holder.held = new {struct_name.replace("LDK", "")}(null, ptr);
893 impl_holder.held.bindings_instance = structImplementation;
894 {pointer_to_adder} return impl_holder.held;
898 self.obj_defined([struct_name.replace("LDK", ""), struct_name.replace("LDK", "") + "Interface"], "structs")
900 out_typescript_bindings += "/* @internal */\nexport interface " + struct_name + " {\n"
902 for fn_line in field_function_lines:
903 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
904 out_typescript_bindings += f"\t{fn_line.fn_name} ("
906 for idx, arg_conv_info in enumerate(fn_line.args_ty):
908 out_typescript_bindings = out_typescript_bindings + ", "
909 out_typescript_bindings += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
911 out_typescript_bindings += f"): {fn_line.ret_ty_info.java_ty};\n"
913 out_typescript_bindings += "}\n\n"
915 out_typescript_bindings += f"/* @internal */\nexport function {struct_name}_new(impl: {struct_name}"
916 for var in flattened_field_var_conversions:
917 if isinstance(var, ConvInfo):
918 out_typescript_bindings += f", {var.arg_name}: {var.java_ty}"
920 out_typescript_bindings += f", {var[1]}: {var[0]}"
922 out_typescript_bindings += f"""): number {{
923 if(!isWasmInitialized) {{
924 throw new Error("initializeWasm() must be awaited first!");
926 var new_obj_idx = js_objs.length;
927 for (var i = 0; i < js_objs.length; i++) {{
928 if (js_objs[i] == null || js_objs[i] == undefined) {{ new_obj_idx = i; break; }}
930 js_objs[i] = new WeakRef(impl);
931 return wasm.TS_{struct_name}_new(i);
935 # Now that we've written out our java code (and created java_meths), generate C
936 out_c = "typedef struct " + struct_name + "_JCalls {\n"
937 out_c += "\tatomic_size_t refcnt;\n"
938 out_c += "\tuint32_t instance_ptr;\n"
939 for var in flattened_field_var_conversions:
940 if isinstance(var, ConvInfo):
941 # We're a regular ol' field
945 out_c = out_c + "\t" + var[0] + "_JCalls* " + var[1] + ";\n"
946 out_c = out_c + "} " + struct_name + "_JCalls;\n"
948 for fn_line in field_function_lines:
949 if fn_line.fn_name == "free":
950 out_c = out_c + "static void " + struct_name + "_JCalls_free(void* this_arg) {\n"
951 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
952 out_c = out_c + "\tif (atomic_fetch_sub_explicit(&j_calls->refcnt, 1, memory_order_acquire) == 1) {\n"
953 out_c = out_c + "\t\tFREE(j_calls);\n"
954 out_c = out_c + "\t}\n}\n"
956 for idx, fn_line in enumerate(field_function_lines):
957 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
958 assert fn_line.ret_ty_info.ty_info.get_full_rust_ty()[1] == ""
959 out_c = out_c + fn_line.ret_ty_info.ty_info.get_full_rust_ty()[0] + " " + fn_line.fn_name + "_" + struct_name + "_jcall("
960 if fn_line.self_is_const:
961 out_c = out_c + "const void* this_arg"
963 out_c = out_c + "void* this_arg"
965 for idx, arg in enumerate(fn_line.args_ty):
966 out_c = out_c + ", " + arg.ty_info.get_full_rust_ty()[0] + " " + arg.arg_name + arg.ty_info.get_full_rust_ty()[1]
968 out_c = out_c + ") {\n"
969 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) this_arg;\n"
971 for arg_info in fn_line.args_ty:
972 if arg_info.ret_conv is not None:
973 out_c = out_c + "\t" + arg_info.ret_conv[0].replace('\n', '\n\t')
974 out_c = out_c + arg_info.arg_name
975 out_c = out_c + arg_info.ret_conv[1].replace('\n', '\n\t') + "\n"
977 if fn_line.ret_ty_info.c_ty.endswith("Array"):
978 out_c += "\t" + fn_line.ret_ty_info.c_ty + " ret = (" + fn_line.ret_ty_info.c_ty + ")"
979 out_c += "js_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
980 elif fn_line.ret_ty_info.java_ty == "void":
981 out_c = out_c + "\tjs_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
982 elif fn_line.ret_ty_info.java_hu_ty == "string":
983 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)
984 elif not fn_line.ret_ty_info.passed_as_ptr:
985 out_c = out_c + "\treturn js_invoke_function_" + str(len(fn_line.args_ty)) + "(j_calls->instance_ptr, " + str(self.function_ptr_counter)
987 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)
989 self.function_ptrs[self.function_ptr_counter] = (struct_name, fn_line.fn_name)
990 self.function_ptr_counter += 1
992 for idx, arg_info in enumerate(fn_line.args_ty):
993 if arg_info.ret_conv is not None:
994 out_c = out_c + ", (uint32_t)" + arg_info.ret_conv_name
996 out_c = out_c + ", (uint32_t)" + arg_info.arg_name
997 out_c = out_c + ");\n"
998 if fn_line.ret_ty_info.arg_conv is not None:
999 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"
1001 out_c = out_c + "}\n"
1003 # Write out a clone function whether we need one or not, as we use them in moving to rust
1004 out_c = out_c + "static void " + struct_name + "_JCalls_cloned(" + struct_name + "* new_obj) {\n"
1005 out_c = out_c + "\t" + struct_name + "_JCalls *j_calls = (" + struct_name + "_JCalls*) new_obj->this_arg;\n"
1006 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->refcnt, 1, memory_order_release);\n"
1007 for var in field_var_conversions:
1008 if not isinstance(var, ConvInfo):
1009 out_c = out_c + "\tatomic_fetch_add_explicit(&j_calls->" + var[1] + "->refcnt, 1, memory_order_release);\n"
1010 out_c = out_c + "}\n"
1012 out_c = out_c + "static inline " + struct_name + " " + struct_name + "_init (JSValue o"
1013 for var in flattened_field_var_conversions:
1014 if isinstance(var, ConvInfo):
1015 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
1017 out_c = out_c + ", JSValue " + var[1]
1018 out_c = out_c + ") {\n"
1020 out_c = out_c + "\t" + struct_name + "_JCalls *calls = MALLOC(sizeof(" + struct_name + "_JCalls), \"" + struct_name + "_JCalls\");\n"
1021 out_c = out_c + "\tatomic_init(&calls->refcnt, 1);\n"
1022 out_c = out_c + "\tcalls->instance_ptr = o;\n"
1024 for (fn_name, java_meth_descr) in java_meths:
1025 if fn_name != "free" and fn_name != "cloned":
1026 out_c = out_c + "\tcalls->" + fn_name + "_meth = (*env)->GetMethodID(env, c, \"" + fn_name + "\", \"" + java_meth_descr + "\");\n"
1027 out_c = out_c + "\tCHECK(calls->" + fn_name + "_meth != NULL);\n"
1029 for var in flattened_field_var_conversions:
1030 if isinstance(var, ConvInfo) and var.arg_conv is not None:
1031 out_c = out_c + "\n\t" + var.arg_conv.replace("\n", "\n\t") +"\n"
1032 out_c = out_c + "\n\t" + struct_name + " ret = {\n"
1033 out_c = out_c + "\t\t.this_arg = (void*) calls,\n"
1034 for fn_line in field_function_lines:
1035 if fn_line.fn_name != "free" and fn_line.fn_name != "cloned":
1036 out_c = out_c + "\t\t." + fn_line.fn_name + " = " + fn_line.fn_name + "_" + struct_name + "_jcall,\n"
1037 elif fn_line.fn_name == "free":
1038 out_c = out_c + "\t\t.free = " + struct_name + "_JCalls_free,\n"
1040 out_c = out_c + "\t\t.cloned = " + struct_name + "_JCalls_cloned,\n"
1041 for var in field_var_conversions:
1042 if isinstance(var, ConvInfo):
1043 if var.arg_conv_name is not None:
1044 out_c = out_c + "\t\t." + var.arg_name + " = " + var.arg_conv_name + ",\n"
1045 out_c = out_c + "\t\t.set_" + var.arg_name + " = NULL,\n"
1047 out_c = out_c + "\t\t." + var.var_name + " = " + var.var_name + ",\n"
1048 out_c = out_c + "\t\t.set_" + var.var_name + " = NULL,\n"
1050 out_c += "\t\t." + var[1] + " = " + var[0] + "_init(" + var[1]
1051 for suparg in var[2]:
1052 if isinstance(suparg, ConvInfo):
1053 out_c += ", " + suparg.arg_name
1055 out_c += ", " + suparg[1]
1057 out_c = out_c + "\t};\n"
1058 for var in flattened_field_var_conversions:
1059 if not isinstance(var, ConvInfo):
1060 out_c = out_c + "\tcalls->" + var[1] + " = ret." + var[1] + ".this_arg;\n"
1061 out_c = out_c + "\treturn ret;\n"
1062 out_c = out_c + "}\n"
1064 out_c = out_c + self.c_fn_ty_pfx + "long " + self.c_fn_name_define_pfx(struct_name + "_new", True) + "JSValue o"
1065 for var in flattened_field_var_conversions:
1066 if isinstance(var, ConvInfo):
1067 out_c = out_c + ", " + var.c_ty + " " + var.arg_name
1069 out_c = out_c + ", JSValue " + var[1]
1070 out_c = out_c + ") {\n"
1071 out_c = out_c + "\t" + struct_name + " *res_ptr = MALLOC(sizeof(" + struct_name + "), \"" + struct_name + "\");\n"
1072 out_c = out_c + "\t*res_ptr = " + struct_name + "_init(o"
1073 for var in flattened_field_var_conversions:
1074 if isinstance(var, ConvInfo):
1075 out_c = out_c + ", " + var.arg_name
1077 out_c = out_c + ", " + var[1]
1078 out_c = out_c + ");\n"
1079 out_c = out_c + "\treturn (long)res_ptr;\n"
1080 out_c = out_c + "}\n"
1082 return (out_typescript_bindings, out_typescript_human, out_c)
1084 def trait_struct_inc_refcnt(self, ty_info):
1087 def map_complex_enum(self, struct_name, variant_list, camel_to_snake, enum_doc_comment):
1088 bindings_type = struct_name.replace("LDK", "")
1089 java_hu_type = struct_name.replace("LDK", "").replace("COption", "Option")
1095 out_java_enum += (self.hu_struct_file_prefix)
1097 java_hu_class = "/**\n * " + enum_doc_comment.replace("\n", "\n * ") + "\n */\n"
1098 java_hu_class += "export class " + java_hu_type + " extends CommonBase {\n"
1099 java_hu_class += "\tprotected constructor(_dummy: object, ptr: number) { super(ptr, bindings." + bindings_type + "_free); }\n"
1100 java_hu_class += "\t/* @internal */\n"
1101 java_hu_class += f"\tpublic static constr_from_ptr(ptr: number): {java_hu_type} {{\n"
1102 java_hu_class += f"\t\tconst raw_ty: number = bindings." + struct_name + "_ty_from_ptr(ptr);\n"
1103 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"
1104 out_c += "\t" + struct_name + " *obj = (" + struct_name + "*)(ptr & ~1);\n"
1105 out_c += "\tswitch(obj->tag) {\n"
1106 java_hu_class += "\t\tswitch (raw_ty) {\n"
1107 java_hu_subclasses = ""
1109 out_java += "/* @internal */\nexport class " + struct_name + " {\n"
1110 out_java += "\tprotected constructor() {}\n"
1112 for var in variant_list:
1113 java_hu_subclasses += "/** A " + java_hu_type + " of type " + var.var_name + " */\n"
1114 java_hu_subclasses += "export class " + java_hu_type + "_" + var.var_name + " extends " + java_hu_type + " {\n"
1115 java_hu_class += f"\t\t\tcase {var_idx}: "
1116 java_hu_class += "return new " + java_hu_type + "_" + var.var_name + "(ptr);\n"
1117 out_c += f"\t\tcase {struct_name}_{var.var_name}: return {var_idx};\n"
1119 for idx, (field_ty, field_docs) in enumerate(var.fields):
1120 if field_docs is not None:
1121 java_hu_subclasses += "\t/**\n\t * " + field_docs.replace("\n", "\n\t * ") + "\n\t */\n"
1122 java_hu_subclasses += "\tpublic " + field_ty.arg_name + f": {field_ty.java_hu_ty};\n"
1123 if field_ty.to_hu_conv is not None:
1124 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"
1125 hu_conv_body += f"\t\t" + field_ty.to_hu_conv.replace("\n", "\n\t\t\t") + "\n"
1126 hu_conv_body += f"\t\tthis." + field_ty.arg_name + " = " + field_ty.to_hu_conv_name + ";\n"
1128 hu_conv_body += f"\t\tthis.{field_ty.arg_name} = bindings.{struct_name}_{var.var_name}_get_{field_ty.arg_name}(ptr);\n"
1129 java_hu_subclasses += "\t/* @internal */\n"
1130 java_hu_subclasses += "\tpublic constructor(ptr: number) {\n\t\tsuper(null, ptr);\n"
1131 java_hu_subclasses = java_hu_subclasses + hu_conv_body
1132 java_hu_subclasses = java_hu_subclasses + "\t}\n}\n"
1135 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"
1136 out_java += self.fn_call_body(struct_name + "_ty_from_ptr", "uint32_t", "number", "ptr: number", "ptr")
1137 out_c += ("\t\tdefault: abort();\n")
1138 out_c += ("\t}\n}\n")
1140 for var in variant_list:
1141 for idx, (field_map, _) in enumerate(var.fields):
1142 fn_name = f"{struct_name}_{var.var_name}_get_{field_map.arg_name}"
1143 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"
1144 out_c += "\t" + struct_name + " *obj = (" + struct_name + "*)(ptr & ~1);\n"
1145 out_c += f"\tassert(obj->tag == {struct_name}_{var.var_name});\n"
1146 if field_map.ret_conv is not None:
1147 out_c += ("\t\t\t" + field_map.ret_conv[0].replace("\n", "\n\t\t\t"))
1148 if var.tuple_variant:
1149 out_c += "obj->" + camel_to_snake(var.var_name)
1151 out_c += "obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name
1152 out_c += (field_map.ret_conv[1].replace("\n", "\n\t\t\t") + "\n")
1153 out_c += "\treturn " + field_map.ret_conv_name + ";\n"
1155 if var.tuple_variant:
1156 out_c += "\treturn " + "obj->" + camel_to_snake(var.var_name) + ";\n"
1158 out_c += "\treturn " + "obj->" + camel_to_snake(var.var_name) + "." + field_map.arg_name + ";\n"
1160 out_java += self.fn_call_body(fn_name, field_map.c_ty, field_map.java_ty, "ptr: number", "ptr")
1161 out_java_enum += java_hu_class
1162 self.struct_file_suffixes[java_hu_type] = java_hu_subclasses
1163 self.obj_defined([java_hu_type], "structs")
1164 return (out_java, out_java_enum, out_c)
1166 def map_opaque_struct(self, struct_name, struct_doc_comment):
1167 implementations = ""
1170 hu_name = struct_name.replace("LDKC2Tuple", "TwoTuple").replace("LDKC3Tuple", "ThreeTuple").replace("LDK", "")
1171 out_opaque_struct_human = f"{self.hu_struct_file_prefix}"
1172 if struct_name.startswith("LDKLocked"):
1173 out_opaque_struct_human += "/** XXX: DO NOT USE THIS - it remains locked until the GC runs (if that ever happens */"
1174 formatted_doc_comment = struct_doc_comment.replace("\n", "\n * ")
1175 out_opaque_struct_human += f"""
1177 * {formatted_doc_comment}
1179 export class {hu_name} extends CommonBase {implementations}{{
1181 public constructor(_dummy: object, ptr: number) {{
1182 super(ptr, bindings.{struct_name.replace("LDK","")}_free);
1186 self.obj_defined([hu_name], "structs")
1187 return out_opaque_struct_human
1189 def map_tuple(self, struct_name):
1190 return self.map_opaque_struct(struct_name, "A Tuple")
1192 def map_result(self, struct_name, res_map, err_map):
1193 human_ty = struct_name.replace("LDKCResult", "Result")
1195 suffixes = f"export class {human_ty}_OK extends {human_ty} {{\n"
1196 if res_map.java_hu_ty != "void":
1197 suffixes += "\tpublic res: " + res_map.java_hu_ty + ";\n"
1200 public constructor(_dummy: object, ptr: number) {{
1203 if res_map.java_hu_ty == "void":
1205 elif res_map.to_hu_conv is not None:
1206 suffixes += "\t\tconst res: " + res_map.java_ty + " = bindings." + struct_name.replace("LDK", "") + "_get_ok(ptr);\n"
1207 suffixes += "\t\t" + res_map.to_hu_conv.replace("\n", "\n\t\t")
1208 suffixes += "\n\t\tthis.res = " + res_map.to_hu_conv_name + ";\n"
1210 suffixes += "\t\tthis.res = bindings." + struct_name.replace("LDK", "") + "_get_ok(ptr);\n"
1211 suffixes += "\t}\n}\n"
1213 suffixes += f"export class {human_ty}_Err extends {human_ty} {{\n"
1214 if err_map.java_hu_ty != "void":
1215 suffixes += "\tpublic err: " + err_map.java_hu_ty + ";\n"
1218 public constructor(_dummy: object, ptr: number) {{
1221 if err_map.java_hu_ty == "void":
1223 elif err_map.to_hu_conv is not None:
1224 suffixes += "\t\tconst err: " + err_map.java_ty + " = bindings." + struct_name.replace("LDK", "") + "_get_err(ptr);\n"
1225 suffixes += "\t\t" + err_map.to_hu_conv.replace("\n", "\n\t\t")
1226 suffixes += "\n\t\tthis.err = " + err_map.to_hu_conv_name + ";\n"
1228 suffixes += "\t\tthis.err = bindings." + struct_name.replace("LDK", "") + "_get_err(ptr);\n"
1229 suffixes += "\t}\n}"
1231 self.struct_file_suffixes[human_ty] = suffixes
1232 self.obj_defined([human_ty], "structs")
1234 return f"""{self.hu_struct_file_prefix}
1236 export class {human_ty} extends CommonBase {{
1237 protected constructor(_dummy: object, ptr: number) {{
1238 super(ptr, bindings.{struct_name.replace("LDK","")}_free);
1241 public static constr_from_ptr(ptr: number): {human_ty} {{
1242 if (bindings.{struct_name.replace("LDK", "")}_is_ok(ptr)) {{
1243 return new {human_ty}_OK(null, ptr);
1245 return new {human_ty}_Err(null, ptr);
1250 def fn_call_body(self, method_name, return_c_ty, return_java_ty, method_argument_string, native_call_argument_string):
1251 has_return_value = return_c_ty != 'void'
1252 return_statement = 'return nativeResponseValue;'
1253 if not has_return_value:
1254 return_statement = '// debug statements here'
1256 return f"""/* @internal */
1257 export function {method_name}({method_argument_string}): {return_java_ty} {{
1258 if(!isWasmInitialized) {{
1259 throw new Error("initializeWasm() must be awaited first!");
1261 const nativeResponseValue = wasm.TS_{method_name}({native_call_argument_string});
1265 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):
1268 out_java_struct = None
1271 out_c += (self.c_fn_ty_pfx)
1272 out_c += (return_type_info.c_ty)
1273 out_java += (return_type_info.java_ty)
1274 if return_type_info.ret_conv is not None:
1275 ret_conv_pfx, ret_conv_sfx = return_type_info.ret_conv
1276 out_java += (" " + method_name + "(")
1277 out_c += (" " + self.c_fn_name_define_pfx(method_name, True))
1279 method_argument_string = ""
1280 native_call_argument_string = ""
1281 for idx, arg_conv_info in enumerate(argument_types):
1283 method_argument_string += (", ")
1284 native_call_argument_string += ', '
1286 if arg_conv_info.c_ty != "void":
1287 out_c += (arg_conv_info.c_ty + " " + arg_conv_info.arg_name)
1288 method_argument_string += f"{arg_conv_info.arg_name}: {arg_conv_info.java_ty}"
1289 native_call_argument_string += arg_conv_info.arg_name
1290 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)
1292 out_java_struct = ""
1293 if doc_comment is not None:
1294 out_java_struct = "\t/**\n\t * " + doc_comment.replace("\n", "\n\t * ") + "\n\t */\n"
1297 out_java_struct += ("\t// Skipped " + method_name + "\n")
1300 out_java_struct += (
1301 "\tpublic static constructor_" + meth_n + "(")
1303 out_java_struct += ("\tpublic " + meth_n + "(")
1304 for idx, arg in enumerate(argument_types):
1306 if not takes_self or idx > 1:
1307 out_java_struct += (", ")
1310 if arg.java_ty != "void":
1311 if arg.arg_name in default_constructor_args:
1312 for explode_idx, explode_arg in enumerate(default_constructor_args[arg.arg_name]):
1313 if explode_idx != 0:
1314 out_java_struct += (", ")
1315 out_java_struct += arg.arg_name + "_" + explode_arg.arg_name + ": " + explode_arg.java_hu_ty
1317 out_java_struct += arg.arg_name + ": " + arg.java_hu_ty
1320 if out_java_struct is not None:
1321 out_java_struct += "): " + return_type_info.java_hu_ty + " {\n"
1322 for info in argument_types:
1323 if info.arg_conv is not None:
1324 out_c += ("\t" + info.arg_conv.replace('\n', "\n\t") + "\n")
1325 if return_type_info.ret_conv is not None:
1326 out_c += ("\t" + ret_conv_pfx.replace('\n', '\n\t'))
1327 elif return_type_info.c_ty != "void":
1328 out_c += ("\t" + return_type_info.c_ty + " ret_val = ")
1331 if c_call_string is None:
1332 out_c += (method_name + "(")
1334 out_c += (c_call_string)
1335 for idx, info in enumerate(argument_types):
1336 if info.arg_conv_name is not None:
1339 elif c_call_string is not None:
1341 out_c += (info.arg_conv_name)
1343 if return_type_info.ret_conv is not None:
1344 out_c += (ret_conv_sfx.replace('\n', '\n\t'))
1347 for info in argument_types:
1348 if info.arg_conv_cleanup is not None:
1349 out_c += ("\n\t" + info.arg_conv_cleanup.replace("\n", "\n\t"))
1350 if return_type_info.ret_conv is not None:
1351 out_c += ("\n\treturn " + return_type_info.ret_conv_name + ";")
1352 elif return_type_info.c_ty != "void":
1353 out_c += ("\n\treturn ret_val;")
1354 out_c += ("\n}\n\n")
1357 out_java_struct += ("\t\t")
1358 if return_type_info.java_ty != "void":
1359 out_java_struct += "const ret: " + return_type_info.java_ty + " = "
1360 out_java_struct += ("bindings." + method_name + "(")
1361 for idx, info in enumerate(argument_types):
1363 out_java_struct += (", ")
1364 if idx == 0 and takes_self:
1365 out_java_struct += ("this.ptr")
1366 elif info.arg_name in default_constructor_args:
1367 out_java_struct += ("bindings." + info.java_hu_ty + "_new(")
1368 for explode_idx, explode_arg in enumerate(default_constructor_args[info.arg_name]):
1369 if explode_idx != 0:
1370 out_java_struct += (", ")
1371 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1372 if explode_arg.from_hu_conv is not None:
1373 out_java_struct += (
1374 explode_arg.from_hu_conv[0].replace(explode_arg.arg_name, expl_arg_name))
1376 out_java_struct += (expl_arg_name)
1377 out_java_struct += (")")
1378 elif info.from_hu_conv is not None:
1379 out_java_struct += (info.from_hu_conv[0])
1381 out_java_struct += (info.arg_name)
1382 out_java_struct += (");\n")
1383 if return_type_info.to_hu_conv is not None:
1385 out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t").replace("this",
1386 return_type_info.to_hu_conv_name) + "\n")
1388 out_java_struct += ("\t\t" + return_type_info.to_hu_conv.replace("\n", "\n\t\t") + "\n")
1390 for idx, info in enumerate(argument_types):
1391 if idx == 0 and takes_self:
1393 elif info.arg_name in default_constructor_args:
1394 for explode_arg in default_constructor_args[info.arg_name]:
1395 expl_arg_name = info.arg_name + "_" + explode_arg.arg_name
1396 if explode_arg.from_hu_conv is not None and return_type_info.to_hu_conv_name:
1397 out_java_struct += ("\t\t" + explode_arg.from_hu_conv[1].replace(explode_arg.arg_name,
1398 expl_arg_name).replace(
1399 "this", return_type_info.to_hu_conv_name) + ";\n")
1400 elif info.from_hu_conv is not None and info.from_hu_conv[1] != "":
1401 if not takes_self and return_type_info.to_hu_conv_name is not None:
1402 out_java_struct += (
1403 "\t\t" + info.from_hu_conv[1].replace("this", return_type_info.to_hu_conv_name).replace("\n", "\n\t\t") + ";\n")
1405 out_java_struct += ("\t\t" + info.from_hu_conv[1].replace("\n", "\n\t\t") + ";\n")
1407 if return_type_info.to_hu_conv_name is not None:
1408 out_java_struct += ("\t\treturn " + return_type_info.to_hu_conv_name + ";\n")
1409 elif return_type_info.java_ty != "void" and return_type_info.rust_obj != "LDK" + struct_meth:
1410 out_java_struct += ("\t\treturn ret;\n")
1411 out_java_struct += ("\t}\n\n")
1413 return (out_java, out_c, out_java_struct)
1416 for struct in self.struct_file_suffixes:
1417 with open(self.outdir + "/structs/" + struct + self.file_ext, "a") as src:
1418 src.write(self.struct_file_suffixes[struct])
1420 with open(self.outdir + "/bindings.mts", "a") as bindings:
1423 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) {
1424 const weak: WeakRef<object> = js_objs[obj_ptr];
1425 if (weak == null || weak == undefined) {
1426 console.error("Got function call on unknown/free'd JS object!");
1427 throw new Error("Got function call on unknown/free'd JS object!");
1429 const obj: object = weak.deref();
1430 if (obj == null || obj == undefined) {
1431 console.error("Got function call on GC'd JS object!");
1432 throw new Error("Got function call on GC'd JS object!");
1436 bindings.write("\tswitch (fn_id) {\n")
1437 for f in self.function_ptrs:
1438 bindings.write(f"\t\tcase {str(f)}: fn = Object.getOwnPropertyDescriptor(obj, \"{self.function_ptrs[f][1]}\"); break;\n")
1440 bindings.write("""\t\tdefault:
1441 console.error("Got unknown function call from C!");
1442 throw new Error("Got unknown function call from C!");
1444 if (fn == null || fn == undefined) {
1445 console.error("Got function call on incorrect JS object!");
1446 throw new Error("Got function call on incorrect JS object!");
1448 return fn.value.bind(obj)(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10);